Merge branch 'master1' of https://github.com/HorrorTroll/Ryujinx into TextureRG16

This commit is contained in:
HorrorTroll 2018-12-06 20:16:27 +07:00
commit 4e525a8631
419 changed files with 21302 additions and 13096 deletions

View file

@ -18,7 +18,7 @@ namespace ChocolArm64
private int _isExecuting; private int _isExecuting;
public CpuThread(Translator translator, MemoryManager memory, long entryPoint) public CpuThread(Translator translator, MemoryManager memory, long entrypoint)
{ {
_translator = translator; _translator = translator;
Memory = memory; Memory = memory;
@ -31,7 +31,7 @@ namespace ChocolArm64
Work = new Thread(delegate() Work = new Thread(delegate()
{ {
translator.ExecuteSubroutine(this, entryPoint); translator.ExecuteSubroutine(this, entrypoint);
memory.RemoveMonitor(ThreadState.Core); memory.RemoveMonitor(ThreadState.Core);

View file

@ -10,8 +10,8 @@ namespace ChocolArm64.Decoders
public OpCodeSimdFcond64(Inst inst, long position, int opCode) : base(inst, position, opCode) public OpCodeSimdFcond64(Inst inst, long position, int opCode) : base(inst, position, opCode)
{ {
Nzcv = (opCode >> 0) & 0xf; Nzcv = (opCode >> 0) & 0xf;
Cond = (Cond)((opCode >> 12) & 0xf); Cond = (Cond)((opCode >> 12) & 0xf);
} }
} }
} }

View file

@ -1,13 +0,0 @@
using System;
namespace ChocolArm64.Exceptions
{
public class VmmAccessException : Exception
{
private const string ExMsg = "Memory region at 0x{0} with size 0x{1} is not contiguous!";
public VmmAccessException() { }
public VmmAccessException(long position, long size) : base(string.Format(ExMsg, position, size)) { }
}
}

View file

@ -1638,7 +1638,34 @@ namespace ChocolArm64.Instructions
public static void Neg_V(ILEmitterCtx context) public static void Neg_V(ILEmitterCtx context)
{ {
EmitVectorUnaryOpSx(context, () => context.Emit(OpCodes.Neg)); if (Optimizations.UseSse2)
{
OpCodeSimd64 op = (OpCodeSimd64)context.CurrOp;
Type[] typesSub = new Type[] { VectorIntTypesPerSizeLog2[op.Size], VectorIntTypesPerSizeLog2[op.Size] };
string[] namesSzv = new string[] { nameof(VectorHelper.VectorSByteZero),
nameof(VectorHelper.VectorInt16Zero),
nameof(VectorHelper.VectorInt32Zero),
nameof(VectorHelper.VectorInt64Zero) };
VectorHelper.EmitCall(context, namesSzv[op.Size]);
EmitLdvecWithSignedCast(context, op.Rn, op.Size);
context.EmitCall(typeof(Sse2).GetMethod(nameof(Sse2.Subtract), typesSub));
EmitStvecWithSignedCast(context, op.Rd, op.Size);
if (op.RegisterSize == RegisterSize.Simd64)
{
EmitVectorZeroUpper(context, op.Rd);
}
}
else
{
EmitVectorUnaryOpSx(context, () => context.Emit(OpCodes.Neg));
}
} }
public static void Raddhn_V(ILEmitterCtx context) public static void Raddhn_V(ILEmitterCtx context)

View file

@ -3,6 +3,7 @@ using ChocolArm64.State;
using ChocolArm64.Translation; using ChocolArm64.Translation;
using System; using System;
using System.Reflection.Emit; using System.Reflection.Emit;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86; using System.Runtime.Intrinsics.X86;
using static ChocolArm64.Instructions.InstEmitSimdHelper; using static ChocolArm64.Instructions.InstEmitSimdHelper;
@ -29,18 +30,14 @@ namespace ChocolArm64.Instructions
{ {
OpCodeSimdReg64 op = (OpCodeSimdReg64)context.CurrOp; OpCodeSimdReg64 op = (OpCodeSimdReg64)context.CurrOp;
EmitLdvecWithUnsignedCast(context, op.Rm, op.Size); Type[] typesAndNot = new Type[] { typeof(Vector128<byte>), typeof(Vector128<byte>) };
EmitLdvecWithUnsignedCast(context, op.Rn, op.Size);
Type[] types = new Type[] EmitLdvecWithUnsignedCast(context, op.Rm, 0);
{ EmitLdvecWithUnsignedCast(context, op.Rn, 0);
VectorUIntTypesPerSizeLog2[op.Size],
VectorUIntTypesPerSizeLog2[op.Size]
};
context.EmitCall(typeof(Sse2).GetMethod(nameof(Sse2.AndNot), types)); context.EmitCall(typeof(Sse2).GetMethod(nameof(Sse2.AndNot), typesAndNot));
EmitStvecWithUnsignedCast(context, op.Rd, op.Size); EmitStvecWithUnsignedCast(context, op.Rd, 0);
if (op.RegisterSize == RegisterSize.Simd64) if (op.RegisterSize == RegisterSize.Simd64)
{ {
@ -68,41 +65,34 @@ namespace ChocolArm64.Instructions
public static void Bif_V(ILEmitterCtx context) public static void Bif_V(ILEmitterCtx context)
{ {
EmitBitBif(context, true); EmitBifBit(context, notRm: true);
} }
public static void Bit_V(ILEmitterCtx context) public static void Bit_V(ILEmitterCtx context)
{ {
EmitBitBif(context, false); EmitBifBit(context, notRm: false);
} }
private static void EmitBitBif(ILEmitterCtx context, bool notRm) private static void EmitBifBit(ILEmitterCtx context, bool notRm)
{ {
OpCodeSimdReg64 op = (OpCodeSimdReg64)context.CurrOp; OpCodeSimdReg64 op = (OpCodeSimdReg64)context.CurrOp;
if (Optimizations.UseSse2) if (Optimizations.UseSse2)
{ {
Type[] types = new Type[] Type[] typesXorAndNot = new Type[] { typeof(Vector128<byte>), typeof(Vector128<byte>) };
{
VectorUIntTypesPerSizeLog2[op.Size],
VectorUIntTypesPerSizeLog2[op.Size]
};
EmitLdvecWithUnsignedCast(context, op.Rm, op.Size); string nameAndNot = notRm ? nameof(Sse2.AndNot) : nameof(Sse2.And);
EmitLdvecWithUnsignedCast(context, op.Rd, op.Size);
EmitLdvecWithUnsignedCast(context, op.Rn, op.Size);
context.EmitCall(typeof(Sse2).GetMethod(nameof(Sse2.Xor), types)); EmitLdvecWithUnsignedCast(context, op.Rd, 0);
EmitLdvecWithUnsignedCast(context, op.Rm, 0);
EmitLdvecWithUnsignedCast(context, op.Rn, 0);
EmitLdvecWithUnsignedCast(context, op.Rd, 0);
string name = notRm ? nameof(Sse2.AndNot) : nameof(Sse2.And); context.EmitCall(typeof(Sse2).GetMethod(nameof(Sse2.Xor), typesXorAndNot));
context.EmitCall(typeof(Sse2).GetMethod(nameAndNot, typesXorAndNot));
context.EmitCall(typeof(Sse2).GetMethod(nameof(Sse2.Xor), typesXorAndNot));
context.EmitCall(typeof(Sse2).GetMethod(name, types)); EmitStvecWithUnsignedCast(context, op.Rd, 0);
EmitLdvecWithUnsignedCast(context, op.Rd, op.Size);
context.EmitCall(typeof(Sse2).GetMethod(nameof(Sse2.Xor), types));
EmitStvecWithUnsignedCast(context, op.Rd, op.Size);
if (op.RegisterSize == RegisterSize.Simd64) if (op.RegisterSize == RegisterSize.Simd64)
{ {
@ -111,17 +101,18 @@ namespace ChocolArm64.Instructions
} }
else else
{ {
int bytes = op.GetBitsCount() >> 3; int elems = op.RegisterSize == RegisterSize.Simd128 ? 2 : 1;
int elems = bytes >> op.Size;
for (int index = 0; index < elems; index++) for (int index = 0; index < elems; index++)
{ {
EmitVectorExtractZx(context, op.Rd, index, op.Size); EmitVectorExtractZx(context, op.Rd, index, 3);
EmitVectorExtractZx(context, op.Rn, index, op.Size); context.Emit(OpCodes.Dup);
EmitVectorExtractZx(context, op.Rn, index, 3);
context.Emit(OpCodes.Xor); context.Emit(OpCodes.Xor);
EmitVectorExtractZx(context, op.Rm, index, op.Size); EmitVectorExtractZx(context, op.Rm, index, 3);
if (notRm) if (notRm)
{ {
@ -130,11 +121,9 @@ namespace ChocolArm64.Instructions
context.Emit(OpCodes.And); context.Emit(OpCodes.And);
EmitVectorExtractZx(context, op.Rd, index, op.Size);
context.Emit(OpCodes.Xor); context.Emit(OpCodes.Xor);
EmitVectorInsert(context, op.Rd, index, op.Size); EmitVectorInsert(context, op.Rd, index, 3);
} }
if (op.RegisterSize == RegisterSize.Simd64) if (op.RegisterSize == RegisterSize.Simd64)
@ -150,26 +139,22 @@ namespace ChocolArm64.Instructions
{ {
OpCodeSimdReg64 op = (OpCodeSimdReg64)context.CurrOp; OpCodeSimdReg64 op = (OpCodeSimdReg64)context.CurrOp;
Type[] types = new Type[] Type[] typesXorAnd = new Type[] { typeof(Vector128<byte>), typeof(Vector128<byte>) };
{
VectorUIntTypesPerSizeLog2[op.Size],
VectorUIntTypesPerSizeLog2[op.Size]
};
EmitLdvecWithUnsignedCast(context, op.Rn, op.Size); EmitLdvecWithUnsignedCast(context, op.Rm, 0);
EmitLdvecWithUnsignedCast(context, op.Rm, op.Size); context.Emit(OpCodes.Dup);
context.EmitCall(typeof(Sse2).GetMethod(nameof(Sse2.Xor), types)); EmitLdvecWithUnsignedCast(context, op.Rn, 0);
EmitLdvecWithUnsignedCast(context, op.Rd, op.Size); context.EmitCall(typeof(Sse2).GetMethod(nameof(Sse2.Xor), typesXorAnd));
context.EmitCall(typeof(Sse2).GetMethod(nameof(Sse2.And), types)); EmitLdvecWithUnsignedCast(context, op.Rd, 0);
EmitLdvecWithUnsignedCast(context, op.Rm, op.Size); context.EmitCall(typeof(Sse2).GetMethod(nameof(Sse2.And), typesXorAnd));
context.EmitCall(typeof(Sse2).GetMethod(nameof(Sse2.Xor), types)); context.EmitCall(typeof(Sse2).GetMethod(nameof(Sse2.Xor), typesXorAnd));
EmitStvecWithUnsignedCast(context, op.Rd, op.Size); EmitStvecWithUnsignedCast(context, op.Rd, 0);
if (op.RegisterSize == RegisterSize.Simd64) if (op.RegisterSize == RegisterSize.Simd64)
{ {
@ -207,16 +192,66 @@ namespace ChocolArm64.Instructions
public static void Not_V(ILEmitterCtx context) public static void Not_V(ILEmitterCtx context)
{ {
EmitVectorUnaryOpZx(context, () => context.Emit(OpCodes.Not)); if (Optimizations.UseSse2)
{
OpCodeSimd64 op = (OpCodeSimd64)context.CurrOp;
Type[] typesSav = new Type[] { typeof(byte) };
Type[] typesAndNot = new Type[] { typeof(Vector128<byte>), typeof(Vector128<byte>) };
EmitLdvecWithUnsignedCast(context, op.Rn, 0);
context.EmitLdc_I4(byte.MaxValue);
context.EmitCall(typeof(Sse2).GetMethod(nameof(Sse2.SetAllVector128), typesSav));
context.EmitCall(typeof(Sse2).GetMethod(nameof(Sse2.AndNot), typesAndNot));
EmitStvecWithUnsignedCast(context, op.Rd, 0);
if (op.RegisterSize == RegisterSize.Simd64)
{
EmitVectorZeroUpper(context, op.Rd);
}
}
else
{
EmitVectorUnaryOpZx(context, () => context.Emit(OpCodes.Not));
}
} }
public static void Orn_V(ILEmitterCtx context) public static void Orn_V(ILEmitterCtx context)
{ {
EmitVectorBinaryOpZx(context, () => if (Optimizations.UseSse2)
{ {
context.Emit(OpCodes.Not); OpCodeSimdReg64 op = (OpCodeSimdReg64)context.CurrOp;
context.Emit(OpCodes.Or);
}); Type[] typesSav = new Type[] { typeof(byte) };
Type[] typesAndNotOr = new Type[] { typeof(Vector128<byte>), typeof(Vector128<byte>) };
EmitLdvecWithUnsignedCast(context, op.Rn, 0);
EmitLdvecWithUnsignedCast(context, op.Rm, 0);
context.EmitLdc_I4(byte.MaxValue);
context.EmitCall(typeof(Sse2).GetMethod(nameof(Sse2.SetAllVector128), typesSav));
context.EmitCall(typeof(Sse2).GetMethod(nameof(Sse2.AndNot), typesAndNotOr));
context.EmitCall(typeof(Sse2).GetMethod(nameof(Sse2.Or), typesAndNotOr));
EmitStvecWithUnsignedCast(context, op.Rd, 0);
if (op.RegisterSize == RegisterSize.Simd64)
{
EmitVectorZeroUpper(context, op.Rd);
}
}
else
{
EmitVectorBinaryOpZx(context, () =>
{
context.Emit(OpCodes.Not);
context.Emit(OpCodes.Or);
});
}
} }
public static void Orr_V(ILEmitterCtx context) public static void Orr_V(ILEmitterCtx context)
@ -263,28 +298,122 @@ namespace ChocolArm64.Instructions
public static void Rev16_V(ILEmitterCtx context) public static void Rev16_V(ILEmitterCtx context)
{ {
EmitRev_V(context, containerSize: 1); if (Optimizations.UseSsse3)
{
OpCodeSimd64 op = (OpCodeSimd64)context.CurrOp;
Type[] typesSve = new Type[] { typeof(long), typeof(long) };
Type[] typesSfl = new Type[] { typeof(Vector128<sbyte>), typeof(Vector128<sbyte>) };
EmitLdvecWithSignedCast(context, op.Rn, 0); // value
context.EmitLdc_I8(14L << 56 | 15L << 48 | 12L << 40 | 13L << 32 | 10L << 24 | 11L << 16 | 08L << 8 | 09L << 0); // maskE1
context.EmitLdc_I8(06L << 56 | 07L << 48 | 04L << 40 | 05L << 32 | 02L << 24 | 03L << 16 | 00L << 8 | 01L << 0); // maskE0
context.EmitCall(typeof(Sse2).GetMethod(nameof(Sse2.SetVector128), typesSve));
context.EmitCall(typeof(Ssse3).GetMethod(nameof(Ssse3.Shuffle), typesSfl));
EmitStvecWithSignedCast(context, op.Rd, 0);
if (op.RegisterSize == RegisterSize.Simd64)
{
EmitVectorZeroUpper(context, op.Rd);
}
}
else
{
EmitRev_V(context, containerSize: 1);
}
} }
public static void Rev32_V(ILEmitterCtx context) public static void Rev32_V(ILEmitterCtx context)
{ {
EmitRev_V(context, containerSize: 2); if (Optimizations.UseSsse3)
{
OpCodeSimd64 op = (OpCodeSimd64)context.CurrOp;
Type[] typesSve = new Type[] { typeof(long), typeof(long) };
Type[] typesSfl = new Type[] { typeof(Vector128<sbyte>), typeof(Vector128<sbyte>) };
EmitLdvecWithSignedCast(context, op.Rn, op.Size); // value
if (op.Size == 0)
{
context.EmitLdc_I8(12L << 56 | 13L << 48 | 14L << 40 | 15L << 32 | 08L << 24 | 09L << 16 | 10L << 8 | 11L << 0); // maskE1
context.EmitLdc_I8(04L << 56 | 05L << 48 | 06L << 40 | 07L << 32 | 00L << 24 | 01L << 16 | 02L << 8 | 03L << 0); // maskE0
}
else /* if (op.Size == 1) */
{
context.EmitLdc_I8(13L << 56 | 12L << 48 | 15L << 40 | 14L << 32 | 09L << 24 | 08L << 16 | 11L << 8 | 10L << 0); // maskE1
context.EmitLdc_I8(05L << 56 | 04L << 48 | 07L << 40 | 06L << 32 | 01L << 24 | 00L << 16 | 03L << 8 | 02L << 0); // maskE0
}
context.EmitCall(typeof(Sse2).GetMethod(nameof(Sse2.SetVector128), typesSve));
context.EmitCall(typeof(Ssse3).GetMethod(nameof(Ssse3.Shuffle), typesSfl));
EmitStvecWithSignedCast(context, op.Rd, op.Size);
if (op.RegisterSize == RegisterSize.Simd64)
{
EmitVectorZeroUpper(context, op.Rd);
}
}
else
{
EmitRev_V(context, containerSize: 2);
}
} }
public static void Rev64_V(ILEmitterCtx context) public static void Rev64_V(ILEmitterCtx context)
{ {
EmitRev_V(context, containerSize: 3); if (Optimizations.UseSsse3)
{
OpCodeSimd64 op = (OpCodeSimd64)context.CurrOp;
Type[] typesSve = new Type[] { typeof(long), typeof(long) };
Type[] typesSfl = new Type[] { typeof(Vector128<sbyte>), typeof(Vector128<sbyte>) };
EmitLdvecWithSignedCast(context, op.Rn, op.Size); // value
if (op.Size == 0)
{
context.EmitLdc_I8(08L << 56 | 09L << 48 | 10L << 40 | 11L << 32 | 12L << 24 | 13L << 16 | 14L << 8 | 15L << 0); // maskE1
context.EmitLdc_I8(00L << 56 | 01L << 48 | 02L << 40 | 03L << 32 | 04L << 24 | 05L << 16 | 06L << 8 | 07L << 0); // maskE0
}
else if (op.Size == 1)
{
context.EmitLdc_I8(09L << 56 | 08L << 48 | 11L << 40 | 10L << 32 | 13L << 24 | 12L << 16 | 15L << 8 | 14L << 0); // maskE1
context.EmitLdc_I8(01L << 56 | 00L << 48 | 03L << 40 | 02L << 32 | 05L << 24 | 04L << 16 | 07L << 8 | 06L << 0); // maskE0
}
else /* if (op.Size == 2) */
{
context.EmitLdc_I8(11L << 56 | 10L << 48 | 09L << 40 | 08L << 32 | 15L << 24 | 14L << 16 | 13L << 8 | 12L << 0); // maskE1
context.EmitLdc_I8(03L << 56 | 02L << 48 | 01L << 40 | 00L << 32 | 07L << 24 | 06L << 16 | 05L << 8 | 04L << 0); // maskE0
}
context.EmitCall(typeof(Sse2).GetMethod(nameof(Sse2.SetVector128), typesSve));
context.EmitCall(typeof(Ssse3).GetMethod(nameof(Ssse3.Shuffle), typesSfl));
EmitStvecWithSignedCast(context, op.Rd, op.Size);
if (op.RegisterSize == RegisterSize.Simd64)
{
EmitVectorZeroUpper(context, op.Rd);
}
}
else
{
EmitRev_V(context, containerSize: 3);
}
} }
private static void EmitRev_V(ILEmitterCtx context, int containerSize) private static void EmitRev_V(ILEmitterCtx context, int containerSize)
{ {
OpCodeSimd64 op = (OpCodeSimd64)context.CurrOp; OpCodeSimd64 op = (OpCodeSimd64)context.CurrOp;
if (op.Size >= containerSize)
{
throw new InvalidOperationException();
}
int bytes = op.GetBitsCount() >> 3; int bytes = op.GetBitsCount() >> 3;
int elems = bytes >> op.Size; int elems = bytes >> op.Size;

View file

@ -110,6 +110,34 @@ namespace ChocolArm64.Instructions
} }
} }
public static void Sqrshl_V(ILEmitterCtx context)
{
OpCodeSimdReg64 op = (OpCodeSimdReg64)context.CurrOp;
int bytes = op.GetBitsCount() >> 3;
int elems = bytes >> op.Size;
for (int index = 0; index < elems; index++)
{
EmitVectorExtractSx(context, op.Rn, index, op.Size);
EmitVectorExtractSx(context, op.Rm, index, op.Size);
context.Emit(OpCodes.Ldc_I4_1);
context.EmitLdc_I4(op.Size);
context.EmitLdarg(TranslatedSub.StateArgIdx);
SoftFallback.EmitCall(context, nameof(SoftFallback.SignedShlRegSatQ));
EmitVectorInsert(context, op.Rd, index, op.Size);
}
if (op.RegisterSize == RegisterSize.Simd64)
{
EmitVectorZeroUpper(context, op.Rd);
}
}
public static void Sqrshrn_S(ILEmitterCtx context) public static void Sqrshrn_S(ILEmitterCtx context)
{ {
EmitRoundShrImmSaturatingNarrowOp(context, ShrImmSaturatingNarrowFlags.ScalarSxSx); EmitRoundShrImmSaturatingNarrowOp(context, ShrImmSaturatingNarrowFlags.ScalarSxSx);
@ -130,6 +158,34 @@ namespace ChocolArm64.Instructions
EmitRoundShrImmSaturatingNarrowOp(context, ShrImmSaturatingNarrowFlags.VectorSxZx); EmitRoundShrImmSaturatingNarrowOp(context, ShrImmSaturatingNarrowFlags.VectorSxZx);
} }
public static void Sqshl_V(ILEmitterCtx context)
{
OpCodeSimdReg64 op = (OpCodeSimdReg64)context.CurrOp;
int bytes = op.GetBitsCount() >> 3;
int elems = bytes >> op.Size;
for (int index = 0; index < elems; index++)
{
EmitVectorExtractSx(context, op.Rn, index, op.Size);
EmitVectorExtractSx(context, op.Rm, index, op.Size);
context.Emit(OpCodes.Ldc_I4_0);
context.EmitLdc_I4(op.Size);
context.EmitLdarg(TranslatedSub.StateArgIdx);
SoftFallback.EmitCall(context, nameof(SoftFallback.SignedShlRegSatQ));
EmitVectorInsert(context, op.Rd, index, op.Size);
}
if (op.RegisterSize == RegisterSize.Simd64)
{
EmitVectorZeroUpper(context, op.Rd);
}
}
public static void Sqshrn_S(ILEmitterCtx context) public static void Sqshrn_S(ILEmitterCtx context)
{ {
EmitShrImmSaturatingNarrowOp(context, ShrImmSaturatingNarrowFlags.ScalarSxSx); EmitShrImmSaturatingNarrowOp(context, ShrImmSaturatingNarrowFlags.ScalarSxSx);
@ -150,6 +206,32 @@ namespace ChocolArm64.Instructions
EmitShrImmSaturatingNarrowOp(context, ShrImmSaturatingNarrowFlags.VectorSxZx); EmitShrImmSaturatingNarrowOp(context, ShrImmSaturatingNarrowFlags.VectorSxZx);
} }
public static void Srshl_V(ILEmitterCtx context)
{
OpCodeSimdReg64 op = (OpCodeSimdReg64)context.CurrOp;
int bytes = op.GetBitsCount() >> 3;
int elems = bytes >> op.Size;
for (int index = 0; index < elems; index++)
{
EmitVectorExtractSx(context, op.Rn, index, op.Size);
EmitVectorExtractSx(context, op.Rm, index, op.Size);
context.Emit(OpCodes.Ldc_I4_1);
context.EmitLdc_I4(op.Size);
SoftFallback.EmitCall(context, nameof(SoftFallback.SignedShlReg));
EmitVectorInsert(context, op.Rd, index, op.Size);
}
if (op.RegisterSize == RegisterSize.Simd64)
{
EmitVectorZeroUpper(context, op.Rd);
}
}
public static void Srshr_S(ILEmitterCtx context) public static void Srshr_S(ILEmitterCtx context)
{ {
EmitScalarShrImmOpSx(context, ShrImmFlags.Round); EmitScalarShrImmOpSx(context, ShrImmFlags.Round);
@ -252,7 +334,28 @@ namespace ChocolArm64.Instructions
public static void Sshl_V(ILEmitterCtx context) public static void Sshl_V(ILEmitterCtx context)
{ {
EmitVectorShl(context, signed: true); OpCodeSimdReg64 op = (OpCodeSimdReg64)context.CurrOp;
int bytes = op.GetBitsCount() >> 3;
int elems = bytes >> op.Size;
for (int index = 0; index < elems; index++)
{
EmitVectorExtractSx(context, op.Rn, index, op.Size);
EmitVectorExtractSx(context, op.Rm, index, op.Size);
context.Emit(OpCodes.Ldc_I4_0);
context.EmitLdc_I4(op.Size);
SoftFallback.EmitCall(context, nameof(SoftFallback.SignedShlReg));
EmitVectorInsert(context, op.Rd, index, op.Size);
}
if (op.RegisterSize == RegisterSize.Simd64)
{
EmitVectorZeroUpper(context, op.Rd);
}
} }
public static void Sshll_V(ILEmitterCtx context) public static void Sshll_V(ILEmitterCtx context)
@ -330,6 +433,34 @@ namespace ChocolArm64.Instructions
} }
} }
public static void Uqrshl_V(ILEmitterCtx context)
{
OpCodeSimdReg64 op = (OpCodeSimdReg64)context.CurrOp;
int bytes = op.GetBitsCount() >> 3;
int elems = bytes >> op.Size;
for (int index = 0; index < elems; index++)
{
EmitVectorExtractZx(context, op.Rn, index, op.Size);
EmitVectorExtractZx(context, op.Rm, index, op.Size);
context.Emit(OpCodes.Ldc_I4_1);
context.EmitLdc_I4(op.Size);
context.EmitLdarg(TranslatedSub.StateArgIdx);
SoftFallback.EmitCall(context, nameof(SoftFallback.UnsignedShlRegSatQ));
EmitVectorInsert(context, op.Rd, index, op.Size);
}
if (op.RegisterSize == RegisterSize.Simd64)
{
EmitVectorZeroUpper(context, op.Rd);
}
}
public static void Uqrshrn_S(ILEmitterCtx context) public static void Uqrshrn_S(ILEmitterCtx context)
{ {
EmitRoundShrImmSaturatingNarrowOp(context, ShrImmSaturatingNarrowFlags.ScalarZxZx); EmitRoundShrImmSaturatingNarrowOp(context, ShrImmSaturatingNarrowFlags.ScalarZxZx);
@ -340,6 +471,34 @@ namespace ChocolArm64.Instructions
EmitRoundShrImmSaturatingNarrowOp(context, ShrImmSaturatingNarrowFlags.VectorZxZx); EmitRoundShrImmSaturatingNarrowOp(context, ShrImmSaturatingNarrowFlags.VectorZxZx);
} }
public static void Uqshl_V(ILEmitterCtx context)
{
OpCodeSimdReg64 op = (OpCodeSimdReg64)context.CurrOp;
int bytes = op.GetBitsCount() >> 3;
int elems = bytes >> op.Size;
for (int index = 0; index < elems; index++)
{
EmitVectorExtractZx(context, op.Rn, index, op.Size);
EmitVectorExtractZx(context, op.Rm, index, op.Size);
context.Emit(OpCodes.Ldc_I4_0);
context.EmitLdc_I4(op.Size);
context.EmitLdarg(TranslatedSub.StateArgIdx);
SoftFallback.EmitCall(context, nameof(SoftFallback.UnsignedShlRegSatQ));
EmitVectorInsert(context, op.Rd, index, op.Size);
}
if (op.RegisterSize == RegisterSize.Simd64)
{
EmitVectorZeroUpper(context, op.Rd);
}
}
public static void Uqshrn_S(ILEmitterCtx context) public static void Uqshrn_S(ILEmitterCtx context)
{ {
EmitShrImmSaturatingNarrowOp(context, ShrImmSaturatingNarrowFlags.ScalarZxZx); EmitShrImmSaturatingNarrowOp(context, ShrImmSaturatingNarrowFlags.ScalarZxZx);
@ -350,6 +509,32 @@ namespace ChocolArm64.Instructions
EmitShrImmSaturatingNarrowOp(context, ShrImmSaturatingNarrowFlags.VectorZxZx); EmitShrImmSaturatingNarrowOp(context, ShrImmSaturatingNarrowFlags.VectorZxZx);
} }
public static void Urshl_V(ILEmitterCtx context)
{
OpCodeSimdReg64 op = (OpCodeSimdReg64)context.CurrOp;
int bytes = op.GetBitsCount() >> 3;
int elems = bytes >> op.Size;
for (int index = 0; index < elems; index++)
{
EmitVectorExtractZx(context, op.Rn, index, op.Size);
EmitVectorExtractZx(context, op.Rm, index, op.Size);
context.Emit(OpCodes.Ldc_I4_1);
context.EmitLdc_I4(op.Size);
SoftFallback.EmitCall(context, nameof(SoftFallback.UnsignedShlReg));
EmitVectorInsert(context, op.Rd, index, op.Size);
}
if (op.RegisterSize == RegisterSize.Simd64)
{
EmitVectorZeroUpper(context, op.Rd);
}
}
public static void Urshr_S(ILEmitterCtx context) public static void Urshr_S(ILEmitterCtx context)
{ {
EmitScalarShrImmOpZx(context, ShrImmFlags.Round); EmitScalarShrImmOpZx(context, ShrImmFlags.Round);
@ -450,7 +635,28 @@ namespace ChocolArm64.Instructions
public static void Ushl_V(ILEmitterCtx context) public static void Ushl_V(ILEmitterCtx context)
{ {
EmitVectorShl(context, signed: false); OpCodeSimdReg64 op = (OpCodeSimdReg64)context.CurrOp;
int bytes = op.GetBitsCount() >> 3;
int elems = bytes >> op.Size;
for (int index = 0; index < elems; index++)
{
EmitVectorExtractZx(context, op.Rn, index, op.Size);
EmitVectorExtractZx(context, op.Rm, index, op.Size);
context.Emit(OpCodes.Ldc_I4_0);
context.EmitLdc_I4(op.Size);
SoftFallback.EmitCall(context, nameof(SoftFallback.UnsignedShlReg));
EmitVectorInsert(context, op.Rd, index, op.Size);
}
if (op.RegisterSize == RegisterSize.Simd64)
{
EmitVectorZeroUpper(context, op.Rd);
}
} }
public static void Ushll_V(ILEmitterCtx context) public static void Ushll_V(ILEmitterCtx context)
@ -526,69 +732,6 @@ namespace ChocolArm64.Instructions
} }
} }
private static void EmitVectorShl(ILEmitterCtx context, bool signed)
{
//This instruction shifts the value on vector A by the number of bits
//specified on the signed, lower 8 bits of vector B. If the shift value
//is greater or equal to the data size of each lane, then the result is zero.
//Additionally, negative shifts produces right shifts by the negated shift value.
OpCodeSimd64 op = (OpCodeSimd64)context.CurrOp;
int maxShift = 8 << op.Size;
Action emit = () =>
{
ILLabel lblShl = new ILLabel();
ILLabel lblZero = new ILLabel();
ILLabel lblEnd = new ILLabel();
void EmitShift(OpCode ilOp)
{
context.Emit(OpCodes.Dup);
context.EmitLdc_I4(maxShift);
context.Emit(OpCodes.Bge_S, lblZero);
context.Emit(ilOp);
context.Emit(OpCodes.Br_S, lblEnd);
}
context.Emit(OpCodes.Conv_I1);
context.Emit(OpCodes.Dup);
context.EmitLdc_I4(0);
context.Emit(OpCodes.Bge_S, lblShl);
context.Emit(OpCodes.Neg);
EmitShift(signed
? OpCodes.Shr
: OpCodes.Shr_Un);
context.MarkLabel(lblShl);
EmitShift(OpCodes.Shl);
context.MarkLabel(lblZero);
context.Emit(OpCodes.Pop);
context.Emit(OpCodes.Pop);
context.EmitLdc_I8(0);
context.MarkLabel(lblEnd);
};
if (signed)
{
EmitVectorBinaryOpSx(context, emit);
}
else
{
EmitVectorBinaryOpZx(context, emit);
}
}
[Flags] [Flags]
private enum ShrImmFlags private enum ShrImmFlags
{ {

View file

@ -16,6 +16,283 @@ namespace ChocolArm64.Instructions
context.EmitCall(typeof(SoftFallback), mthdName); context.EmitCall(typeof(SoftFallback), mthdName);
} }
#region "ShlReg"
public static long SignedShlReg(long value, long shift, bool round, int size)
{
int eSize = 8 << size;
int shiftLsB = (sbyte)shift;
if (shiftLsB < 0)
{
return SignedShrReg(value, -shiftLsB, round, eSize);
}
else if (shiftLsB > 0)
{
if (shiftLsB >= eSize)
{
return 0L;
}
return value << shiftLsB;
}
else /* if (shiftLsB == 0) */
{
return value;
}
}
public static ulong UnsignedShlReg(ulong value, ulong shift, bool round, int size)
{
int eSize = 8 << size;
int shiftLsB = (sbyte)shift;
if (shiftLsB < 0)
{
return UnsignedShrReg(value, -shiftLsB, round, eSize);
}
else if (shiftLsB > 0)
{
if (shiftLsB >= eSize)
{
return 0UL;
}
return value << shiftLsB;
}
else /* if (shiftLsB == 0) */
{
return value;
}
}
public static long SignedShlRegSatQ(long value, long shift, bool round, int size, CpuThreadState state)
{
int eSize = 8 << size;
int shiftLsB = (sbyte)shift;
if (shiftLsB < 0)
{
return SignedShrReg(value, -shiftLsB, round, eSize);
}
else if (shiftLsB > 0)
{
if (shiftLsB >= eSize)
{
return SignedSignSatQ(value, eSize, state);
}
if (eSize == 64)
{
long shl = value << shiftLsB;
long shr = shl >> shiftLsB;
if (shr != value)
{
return SignedSignSatQ(value, eSize, state);
}
else /* if (shr == value) */
{
return shl;
}
}
else /* if (eSize != 64) */
{
return SignedSrcSignedDstSatQ(value << shiftLsB, size, state);
}
}
else /* if (shiftLsB == 0) */
{
return value;
}
}
public static ulong UnsignedShlRegSatQ(ulong value, ulong shift, bool round, int size, CpuThreadState state)
{
int eSize = 8 << size;
int shiftLsB = (sbyte)shift;
if (shiftLsB < 0)
{
return UnsignedShrReg(value, -shiftLsB, round, eSize);
}
else if (shiftLsB > 0)
{
if (shiftLsB >= eSize)
{
return UnsignedSignSatQ(value, eSize, state);
}
if (eSize == 64)
{
ulong shl = value << shiftLsB;
ulong shr = shl >> shiftLsB;
if (shr != value)
{
return UnsignedSignSatQ(value, eSize, state);
}
else /* if (shr == value) */
{
return shl;
}
}
else /* if (eSize != 64) */
{
return UnsignedSrcUnsignedDstSatQ(value << shiftLsB, size, state);
}
}
else /* if (shiftLsB == 0) */
{
return value;
}
}
private static long SignedShrReg(long value, int shift, bool round, int eSize) // shift := [1, 128]; eSize := {8, 16, 32, 64}.
{
if (round)
{
if (shift >= eSize)
{
return 0L;
}
long roundConst = 1L << (shift - 1);
long add = value + roundConst;
if (eSize == 64)
{
if ((~value & (value ^ add)) < 0L)
{
return (long)((ulong)add >> shift);
}
else
{
return add >> shift;
}
}
else /* if (eSize != 64) */
{
return add >> shift;
}
}
else /* if (!round) */
{
if (shift >= eSize)
{
if (value < 0L)
{
return -1L;
}
else /* if (value >= 0L) */
{
return 0L;
}
}
return value >> shift;
}
}
private static ulong UnsignedShrReg(ulong value, int shift, bool round, int eSize) // shift := [1, 128]; eSize := {8, 16, 32, 64}.
{
if (round)
{
if (shift > 64)
{
return 0UL;
}
ulong roundConst = 1UL << (shift - 1);
ulong add = value + roundConst;
if (eSize == 64)
{
if ((add < value) && (add < roundConst))
{
if (shift == 64)
{
return 1UL;
}
return (add >> shift) | (0x8000000000000000UL >> (shift - 1));
}
else
{
if (shift == 64)
{
return 0UL;
}
return add >> shift;
}
}
else /* if (eSize != 64) */
{
if (shift == 64)
{
return 0UL;
}
return add >> shift;
}
}
else /* if (!round) */
{
if (shift >= eSize)
{
return 0UL;
}
return value >> shift;
}
}
private static long SignedSignSatQ(long op, int eSize, CpuThreadState state) // eSize := {8, 16, 32, 64}.
{
long tMaxValue = (1L << (eSize - 1)) - 1L;
long tMinValue = -(1L << (eSize - 1));
if (op > 0L)
{
state.SetFpsrFlag(Fpsr.Qc);
return tMaxValue;
}
else if (op < 0L)
{
state.SetFpsrFlag(Fpsr.Qc);
return tMinValue;
}
else
{
return 0L;
}
}
private static ulong UnsignedSignSatQ(ulong op, int eSize, CpuThreadState state) // eSize := {8, 16, 32, 64}.
{
ulong tMaxValue = ulong.MaxValue >> (64 - eSize);
if (op > 0UL)
{
state.SetFpsrFlag(Fpsr.Qc);
return tMaxValue;
}
else
{
return 0UL;
}
}
#endregion
#region "ShrImm64" #region "ShrImm64"
public static long SignedShrImm64(long value, long roundConst, int shift) public static long SignedShrImm64(long value, long roundConst, int shift)
{ {
@ -31,7 +308,7 @@ namespace ChocolArm64.Instructions
{ {
return -1L; return -1L;
} }
else else /* if (value >= 0L) */
{ {
return 0L; return 0L;
} }

View file

@ -26,22 +26,26 @@ namespace ChocolArm64.Memory
{ {
long size = Marshal.SizeOf<T>(); long size = Marshal.SizeOf<T>();
memory.EnsureRangeIsValid(position, size); byte[] data = memory.ReadBytes(position, size);
IntPtr ptr = (IntPtr)memory.Translate(position); fixed (byte* ptr = data)
{
return Marshal.PtrToStructure<T>(ptr); return Marshal.PtrToStructure<T>((IntPtr)ptr);
}
} }
public unsafe static void Write<T>(MemoryManager memory, long position, T value) where T : struct public unsafe static void Write<T>(MemoryManager memory, long position, T value) where T : struct
{ {
long size = Marshal.SizeOf<T>(); long size = Marshal.SizeOf<T>();
memory.EnsureRangeIsValid(position, size); byte[] data = new byte[size];
IntPtr ptr = (IntPtr)memory.TranslateWrite(position); fixed (byte* ptr = data)
{
Marshal.StructureToPtr<T>(value, (IntPtr)ptr, false);
}
Marshal.StructureToPtr<T>(value, ptr, false); memory.WriteBytes(position, data);
} }
public static string ReadAsciiString(MemoryManager memory, long position, long maxSize = -1) public static string ReadAsciiString(MemoryManager memory, long position, long maxSize = -1)

View file

@ -1,5 +1,6 @@
using ChocolArm64.Events; using ChocolArm64.Events;
using ChocolArm64.Exceptions; using ChocolArm64.Exceptions;
using ChocolArm64.Instructions;
using ChocolArm64.State; using ChocolArm64.State;
using System; using System;
using System.Collections.Concurrent; using System.Collections.Concurrent;
@ -197,17 +198,41 @@ namespace ChocolArm64.Memory
public ushort ReadUInt16(long position) public ushort ReadUInt16(long position)
{ {
return *((ushort*)Translate(position)); if ((position & 1) == 0)
{
return *((ushort*)Translate(position));
}
else
{
return (ushort)(ReadByte(position + 0) << 0 |
ReadByte(position + 1) << 8);
}
} }
public uint ReadUInt32(long position) public uint ReadUInt32(long position)
{ {
return *((uint*)Translate(position)); if ((position & 3) == 0)
{
return *((uint*)Translate(position));
}
else
{
return (uint)(ReadUInt16(position + 0) << 0 |
ReadUInt16(position + 2) << 16);
}
} }
public ulong ReadUInt64(long position) public ulong ReadUInt64(long position)
{ {
return *((ulong*)Translate(position)); if ((position & 7) == 0)
{
return *((ulong*)Translate(position));
}
else
{
return (ulong)ReadUInt32(position + 0) << 0 |
(ulong)ReadUInt32(position + 4) << 32;
}
} }
public Vector128<float> ReadVector8(long position) public Vector128<float> ReadVector8(long position)
@ -218,74 +243,117 @@ namespace ChocolArm64.Memory
} }
else else
{ {
throw new PlatformNotSupportedException(); Vector128<float> value = VectorHelper.VectorSingleZero();
value = VectorHelper.VectorInsertInt(ReadByte(position), value, 0, 0);
return value;
} }
} }
[MethodImpl(MethodImplOptions.AggressiveInlining)] [MethodImpl(MethodImplOptions.AggressiveInlining)]
public Vector128<float> ReadVector16(long position) public Vector128<float> ReadVector16(long position)
{ {
if (Sse2.IsSupported) if (Sse2.IsSupported && (position & 1) == 0)
{ {
return Sse.StaticCast<ushort, float>(Sse2.Insert(Sse2.SetZeroVector128<ushort>(), ReadUInt16(position), 0)); return Sse.StaticCast<ushort, float>(Sse2.Insert(Sse2.SetZeroVector128<ushort>(), ReadUInt16(position), 0));
} }
else else
{ {
throw new PlatformNotSupportedException(); Vector128<float> value = VectorHelper.VectorSingleZero();
value = VectorHelper.VectorInsertInt(ReadUInt16(position), value, 0, 1);
return value;
} }
} }
[MethodImpl(MethodImplOptions.AggressiveInlining)] [MethodImpl(MethodImplOptions.AggressiveInlining)]
public Vector128<float> ReadVector32(long position) public Vector128<float> ReadVector32(long position)
{ {
if (Sse.IsSupported) if (Sse.IsSupported && (position & 3) == 0)
{ {
return Sse.LoadScalarVector128((float*)Translate(position)); return Sse.LoadScalarVector128((float*)Translate(position));
} }
else else
{ {
throw new PlatformNotSupportedException(); Vector128<float> value = VectorHelper.VectorSingleZero();
value = VectorHelper.VectorInsertInt(ReadUInt32(position), value, 0, 2);
return value;
} }
} }
[MethodImpl(MethodImplOptions.AggressiveInlining)] [MethodImpl(MethodImplOptions.AggressiveInlining)]
public Vector128<float> ReadVector64(long position) public Vector128<float> ReadVector64(long position)
{ {
if (Sse2.IsSupported) if (Sse2.IsSupported && (position & 7) == 0)
{ {
return Sse.StaticCast<double, float>(Sse2.LoadScalarVector128((double*)Translate(position))); return Sse.StaticCast<double, float>(Sse2.LoadScalarVector128((double*)Translate(position)));
} }
else else
{ {
throw new PlatformNotSupportedException(); Vector128<float> value = VectorHelper.VectorSingleZero();
value = VectorHelper.VectorInsertInt(ReadUInt64(position), value, 0, 3);
return value;
} }
} }
[MethodImpl(MethodImplOptions.AggressiveInlining)] [MethodImpl(MethodImplOptions.AggressiveInlining)]
public Vector128<float> ReadVector128(long position) public Vector128<float> ReadVector128(long position)
{ {
if (Sse.IsSupported) if (Sse.IsSupported && (position & 15) == 0)
{ {
return Sse.LoadVector128((float*)Translate(position)); return Sse.LoadVector128((float*)Translate(position));
} }
else else
{ {
throw new PlatformNotSupportedException(); Vector128<float> value = VectorHelper.VectorSingleZero();
value = VectorHelper.VectorInsertInt(ReadUInt64(position + 0), value, 0, 3);
value = VectorHelper.VectorInsertInt(ReadUInt64(position + 8), value, 1, 3);
return value;
} }
} }
public byte[] ReadBytes(long position, long size) public byte[] ReadBytes(long position, long size)
{ {
if ((uint)size > int.MaxValue) long endAddr = position + size;
if ((ulong)size > int.MaxValue)
{ {
throw new ArgumentOutOfRangeException(nameof(size)); throw new ArgumentOutOfRangeException(nameof(size));
} }
EnsureRangeIsValid(position, size); if ((ulong)endAddr < (ulong)position)
{
throw new ArgumentOutOfRangeException(nameof(position));
}
byte[] data = new byte[size]; byte[] data = new byte[size];
Marshal.Copy((IntPtr)Translate(position), data, 0, (int)size); int offset = 0;
while ((ulong)position < (ulong)endAddr)
{
long pageLimit = (position + PageSize) & ~(long)PageMask;
if ((ulong)pageLimit > (ulong)endAddr)
{
pageLimit = endAddr;
}
int copySize = (int)(pageLimit - position);
Marshal.Copy((IntPtr)Translate(position), data, offset, copySize);
position += copySize;
offset += copySize;
}
return data; return data;
} }
@ -293,9 +361,36 @@ namespace ChocolArm64.Memory
public void ReadBytes(long position, byte[] data, int startIndex, int size) public void ReadBytes(long position, byte[] data, int startIndex, int size)
{ {
//Note: This will be moved later. //Note: This will be moved later.
EnsureRangeIsValid(position, (uint)size); long endAddr = position + size;
Marshal.Copy((IntPtr)Translate(position), data, startIndex, size); if ((ulong)size > int.MaxValue)
{
throw new ArgumentOutOfRangeException(nameof(size));
}
if ((ulong)endAddr < (ulong)position)
{
throw new ArgumentOutOfRangeException(nameof(position));
}
int offset = startIndex;
while ((ulong)position < (ulong)endAddr)
{
long pageLimit = (position + PageSize) & ~(long)PageMask;
if ((ulong)pageLimit > (ulong)endAddr)
{
pageLimit = endAddr;
}
int copySize = (int)(pageLimit - position);
Marshal.Copy((IntPtr)Translate(position), data, offset, copySize);
position += copySize;
offset += copySize;
}
} }
public void WriteSByte(long position, sbyte value) public void WriteSByte(long position, sbyte value)
@ -325,17 +420,41 @@ namespace ChocolArm64.Memory
public void WriteUInt16(long position, ushort value) public void WriteUInt16(long position, ushort value)
{ {
*((ushort*)TranslateWrite(position)) = value; if ((position & 1) == 0)
{
*((ushort*)TranslateWrite(position)) = value;
}
else
{
WriteByte(position + 0, (byte)(value >> 0));
WriteByte(position + 1, (byte)(value >> 8));
}
} }
public void WriteUInt32(long position, uint value) public void WriteUInt32(long position, uint value)
{ {
*((uint*)TranslateWrite(position)) = value; if ((position & 3) == 0)
{
*((uint*)TranslateWrite(position)) = value;
}
else
{
WriteUInt16(position + 0, (ushort)(value >> 0));
WriteUInt16(position + 2, (ushort)(value >> 16));
}
} }
public void WriteUInt64(long position, ulong value) public void WriteUInt64(long position, ulong value)
{ {
*((ulong*)TranslateWrite(position)) = value; if ((position & 7) == 0)
{
*((ulong*)TranslateWrite(position)) = value;
}
else
{
WriteUInt32(position + 0, (uint)(value >> 0));
WriteUInt32(position + 4, (uint)(value >> 32));
}
} }
[MethodImpl(MethodImplOptions.AggressiveInlining)] [MethodImpl(MethodImplOptions.AggressiveInlining)]
@ -351,7 +470,7 @@ namespace ChocolArm64.Memory
} }
else else
{ {
throw new PlatformNotSupportedException(); WriteByte(position, (byte)VectorHelper.VectorExtractIntZx(value, 0, 0));
} }
} }
@ -364,46 +483,47 @@ namespace ChocolArm64.Memory
} }
else else
{ {
throw new PlatformNotSupportedException(); WriteUInt16(position, (ushort)VectorHelper.VectorExtractIntZx(value, 0, 1));
} }
} }
[MethodImpl(MethodImplOptions.AggressiveInlining)] [MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteVector32(long position, Vector128<float> value) public void WriteVector32(long position, Vector128<float> value)
{ {
if (Sse.IsSupported) if (Sse.IsSupported && (position & 3) == 0)
{ {
Sse.StoreScalar((float*)TranslateWrite(position), value); Sse.StoreScalar((float*)TranslateWrite(position), value);
} }
else else
{ {
throw new PlatformNotSupportedException(); WriteUInt32(position, (uint)VectorHelper.VectorExtractIntZx(value, 0, 2));
} }
} }
[MethodImpl(MethodImplOptions.AggressiveInlining)] [MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteVector64(long position, Vector128<float> value) public void WriteVector64(long position, Vector128<float> value)
{ {
if (Sse2.IsSupported) if (Sse2.IsSupported && (position & 7) == 0)
{ {
Sse2.StoreScalar((double*)TranslateWrite(position), Sse.StaticCast<float, double>(value)); Sse2.StoreScalar((double*)TranslateWrite(position), Sse.StaticCast<float, double>(value));
} }
else else
{ {
throw new PlatformNotSupportedException(); WriteUInt64(position, VectorHelper.VectorExtractIntZx(value, 0, 3));
} }
} }
[MethodImpl(MethodImplOptions.AggressiveInlining)] [MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteVector128(long position, Vector128<float> value) public void WriteVector128(long position, Vector128<float> value)
{ {
if (Sse.IsSupported) if (Sse.IsSupported && (position & 15) == 0)
{ {
Sse.Store((float*)TranslateWrite(position), value); Sse.Store((float*)TranslateWrite(position), value);
} }
else else
{ {
throw new PlatformNotSupportedException(); WriteUInt64(position + 0, VectorHelper.VectorExtractIntZx(value, 0, 3));
WriteUInt64(position + 8, VectorHelper.VectorExtractIntZx(value, 1, 3));
} }
} }
@ -439,22 +559,48 @@ namespace ChocolArm64.Memory
public void WriteBytes(long position, byte[] data, int startIndex, int size) public void WriteBytes(long position, byte[] data, int startIndex, int size)
{ {
//Note: This will be moved later. //Note: This will be moved later.
//Using Translate instead of TranslateWrite is on purpose. long endAddr = position + size;
EnsureRangeIsValid(position, (uint)size);
Marshal.Copy(data, startIndex, (IntPtr)Translate(position), size); if ((ulong)endAddr < (ulong)position)
{
throw new ArgumentOutOfRangeException(nameof(position));
}
int offset = startIndex;
while ((ulong)position < (ulong)endAddr)
{
long pageLimit = (position + PageSize) & ~(long)PageMask;
if ((ulong)pageLimit > (ulong)endAddr)
{
pageLimit = endAddr;
}
int copySize = (int)(pageLimit - position);
Marshal.Copy(data, offset, (IntPtr)TranslateWrite(position), copySize);
position += copySize;
offset += copySize;
}
} }
public void CopyBytes(long src, long dst, long size) public void CopyBytes(long src, long dst, long size)
{ {
//Note: This will be moved later. //Note: This will be moved later.
EnsureRangeIsValid(src, size); if (IsContiguous(src, size) &&
EnsureRangeIsValid(dst, size); IsContiguous(dst, size))
{
byte* srcPtr = Translate(src);
byte* dstPtr = TranslateWrite(dst);
byte* srcPtr = Translate(src); Buffer.MemoryCopy(srcPtr, dstPtr, size, size);
byte* dstPtr = TranslateWrite(dst); }
else
Buffer.MemoryCopy(srcPtr, dstPtr, size, size); {
WriteBytes(dst, ReadBytes(src, size));
}
} }
public void Map(long va, long pa, long size) public void Map(long va, long pa, long size)
@ -703,14 +849,21 @@ Unmapped:
} }
} }
public IntPtr GetHostAddress(long position, long size) public bool TryGetHostAddress(long position, long size, out IntPtr ptr)
{ {
EnsureRangeIsValid(position, size); if (IsContiguous(position, size))
{
ptr = (IntPtr)Translate(position);
return (IntPtr)Translate(position); return true;
}
ptr = IntPtr.Zero;
return false;
} }
internal void EnsureRangeIsValid(long position, long size) private bool IsContiguous(long position, long size)
{ {
long endPos = position + size; long endPos = position + size;
@ -724,12 +877,14 @@ Unmapped:
if (pa != expectedPa) if (pa != expectedPa)
{ {
throw new VmmAccessException(position, size); return false;
} }
position += PageSize; position += PageSize;
expectedPa += PageSize; expectedPa += PageSize;
} }
return true;
} }
public bool IsValidPosition(long position) public bool IsValidPosition(long position)

View file

@ -427,10 +427,12 @@ namespace ChocolArm64
SetA64("01111110101xxxxx101101xxxxxxxxxx", InstEmit.Sqrdmulh_S, typeof(OpCodeSimdReg64)); SetA64("01111110101xxxxx101101xxxxxxxxxx", InstEmit.Sqrdmulh_S, typeof(OpCodeSimdReg64));
SetA64("0x101110011xxxxx101101xxxxxxxxxx", InstEmit.Sqrdmulh_V, typeof(OpCodeSimdReg64)); SetA64("0x101110011xxxxx101101xxxxxxxxxx", InstEmit.Sqrdmulh_V, typeof(OpCodeSimdReg64));
SetA64("0x101110101xxxxx101101xxxxxxxxxx", InstEmit.Sqrdmulh_V, typeof(OpCodeSimdReg64)); SetA64("0x101110101xxxxx101101xxxxxxxxxx", InstEmit.Sqrdmulh_V, typeof(OpCodeSimdReg64));
SetA64("0>001110<<1xxxxx010111xxxxxxxxxx", InstEmit.Sqrshl_V, typeof(OpCodeSimdReg64));
SetA64("0101111100>>>xxx100111xxxxxxxxxx", InstEmit.Sqrshrn_S, typeof(OpCodeSimdShImm64)); SetA64("0101111100>>>xxx100111xxxxxxxxxx", InstEmit.Sqrshrn_S, typeof(OpCodeSimdShImm64));
SetA64("0x00111100>>>xxx100111xxxxxxxxxx", InstEmit.Sqrshrn_V, typeof(OpCodeSimdShImm64)); SetA64("0x00111100>>>xxx100111xxxxxxxxxx", InstEmit.Sqrshrn_V, typeof(OpCodeSimdShImm64));
SetA64("0111111100>>>xxx100011xxxxxxxxxx", InstEmit.Sqrshrun_S, typeof(OpCodeSimdShImm64)); SetA64("0111111100>>>xxx100011xxxxxxxxxx", InstEmit.Sqrshrun_S, typeof(OpCodeSimdShImm64));
SetA64("0x10111100>>>xxx100011xxxxxxxxxx", InstEmit.Sqrshrun_V, typeof(OpCodeSimdShImm64)); SetA64("0x10111100>>>xxx100011xxxxxxxxxx", InstEmit.Sqrshrun_V, typeof(OpCodeSimdShImm64));
SetA64("0>001110<<1xxxxx010011xxxxxxxxxx", InstEmit.Sqshl_V, typeof(OpCodeSimdReg64));
SetA64("0101111100>>>xxx100101xxxxxxxxxx", InstEmit.Sqshrn_S, typeof(OpCodeSimdShImm64)); SetA64("0101111100>>>xxx100101xxxxxxxxxx", InstEmit.Sqshrn_S, typeof(OpCodeSimdShImm64));
SetA64("0x00111100>>>xxx100101xxxxxxxxxx", InstEmit.Sqshrn_V, typeof(OpCodeSimdShImm64)); SetA64("0x00111100>>>xxx100101xxxxxxxxxx", InstEmit.Sqshrn_V, typeof(OpCodeSimdShImm64));
SetA64("0111111100>>>xxx100001xxxxxxxxxx", InstEmit.Sqshrun_S, typeof(OpCodeSimdShImm64)); SetA64("0111111100>>>xxx100001xxxxxxxxxx", InstEmit.Sqshrun_S, typeof(OpCodeSimdShImm64));
@ -442,6 +444,7 @@ namespace ChocolArm64
SetA64("01111110<<100001001010xxxxxxxxxx", InstEmit.Sqxtun_S, typeof(OpCodeSimd64)); SetA64("01111110<<100001001010xxxxxxxxxx", InstEmit.Sqxtun_S, typeof(OpCodeSimd64));
SetA64("0x101110<<100001001010xxxxxxxxxx", InstEmit.Sqxtun_V, typeof(OpCodeSimd64)); SetA64("0x101110<<100001001010xxxxxxxxxx", InstEmit.Sqxtun_V, typeof(OpCodeSimd64));
SetA64("0x001110<<1xxxxx000101xxxxxxxxxx", InstEmit.Srhadd_V, typeof(OpCodeSimdReg64)); SetA64("0x001110<<1xxxxx000101xxxxxxxxxx", InstEmit.Srhadd_V, typeof(OpCodeSimdReg64));
SetA64("0>001110<<1xxxxx010101xxxxxxxxxx", InstEmit.Srshl_V, typeof(OpCodeSimdReg64));
SetA64("0101111101xxxxxx001001xxxxxxxxxx", InstEmit.Srshr_S, typeof(OpCodeSimdShImm64)); SetA64("0101111101xxxxxx001001xxxxxxxxxx", InstEmit.Srshr_S, typeof(OpCodeSimdShImm64));
SetA64("0x00111100>>>xxx001001xxxxxxxxxx", InstEmit.Srshr_V, typeof(OpCodeSimdShImm64)); SetA64("0x00111100>>>xxx001001xxxxxxxxxx", InstEmit.Srshr_V, typeof(OpCodeSimdShImm64));
SetA64("0100111101xxxxxx001001xxxxxxxxxx", InstEmit.Srshr_V, typeof(OpCodeSimdShImm64)); SetA64("0100111101xxxxxx001001xxxxxxxxxx", InstEmit.Srshr_V, typeof(OpCodeSimdShImm64));
@ -501,8 +504,10 @@ namespace ChocolArm64
SetA64("0x101110<<1xxxxx110000xxxxxxxxxx", InstEmit.Umull_V, typeof(OpCodeSimdReg64)); SetA64("0x101110<<1xxxxx110000xxxxxxxxxx", InstEmit.Umull_V, typeof(OpCodeSimdReg64));
SetA64("01111110xx1xxxxx000011xxxxxxxxxx", InstEmit.Uqadd_S, typeof(OpCodeSimdReg64)); SetA64("01111110xx1xxxxx000011xxxxxxxxxx", InstEmit.Uqadd_S, typeof(OpCodeSimdReg64));
SetA64("0>101110<<1xxxxx000011xxxxxxxxxx", InstEmit.Uqadd_V, typeof(OpCodeSimdReg64)); SetA64("0>101110<<1xxxxx000011xxxxxxxxxx", InstEmit.Uqadd_V, typeof(OpCodeSimdReg64));
SetA64("0>101110<<1xxxxx010111xxxxxxxxxx", InstEmit.Uqrshl_V, typeof(OpCodeSimdReg64));
SetA64("0111111100>>>xxx100111xxxxxxxxxx", InstEmit.Uqrshrn_S, typeof(OpCodeSimdShImm64)); SetA64("0111111100>>>xxx100111xxxxxxxxxx", InstEmit.Uqrshrn_S, typeof(OpCodeSimdShImm64));
SetA64("0x10111100>>>xxx100111xxxxxxxxxx", InstEmit.Uqrshrn_V, typeof(OpCodeSimdShImm64)); SetA64("0x10111100>>>xxx100111xxxxxxxxxx", InstEmit.Uqrshrn_V, typeof(OpCodeSimdShImm64));
SetA64("0>101110<<1xxxxx010011xxxxxxxxxx", InstEmit.Uqshl_V, typeof(OpCodeSimdReg64));
SetA64("0111111100>>>xxx100101xxxxxxxxxx", InstEmit.Uqshrn_S, typeof(OpCodeSimdShImm64)); SetA64("0111111100>>>xxx100101xxxxxxxxxx", InstEmit.Uqshrn_S, typeof(OpCodeSimdShImm64));
SetA64("0x10111100>>>xxx100101xxxxxxxxxx", InstEmit.Uqshrn_V, typeof(OpCodeSimdShImm64)); SetA64("0x10111100>>>xxx100101xxxxxxxxxx", InstEmit.Uqshrn_V, typeof(OpCodeSimdShImm64));
SetA64("01111110xx1xxxxx001011xxxxxxxxxx", InstEmit.Uqsub_S, typeof(OpCodeSimdReg64)); SetA64("01111110xx1xxxxx001011xxxxxxxxxx", InstEmit.Uqsub_S, typeof(OpCodeSimdReg64));
@ -510,6 +515,7 @@ namespace ChocolArm64
SetA64("01111110<<100001010010xxxxxxxxxx", InstEmit.Uqxtn_S, typeof(OpCodeSimd64)); SetA64("01111110<<100001010010xxxxxxxxxx", InstEmit.Uqxtn_S, typeof(OpCodeSimd64));
SetA64("0x101110<<100001010010xxxxxxxxxx", InstEmit.Uqxtn_V, typeof(OpCodeSimd64)); SetA64("0x101110<<100001010010xxxxxxxxxx", InstEmit.Uqxtn_V, typeof(OpCodeSimd64));
SetA64("0x101110<<1xxxxx000101xxxxxxxxxx", InstEmit.Urhadd_V, typeof(OpCodeSimdReg64)); SetA64("0x101110<<1xxxxx000101xxxxxxxxxx", InstEmit.Urhadd_V, typeof(OpCodeSimdReg64));
SetA64("0>101110<<1xxxxx010101xxxxxxxxxx", InstEmit.Urshl_V, typeof(OpCodeSimdReg64));
SetA64("0111111101xxxxxx001001xxxxxxxxxx", InstEmit.Urshr_S, typeof(OpCodeSimdShImm64)); SetA64("0111111101xxxxxx001001xxxxxxxxxx", InstEmit.Urshr_S, typeof(OpCodeSimdShImm64));
SetA64("0x10111100>>>xxx001001xxxxxxxxxx", InstEmit.Urshr_V, typeof(OpCodeSimdShImm64)); SetA64("0x10111100>>>xxx001001xxxxxxxxxx", InstEmit.Urshr_V, typeof(OpCodeSimdShImm64));
SetA64("0110111101xxxxxx001001xxxxxxxxxx", InstEmit.Urshr_V, typeof(OpCodeSimdShImm64)); SetA64("0110111101xxxxxx001001xxxxxxxxxx", InstEmit.Urshr_V, typeof(OpCodeSimdShImm64));

View file

@ -8,11 +8,13 @@ public static class Optimizations
private static bool _useSseIfAvailable = true; private static bool _useSseIfAvailable = true;
private static bool _useSse2IfAvailable = true; private static bool _useSse2IfAvailable = true;
private static bool _useSsse3IfAvailable = true;
private static bool _useSse41IfAvailable = true; private static bool _useSse41IfAvailable = true;
private static bool _useSse42IfAvailable = true; private static bool _useSse42IfAvailable = true;
internal static bool UseSse = (_useAllSseIfAvailable && _useSseIfAvailable) && Sse.IsSupported; internal static bool UseSse = (_useAllSseIfAvailable && _useSseIfAvailable) && Sse.IsSupported;
internal static bool UseSse2 = (_useAllSseIfAvailable && _useSse2IfAvailable) && Sse2.IsSupported; internal static bool UseSse2 = (_useAllSseIfAvailable && _useSse2IfAvailable) && Sse2.IsSupported;
internal static bool UseSsse3 = (_useAllSseIfAvailable && _useSsse3IfAvailable) && Ssse3.IsSupported;
internal static bool UseSse41 = (_useAllSseIfAvailable && _useSse41IfAvailable) && Sse41.IsSupported; internal static bool UseSse41 = (_useAllSseIfAvailable && _useSse41IfAvailable) && Sse41.IsSupported;
internal static bool UseSse42 = (_useAllSseIfAvailable && _useSse42IfAvailable) && Sse42.IsSupported; internal static bool UseSse42 = (_useAllSseIfAvailable && _useSse42IfAvailable) && Sse42.IsSupported;
} }

104
Ryujinx.Common/BitUtils.cs Normal file
View file

@ -0,0 +1,104 @@
namespace Ryujinx.Common
{
public static class BitUtils
{
public static int AlignUp(int Value, int Size)
{
return (Value + (Size - 1)) & -Size;
}
public static ulong AlignUp(ulong Value, int Size)
{
return (ulong)AlignUp((long)Value, Size);
}
public static long AlignUp(long Value, int Size)
{
return (Value + (Size - 1)) & -(long)Size;
}
public static int AlignDown(int Value, int Size)
{
return Value & -Size;
}
public static ulong AlignDown(ulong Value, int Size)
{
return (ulong)AlignDown((long)Value, Size);
}
public static long AlignDown(long Value, int Size)
{
return Value & -(long)Size;
}
public static ulong DivRoundUp(ulong Value, uint Dividend)
{
return (Value + Dividend - 1) / Dividend;
}
public static long DivRoundUp(long Value, int Dividend)
{
return (Value + Dividend - 1) / Dividend;
}
public static bool IsPowerOfTwo32(int Value)
{
return Value != 0 && (Value & (Value - 1)) == 0;
}
public static bool IsPowerOfTwo64(long Value)
{
return Value != 0 && (Value & (Value - 1)) == 0;
}
public static int CountLeadingZeros32(int Value)
{
return (int)CountLeadingZeros((ulong)Value, 32);
}
public static int CountLeadingZeros64(long Value)
{
return (int)CountLeadingZeros((ulong)Value, 64);
}
private static readonly byte[] ClzNibbleTbl = { 4, 3, 2, 2, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0 };
private static ulong CountLeadingZeros(ulong Value, int Size) // Size is 8, 16, 32 or 64 (SIMD&FP or Base Inst.).
{
if (Value == 0ul)
{
return (ulong)Size;
}
int NibbleIdx = Size;
int PreCount, Count = 0;
do
{
NibbleIdx -= 4;
PreCount = ClzNibbleTbl[(Value >> NibbleIdx) & 0b1111];
Count += PreCount;
}
while (PreCount == 4);
return (ulong)Count;
}
public static long ReverseBits64(long Value)
{
return (long)ReverseBits64((ulong)Value);
}
private static ulong ReverseBits64(ulong Value)
{
Value = ((Value & 0xaaaaaaaaaaaaaaaa) >> 1 ) | ((Value & 0x5555555555555555) << 1 );
Value = ((Value & 0xcccccccccccccccc) >> 2 ) | ((Value & 0x3333333333333333) << 2 );
Value = ((Value & 0xf0f0f0f0f0f0f0f0) >> 4 ) | ((Value & 0x0f0f0f0f0f0f0f0f) << 4 );
Value = ((Value & 0xff00ff00ff00ff00) >> 8 ) | ((Value & 0x00ff00ff00ff00ff) << 8 );
Value = ((Value & 0xffff0000ffff0000) >> 16) | ((Value & 0x0000ffff0000ffff) << 16);
return (Value >> 32) | (Value << 32);
}
}
}

View file

@ -0,0 +1,99 @@
using Ryujinx.Graphics.Memory;
using System.Collections.Generic;
namespace Ryujinx.Graphics
{
public class CdmaProcessor
{
private const int MethSetMethod = 0x10;
private const int MethSetData = 0x11;
private NvGpu Gpu;
public CdmaProcessor(NvGpu Gpu)
{
this.Gpu = Gpu;
}
public void PushCommands(NvGpuVmm Vmm, int[] CmdBuffer)
{
List<ChCommand> Commands = new List<ChCommand>();
ChClassId CurrentClass = 0;
for (int Index = 0; Index < CmdBuffer.Length; Index++)
{
int Cmd = CmdBuffer[Index];
int Value = (Cmd >> 0) & 0xffff;
int MethodOffset = (Cmd >> 16) & 0xfff;
ChSubmissionMode SubmissionMode = (ChSubmissionMode)((Cmd >> 28) & 0xf);
switch (SubmissionMode)
{
case ChSubmissionMode.SetClass: CurrentClass = (ChClassId)(Value >> 6); break;
case ChSubmissionMode.Incrementing:
{
int Count = Value;
for (int ArgIdx = 0; ArgIdx < Count; ArgIdx++)
{
int Argument = CmdBuffer[++Index];
Commands.Add(new ChCommand(CurrentClass, MethodOffset + ArgIdx, Argument));
}
break;
}
case ChSubmissionMode.NonIncrementing:
{
int Count = Value;
int[] Arguments = new int[Count];
for (int ArgIdx = 0; ArgIdx < Count; ArgIdx++)
{
Arguments[ArgIdx] = CmdBuffer[++Index];
}
Commands.Add(new ChCommand(CurrentClass, MethodOffset, Arguments));
break;
}
}
}
ProcessCommands(Vmm, Commands.ToArray());
}
private void ProcessCommands(NvGpuVmm Vmm, ChCommand[] Commands)
{
int MethodOffset = 0;
foreach (ChCommand Command in Commands)
{
switch (Command.MethodOffset)
{
case MethSetMethod: MethodOffset = Command.Arguments[0]; break;
case MethSetData:
{
if (Command.ClassId == ChClassId.NvDec)
{
Gpu.VideoDecoder.Process(Vmm, MethodOffset, Command.Arguments);
}
else if (Command.ClassId == ChClassId.GraphicsVic)
{
Gpu.VideoImageComposer.Process(Vmm, MethodOffset, Command.Arguments);
}
break;
}
}
}
}
}
}

View file

@ -0,0 +1,20 @@
namespace Ryujinx.Graphics
{
enum ChClassId
{
Host1x = 0x1,
VideoEncodeMpeg = 0x20,
VideoEncodeNvEnc = 0x21,
VideoStreamingVi = 0x30,
VideoStreamingIsp = 0x32,
VideoStreamingIspB = 0x34,
VideoStreamingViI2c = 0x36,
GraphicsVic = 0x5d,
Graphics3d = 0x60,
GraphicsGpu = 0x61,
Tsec = 0xe0,
TsecB = 0xe1,
NvJpg = 0xc0,
NvDec = 0xf0
}
}

View file

@ -0,0 +1,18 @@
namespace Ryujinx.Graphics
{
struct ChCommand
{
public ChClassId ClassId { get; private set; }
public int MethodOffset { get; private set; }
public int[] Arguments { get; private set; }
public ChCommand(ChClassId ClassId, int MethodOffset, params int[] Arguments)
{
this.ClassId = ClassId;
this.MethodOffset = MethodOffset;
this.Arguments = Arguments;
}
}
}

View file

@ -0,0 +1,13 @@
namespace Ryujinx.Graphics
{
enum ChSubmissionMode
{
SetClass = 0,
Incrementing = 1,
NonIncrementing = 2,
Mask = 3,
Immediate = 4,
Restart = 5,
Gather = 6
}
}

View file

@ -1,5 +1,3 @@
using System;
namespace Ryujinx.Graphics.Gal namespace Ryujinx.Graphics.Gal
{ {
public struct GalVertexAttrib public struct GalVertexAttrib
@ -7,7 +5,7 @@ namespace Ryujinx.Graphics.Gal
public int Index { get; private set; } public int Index { get; private set; }
public bool IsConst { get; private set; } public bool IsConst { get; private set; }
public int Offset { get; private set; } public int Offset { get; private set; }
public IntPtr Pointer { get; private set; } public byte[] Data { get; private set; }
public GalVertexAttribSize Size { get; private set; } public GalVertexAttribSize Size { get; private set; }
public GalVertexAttribType Type { get; private set; } public GalVertexAttribType Type { get; private set; }
@ -18,14 +16,14 @@ namespace Ryujinx.Graphics.Gal
int Index, int Index,
bool IsConst, bool IsConst,
int Offset, int Offset,
IntPtr Pointer, byte[] Data,
GalVertexAttribSize Size, GalVertexAttribSize Size,
GalVertexAttribType Type, GalVertexAttribType Type,
bool IsBgra) bool IsBgra)
{ {
this.Index = Index; this.Index = Index;
this.IsConst = IsConst; this.IsConst = IsConst;
this.Pointer = Pointer; this.Data = Data;
this.Offset = Offset; this.Offset = Offset;
this.Size = Size; this.Size = Size;
this.Type = Type; this.Type = Type;

View file

@ -12,5 +12,6 @@ namespace Ryujinx.Graphics.Gal
bool IsCached(long Key, long Size); bool IsCached(long Key, long Size);
void SetData(long Key, long Size, IntPtr HostAddress); void SetData(long Key, long Size, IntPtr HostAddress);
void SetData(long Key, byte[] Data);
} }
} }

View file

@ -22,6 +22,7 @@ namespace Ryujinx.Graphics.Gal
bool IsIboCached(long Key, long DataSize); bool IsIboCached(long Key, long DataSize);
void CreateVbo(long Key, int DataSize, IntPtr HostAddress); void CreateVbo(long Key, int DataSize, IntPtr HostAddress);
void CreateVbo(long Key, byte[] Data);
void CreateIbo(long Key, int DataSize, IntPtr HostAddress); void CreateIbo(long Key, int DataSize, IntPtr HostAddress);
void CreateIbo(long Key, int DataSize, byte[] Buffer); void CreateIbo(long Key, int DataSize, byte[] Buffer);

View file

@ -44,6 +44,14 @@ namespace Ryujinx.Graphics.Gal.OpenGL
} }
} }
public void SetData(long Key, byte[] Data)
{
if (Cache.TryGetValue(Key, out OGLStreamBuffer Buffer))
{
Buffer.SetData(Data);
}
}
public bool TryGetUbo(long Key, out int UboHandle) public bool TryGetUbo(long Key, out int UboHandle)
{ {
if (Cache.TryGetValue(Key, out OGLStreamBuffer Buffer)) if (Cache.TryGetValue(Key, out OGLStreamBuffer Buffer))

View file

@ -0,0 +1,12 @@
using OpenTK.Graphics.OpenGL;
using System;
namespace Ryujinx.Graphics.Gal.OpenGL
{
static class OGLLimit
{
private static Lazy<int> s_MaxUboSize = new Lazy<int>(() => GL.GetInteger(GetPName.MaxUniformBlockSize));
public static int MaxUboSize => s_MaxUboSize.Value;
}
}

View file

@ -77,17 +77,23 @@ namespace Ryujinx.Graphics.Gal.OpenGL
private GalPipelineState Old; private GalPipelineState Old;
private OGLConstBuffer Buffer; private OGLConstBuffer Buffer;
private OGLRasterizer Rasterizer; private OGLRenderTarget RenderTarget;
private OGLShader Shader; private OGLRasterizer Rasterizer;
private OGLShader Shader;
private int VaoHandle; private int VaoHandle;
public OGLPipeline(OGLConstBuffer Buffer, OGLRasterizer Rasterizer, OGLShader Shader) public OGLPipeline(
OGLConstBuffer Buffer,
OGLRenderTarget RenderTarget,
OGLRasterizer Rasterizer,
OGLShader Shader)
{ {
this.Buffer = Buffer; this.Buffer = Buffer;
this.Rasterizer = Rasterizer; this.RenderTarget = RenderTarget;
this.Shader = Shader; this.Rasterizer = Rasterizer;
this.Shader = Shader;
//These values match OpenGL's defaults //These values match OpenGL's defaults
Old = new GalPipelineState Old = new GalPipelineState
@ -144,6 +150,8 @@ namespace Ryujinx.Graphics.Gal.OpenGL
if (New.FramebufferSrgb != Old.FramebufferSrgb) if (New.FramebufferSrgb != Old.FramebufferSrgb)
{ {
Enable(EnableCap.FramebufferSrgb, New.FramebufferSrgb); Enable(EnableCap.FramebufferSrgb, New.FramebufferSrgb);
RenderTarget.FramebufferSrgb = New.FramebufferSrgb;
} }
if (New.FlipX != Old.FlipX || New.FlipY != Old.FlipY || New.Instance != Old.Instance) if (New.FlipX != Old.FlipX || New.FlipY != Old.FlipY || New.Instance != Old.Instance)
@ -600,122 +608,125 @@ namespace Ryujinx.Graphics.Gal.OpenGL
ThrowUnsupportedAttrib(Attrib); ThrowUnsupportedAttrib(Attrib);
} }
if (Attrib.Type == GalVertexAttribType.Unorm) fixed (byte* Ptr = Attrib.Data)
{ {
switch (Attrib.Size) if (Attrib.Type == GalVertexAttribType.Unorm)
{ {
case GalVertexAttribSize._8: switch (Attrib.Size)
case GalVertexAttribSize._8_8: {
case GalVertexAttribSize._8_8_8: case GalVertexAttribSize._8:
case GalVertexAttribSize._8_8_8_8: case GalVertexAttribSize._8_8:
GL.VertexAttrib4N((uint)Attrib.Index, (byte*)Attrib.Pointer); case GalVertexAttribSize._8_8_8:
break; case GalVertexAttribSize._8_8_8_8:
GL.VertexAttrib4N((uint)Attrib.Index, Ptr);
break;
case GalVertexAttribSize._16: case GalVertexAttribSize._16:
case GalVertexAttribSize._16_16: case GalVertexAttribSize._16_16:
case GalVertexAttribSize._16_16_16: case GalVertexAttribSize._16_16_16:
case GalVertexAttribSize._16_16_16_16: case GalVertexAttribSize._16_16_16_16:
GL.VertexAttrib4N((uint)Attrib.Index, (ushort*)Attrib.Pointer); GL.VertexAttrib4N((uint)Attrib.Index, (ushort*)Ptr);
break; break;
case GalVertexAttribSize._32: case GalVertexAttribSize._32:
case GalVertexAttribSize._32_32: case GalVertexAttribSize._32_32:
case GalVertexAttribSize._32_32_32: case GalVertexAttribSize._32_32_32:
case GalVertexAttribSize._32_32_32_32: case GalVertexAttribSize._32_32_32_32:
GL.VertexAttrib4N((uint)Attrib.Index, (uint*)Attrib.Pointer); GL.VertexAttrib4N((uint)Attrib.Index, (uint*)Ptr);
break; break;
}
} }
} else if (Attrib.Type == GalVertexAttribType.Snorm)
else if (Attrib.Type == GalVertexAttribType.Snorm)
{
switch (Attrib.Size)
{ {
case GalVertexAttribSize._8: switch (Attrib.Size)
case GalVertexAttribSize._8_8: {
case GalVertexAttribSize._8_8_8: case GalVertexAttribSize._8:
case GalVertexAttribSize._8_8_8_8: case GalVertexAttribSize._8_8:
GL.VertexAttrib4N((uint)Attrib.Index, (sbyte*)Attrib.Pointer); case GalVertexAttribSize._8_8_8:
break; case GalVertexAttribSize._8_8_8_8:
GL.VertexAttrib4N((uint)Attrib.Index, (sbyte*)Ptr);
break;
case GalVertexAttribSize._16: case GalVertexAttribSize._16:
case GalVertexAttribSize._16_16: case GalVertexAttribSize._16_16:
case GalVertexAttribSize._16_16_16: case GalVertexAttribSize._16_16_16:
case GalVertexAttribSize._16_16_16_16: case GalVertexAttribSize._16_16_16_16:
GL.VertexAttrib4N((uint)Attrib.Index, (short*)Attrib.Pointer); GL.VertexAttrib4N((uint)Attrib.Index, (short*)Ptr);
break; break;
case GalVertexAttribSize._32: case GalVertexAttribSize._32:
case GalVertexAttribSize._32_32: case GalVertexAttribSize._32_32:
case GalVertexAttribSize._32_32_32: case GalVertexAttribSize._32_32_32:
case GalVertexAttribSize._32_32_32_32: case GalVertexAttribSize._32_32_32_32:
GL.VertexAttrib4N((uint)Attrib.Index, (int*)Attrib.Pointer); GL.VertexAttrib4N((uint)Attrib.Index, (int*)Ptr);
break; break;
}
} }
} else if (Attrib.Type == GalVertexAttribType.Uint)
else if (Attrib.Type == GalVertexAttribType.Uint)
{
switch (Attrib.Size)
{ {
case GalVertexAttribSize._8: switch (Attrib.Size)
case GalVertexAttribSize._8_8: {
case GalVertexAttribSize._8_8_8: case GalVertexAttribSize._8:
case GalVertexAttribSize._8_8_8_8: case GalVertexAttribSize._8_8:
GL.VertexAttribI4((uint)Attrib.Index, (byte*)Attrib.Pointer); case GalVertexAttribSize._8_8_8:
break; case GalVertexAttribSize._8_8_8_8:
GL.VertexAttribI4((uint)Attrib.Index, Ptr);
break;
case GalVertexAttribSize._16: case GalVertexAttribSize._16:
case GalVertexAttribSize._16_16: case GalVertexAttribSize._16_16:
case GalVertexAttribSize._16_16_16: case GalVertexAttribSize._16_16_16:
case GalVertexAttribSize._16_16_16_16: case GalVertexAttribSize._16_16_16_16:
GL.VertexAttribI4((uint)Attrib.Index, (ushort*)Attrib.Pointer); GL.VertexAttribI4((uint)Attrib.Index, (ushort*)Ptr);
break; break;
case GalVertexAttribSize._32: case GalVertexAttribSize._32:
case GalVertexAttribSize._32_32: case GalVertexAttribSize._32_32:
case GalVertexAttribSize._32_32_32: case GalVertexAttribSize._32_32_32:
case GalVertexAttribSize._32_32_32_32: case GalVertexAttribSize._32_32_32_32:
GL.VertexAttribI4((uint)Attrib.Index, (uint*)Attrib.Pointer); GL.VertexAttribI4((uint)Attrib.Index, (uint*)Ptr);
break; break;
}
} }
} else if (Attrib.Type == GalVertexAttribType.Sint)
else if (Attrib.Type == GalVertexAttribType.Sint)
{
switch (Attrib.Size)
{ {
case GalVertexAttribSize._8: switch (Attrib.Size)
case GalVertexAttribSize._8_8: {
case GalVertexAttribSize._8_8_8: case GalVertexAttribSize._8:
case GalVertexAttribSize._8_8_8_8: case GalVertexAttribSize._8_8:
GL.VertexAttribI4((uint)Attrib.Index, (sbyte*)Attrib.Pointer); case GalVertexAttribSize._8_8_8:
break; case GalVertexAttribSize._8_8_8_8:
GL.VertexAttribI4((uint)Attrib.Index, (sbyte*)Ptr);
break;
case GalVertexAttribSize._16: case GalVertexAttribSize._16:
case GalVertexAttribSize._16_16: case GalVertexAttribSize._16_16:
case GalVertexAttribSize._16_16_16: case GalVertexAttribSize._16_16_16:
case GalVertexAttribSize._16_16_16_16: case GalVertexAttribSize._16_16_16_16:
GL.VertexAttribI4((uint)Attrib.Index, (short*)Attrib.Pointer); GL.VertexAttribI4((uint)Attrib.Index, (short*)Ptr);
break; break;
case GalVertexAttribSize._32: case GalVertexAttribSize._32:
case GalVertexAttribSize._32_32: case GalVertexAttribSize._32_32:
case GalVertexAttribSize._32_32_32: case GalVertexAttribSize._32_32_32:
case GalVertexAttribSize._32_32_32_32: case GalVertexAttribSize._32_32_32_32:
GL.VertexAttribI4((uint)Attrib.Index, (int*)Attrib.Pointer); GL.VertexAttribI4((uint)Attrib.Index, (int*)Ptr);
break; break;
}
} }
} else if (Attrib.Type == GalVertexAttribType.Float)
else if (Attrib.Type == GalVertexAttribType.Float)
{
switch (Attrib.Size)
{ {
case GalVertexAttribSize._32: switch (Attrib.Size)
case GalVertexAttribSize._32_32: {
case GalVertexAttribSize._32_32_32: case GalVertexAttribSize._32:
case GalVertexAttribSize._32_32_32_32: case GalVertexAttribSize._32_32:
GL.VertexAttrib4(Attrib.Index, (float*)Attrib.Pointer); case GalVertexAttribSize._32_32_32:
break; case GalVertexAttribSize._32_32_32_32:
GL.VertexAttrib4(Attrib.Index, (float*)Ptr);
break;
default: ThrowUnsupportedAttrib(Attrib); break; default: ThrowUnsupportedAttrib(Attrib); break;
}
} }
} }
} }

View file

@ -92,7 +92,7 @@ namespace Ryujinx.Graphics.Gal.OpenGL
{ {
int Handle = GL.GenBuffer(); int Handle = GL.GenBuffer();
VboCache.AddOrUpdate(Key, Handle, (uint)DataSize); VboCache.AddOrUpdate(Key, Handle, DataSize);
IntPtr Length = new IntPtr(DataSize); IntPtr Length = new IntPtr(DataSize);
@ -100,6 +100,18 @@ namespace Ryujinx.Graphics.Gal.OpenGL
GL.BufferData(BufferTarget.ArrayBuffer, Length, HostAddress, BufferUsageHint.StreamDraw); GL.BufferData(BufferTarget.ArrayBuffer, Length, HostAddress, BufferUsageHint.StreamDraw);
} }
public void CreateVbo(long Key, byte[] Data)
{
int Handle = GL.GenBuffer();
VboCache.AddOrUpdate(Key, Handle, Data.Length);
IntPtr Length = new IntPtr(Data.Length);
GL.BindBuffer(BufferTarget.ArrayBuffer, Handle);
GL.BufferData(BufferTarget.ArrayBuffer, Length, Data, BufferUsageHint.StreamDraw);
}
public void CreateIbo(long Key, int DataSize, IntPtr HostAddress) public void CreateIbo(long Key, int DataSize, IntPtr HostAddress)
{ {
int Handle = GL.GenBuffer(); int Handle = GL.GenBuffer();
@ -116,7 +128,7 @@ namespace Ryujinx.Graphics.Gal.OpenGL
{ {
int Handle = GL.GenBuffer(); int Handle = GL.GenBuffer();
IboCache.AddOrUpdate(Key, Handle, (uint)DataSize); IboCache.AddOrUpdate(Key, Handle, DataSize);
IntPtr Length = new IntPtr(Buffer.Length); IntPtr Length = new IntPtr(Buffer.Length);

View file

@ -90,6 +90,8 @@ namespace Ryujinx.Graphics.Gal.OpenGL
private int CopyPBO; private int CopyPBO;
public bool FramebufferSrgb { get; set; }
public OGLRenderTarget(OGLTexture Texture) public OGLRenderTarget(OGLTexture Texture)
{ {
Attachments = new FrameBufferAttachments(); Attachments = new FrameBufferAttachments();
@ -363,11 +365,24 @@ namespace Ryujinx.Graphics.Gal.OpenGL
GL.Clear(ClearBufferMask.ColorBufferBit); GL.Clear(ClearBufferMask.ColorBufferBit);
GL.Disable(EnableCap.FramebufferSrgb);
GL.BlitFramebuffer( GL.BlitFramebuffer(
SrcX0, SrcY0, SrcX1, SrcY1, SrcX0,
DstX0, DstY0, DstX1, DstY1, SrcY0,
SrcX1,
SrcY1,
DstX0,
DstY0,
DstX1,
DstY1,
ClearBufferMask.ColorBufferBit, ClearBufferMask.ColorBufferBit,
BlitFramebufferFilter.Linear); BlitFramebufferFilter.Linear);
if (FramebufferSrgb)
{
GL.Enable(EnableCap.FramebufferSrgb);
}
} }
public void Copy( public void Copy(
@ -432,7 +447,9 @@ namespace Ryujinx.Graphics.Gal.OpenGL
return; return;
} }
if (NewImage.Format == OldImage.Format) if (NewImage.Format == OldImage.Format &&
NewImage.Width == OldImage.Width &&
NewImage.Height == OldImage.Height)
{ {
return; return;
} }
@ -444,7 +461,11 @@ namespace Ryujinx.Graphics.Gal.OpenGL
GL.BindBuffer(BufferTarget.PixelPackBuffer, CopyPBO); GL.BindBuffer(BufferTarget.PixelPackBuffer, CopyPBO);
GL.BufferData(BufferTarget.PixelPackBuffer, Math.Max(ImageUtils.GetSize(OldImage), ImageUtils.GetSize(NewImage)), IntPtr.Zero, BufferUsageHint.StreamCopy); //The buffer should be large enough to hold the largest texture.
int BufferSize = Math.Max(ImageUtils.GetSize(OldImage),
ImageUtils.GetSize(NewImage));
GL.BufferData(BufferTarget.PixelPackBuffer, BufferSize, IntPtr.Zero, BufferUsageHint.StreamCopy);
if (!Texture.TryGetImageHandler(Key, out ImageHandler CachedImage)) if (!Texture.TryGetImageHandler(Key, out ImageHandler CachedImage))
{ {
@ -460,8 +481,12 @@ namespace Ryujinx.Graphics.Gal.OpenGL
GL.BindBuffer(BufferTarget.PixelPackBuffer, 0); GL.BindBuffer(BufferTarget.PixelPackBuffer, 0);
GL.BindBuffer(BufferTarget.PixelUnpackBuffer, CopyPBO); GL.BindBuffer(BufferTarget.PixelUnpackBuffer, CopyPBO);
GL.PixelStore(PixelStoreParameter.UnpackRowLength, OldImage.Width);
Texture.Create(Key, ImageUtils.GetSize(NewImage), NewImage); Texture.Create(Key, ImageUtils.GetSize(NewImage), NewImage);
GL.PixelStore(PixelStoreParameter.UnpackRowLength, 0);
GL.BindBuffer(BufferTarget.PixelUnpackBuffer, 0); GL.BindBuffer(BufferTarget.PixelUnpackBuffer, 0);
} }

View file

@ -31,7 +31,11 @@ namespace Ryujinx.Graphics.Gal.OpenGL
Shader = new OGLShader(Buffer as OGLConstBuffer); Shader = new OGLShader(Buffer as OGLConstBuffer);
Pipeline = new OGLPipeline(Buffer as OGLConstBuffer, Rasterizer as OGLRasterizer, Shader as OGLShader); Pipeline = new OGLPipeline(
Buffer as OGLConstBuffer,
RenderTarget as OGLRenderTarget,
Rasterizer as OGLRasterizer,
Shader as OGLShader);
ActionsQueue = new ConcurrentQueue<Action>(); ActionsQueue = new ConcurrentQueue<Action>();
} }

View file

@ -30,6 +30,13 @@ namespace Ryujinx.Graphics.Gal.OpenGL
GL.BufferSubData(Target, IntPtr.Zero, (IntPtr)Size, HostAddress); GL.BufferSubData(Target, IntPtr.Zero, (IntPtr)Size, HostAddress);
} }
public void SetData(byte[] Data)
{
GL.BindBuffer(Target, Handle);
GL.BufferSubData(Target, IntPtr.Zero, (IntPtr)Data.Length, Data);
}
public void Dispose() public void Dispose()
{ {
Dispose(true); Dispose(true);

View file

@ -1,3 +1,4 @@
using Ryujinx.Graphics.Gal.OpenGL;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
@ -16,8 +17,6 @@ namespace Ryujinx.Graphics.Gal.Shader
public const int VertexIdAttr = 0x2fc; public const int VertexIdAttr = 0x2fc;
public const int FaceAttr = 0x3fc; public const int FaceAttr = 0x3fc;
public const int MaxUboSize = 1024;
public const int GlPositionVec4Index = 7; public const int GlPositionVec4Index = 7;
public const int PositionOutAttrLocation = 15; public const int PositionOutAttrLocation = 15;
@ -51,6 +50,8 @@ namespace Ryujinx.Graphics.Gal.Shader
public const string SsyStackName = "ssy_stack"; public const string SsyStackName = "ssy_stack";
public const string SsyCursorName = "ssy_cursor"; public const string SsyCursorName = "ssy_cursor";
public static int MaxUboSize => OGLLimit.MaxUboSize / 16;
private string[] StagePrefixes = new string[] { "vp", "tcp", "tep", "gp", "fp" }; private string[] StagePrefixes = new string[] { "vp", "tcp", "tep", "gp", "fp" };
private string StagePrefix; private string StagePrefix;
@ -98,8 +99,7 @@ namespace Ryujinx.Graphics.Gal.Shader
m_Preds = new Dictionary<int, ShaderDeclInfo>(); m_Preds = new Dictionary<int, ShaderDeclInfo>();
} }
public GlslDecl(ShaderIrBlock[] Blocks, GalShaderType ShaderType, ShaderHeader Header) public GlslDecl(ShaderIrBlock[] Blocks, GalShaderType ShaderType, ShaderHeader Header) : this(ShaderType)
: this(ShaderType)
{ {
StagePrefix = StagePrefixes[(int)ShaderType] + "_"; StagePrefix = StagePrefixes[(int)ShaderType] + "_";

View file

@ -63,15 +63,10 @@ namespace Ryujinx.Graphics
Gpu.Renderer.RenderTarget.BindZeta(Position); Gpu.Renderer.RenderTarget.BindZeta(Position);
} }
public void SendTexture(NvGpuVmm Vmm, long Position, GalImage NewImage, int TexIndex = -1) public void SendTexture(NvGpuVmm Vmm, long Position, GalImage NewImage)
{ {
PrepareSendTexture(Vmm, Position, NewImage); PrepareSendTexture(Vmm, Position, NewImage);
if (TexIndex >= 0)
{
Gpu.Renderer.Texture.Bind(Position, TexIndex, NewImage);
}
ImageTypes[Position] = ImageType.Texture; ImageTypes[Position] = ImageType.Texture;
} }

View file

@ -1,6 +1,6 @@
using Ryujinx.Graphics.Memory; using Ryujinx.Graphics.Memory;
namespace Ryujinx.Graphics namespace Ryujinx.Graphics.Graphics3d
{ {
interface INvGpuEngine interface INvGpuEngine
{ {

View file

@ -3,7 +3,7 @@ using Ryujinx.Graphics.Memory;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
namespace Ryujinx.Graphics namespace Ryujinx.Graphics.Graphics3d
{ {
class MacroInterpreter class MacroInterpreter
{ {

View file

@ -1,4 +1,4 @@
namespace Ryujinx.Graphics namespace Ryujinx.Graphics.Graphics3d
{ {
enum NvGpuEngine enum NvGpuEngine
{ {

View file

@ -2,7 +2,7 @@ using Ryujinx.Graphics.Gal;
using Ryujinx.Graphics.Memory; using Ryujinx.Graphics.Memory;
using Ryujinx.Graphics.Texture; using Ryujinx.Graphics.Texture;
namespace Ryujinx.Graphics namespace Ryujinx.Graphics.Graphics3d
{ {
class NvGpuEngine2d : INvGpuEngine class NvGpuEngine2d : INvGpuEngine
{ {
@ -61,8 +61,11 @@ namespace Ryujinx.Graphics
int DstBlitW = ReadRegister(NvGpuEngine2dReg.BlitDstW); int DstBlitW = ReadRegister(NvGpuEngine2dReg.BlitDstW);
int DstBlitH = ReadRegister(NvGpuEngine2dReg.BlitDstH); int DstBlitH = ReadRegister(NvGpuEngine2dReg.BlitDstH);
int SrcBlitX = ReadRegister(NvGpuEngine2dReg.BlitSrcXInt); long BlitDuDx = ReadRegisterFixed1_31_32(NvGpuEngine2dReg.BlitDuDxFract);
int SrcBlitY = ReadRegister(NvGpuEngine2dReg.BlitSrcYInt); long BlitDvDy = ReadRegisterFixed1_31_32(NvGpuEngine2dReg.BlitDvDyFract);
long SrcBlitX = ReadRegisterFixed1_31_32(NvGpuEngine2dReg.BlitSrcXFract);
long SrcBlitY = ReadRegisterFixed1_31_32(NvGpuEngine2dReg.BlitSrcYFract);
GalImageFormat SrcImgFormat = ImageUtils.ConvertSurface((GalSurfaceFormat)SrcFormat); GalImageFormat SrcImgFormat = ImageUtils.ConvertSurface((GalSurfaceFormat)SrcFormat);
GalImageFormat DstImgFormat = ImageUtils.ConvertSurface((GalSurfaceFormat)DstFormat); GalImageFormat DstImgFormat = ImageUtils.ConvertSurface((GalSurfaceFormat)DstFormat);
@ -99,13 +102,19 @@ namespace Ryujinx.Graphics
Gpu.ResourceManager.SendTexture(Vmm, SrcKey, SrcTexture); Gpu.ResourceManager.SendTexture(Vmm, SrcKey, SrcTexture);
Gpu.ResourceManager.SendTexture(Vmm, DstKey, DstTexture); Gpu.ResourceManager.SendTexture(Vmm, DstKey, DstTexture);
int SrcBlitX1 = (int)(SrcBlitX >> 32);
int SrcBlitY1 = (int)(SrcBlitY >> 32);
int SrcBlitX2 = (int)(SrcBlitX + DstBlitW * BlitDuDx >> 32);
int SrcBlitY2 = (int)(SrcBlitY + DstBlitH * BlitDvDy >> 32);
Gpu.Renderer.RenderTarget.Copy( Gpu.Renderer.RenderTarget.Copy(
SrcKey, SrcKey,
DstKey, DstKey,
SrcBlitX, SrcBlitX1,
SrcBlitY, SrcBlitY1,
SrcBlitX + DstBlitW, SrcBlitX2,
SrcBlitY + DstBlitH, SrcBlitY2,
DstBlitX, DstBlitX,
DstBlitY, DstBlitY,
DstBlitX + DstBlitW, DstBlitX + DstBlitW,
@ -121,8 +130,8 @@ namespace Ryujinx.Graphics
DstTexture, DstTexture,
SrcAddress, SrcAddress,
DstAddress, DstAddress,
SrcBlitX, SrcBlitX1,
SrcBlitY, SrcBlitY1,
DstBlitX, DstBlitX,
DstBlitY, DstBlitY,
DstBlitW, DstBlitW,
@ -150,6 +159,14 @@ namespace Ryujinx.Graphics
Registers[MethCall.Method] = MethCall.Argument; Registers[MethCall.Method] = MethCall.Argument;
} }
private long ReadRegisterFixed1_31_32(NvGpuEngine2dReg Reg)
{
long Low = (uint)ReadRegister(Reg + 0);
long High = (uint)ReadRegister(Reg + 1);
return Low | (High << 32);
}
private int ReadRegister(NvGpuEngine2dReg Reg) private int ReadRegister(NvGpuEngine2dReg Reg)
{ {
return Registers[(int)Reg]; return Registers[(int)Reg];

View file

@ -1,4 +1,4 @@
namespace Ryujinx.Graphics namespace Ryujinx.Graphics.Graphics3d
{ {
enum NvGpuEngine2dReg enum NvGpuEngine2dReg
{ {

View file

@ -5,7 +5,7 @@ using Ryujinx.Graphics.Texture;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
namespace Ryujinx.Graphics namespace Ryujinx.Graphics.Graphics3d
{ {
class NvGpuEngine3d : INvGpuEngine class NvGpuEngine3d : INvGpuEngine
{ {
@ -523,7 +523,7 @@ namespace Ryujinx.Graphics
int TextureCbIndex = ReadRegister(NvGpuEngine3dReg.TextureCbIndex); int TextureCbIndex = ReadRegister(NvGpuEngine3dReg.TextureCbIndex);
int TexIndex = 0; List<(long, GalImage, GalTextureSampler)> UnboundTextures = new List<(long, GalImage, GalTextureSampler)>();
for (int Index = 0; Index < Keys.Length; Index++) for (int Index = 0; Index < Keys.Length; Index++)
{ {
@ -542,20 +542,31 @@ namespace Ryujinx.Graphics
int TextureHandle = Vmm.ReadInt32(Position + DeclInfo.Index * 4); int TextureHandle = Vmm.ReadInt32(Position + DeclInfo.Index * 4);
UploadTexture(Vmm, TexIndex, TextureHandle); UnboundTextures.Add(UploadTexture(Vmm, TextureHandle));
TexIndex++;
} }
} }
for (int Index = 0; Index < UnboundTextures.Count; Index++)
{
(long Key, GalImage Image, GalTextureSampler Sampler) = UnboundTextures[Index];
if (Key == 0)
{
continue;
}
Gpu.Renderer.Texture.Bind(Key, Index, Image);
Gpu.Renderer.Texture.SetSampler(Sampler);
}
} }
private void UploadTexture(NvGpuVmm Vmm, int TexIndex, int TextureHandle) private (long, GalImage, GalTextureSampler) UploadTexture(NvGpuVmm Vmm, int TextureHandle)
{ {
if (TextureHandle == 0) if (TextureHandle == 0)
{ {
//FIXME: Some games like puyo puyo will use handles with the value 0. //FIXME: Some games like puyo puyo will use handles with the value 0.
//This is a bug, most likely caused by sync issues. //This is a bug, most likely caused by sync issues.
return; return (0, default(GalImage), default(GalTextureSampler));
} }
bool LinkedTsc = ReadRegisterBool(NvGpuEngine3dReg.LinkedTsc); bool LinkedTsc = ReadRegisterBool(NvGpuEngine3dReg.LinkedTsc);
@ -590,12 +601,12 @@ namespace Ryujinx.Graphics
if (Key == -1) if (Key == -1)
{ {
//FIXME: Shouldn't ignore invalid addresses. //FIXME: Shouldn't ignore invalid addresses.
return; return (0, default(GalImage), default(GalTextureSampler));
} }
Gpu.ResourceManager.SendTexture(Vmm, Key, Image, TexIndex); Gpu.ResourceManager.SendTexture(Vmm, Key, Image);
Gpu.Renderer.Texture.SetSampler(Sampler); return (Key, Image, Sampler);
} }
private void UploadConstBuffers(NvGpuVmm Vmm, GalPipelineState State, long[] Keys) private void UploadConstBuffers(NvGpuVmm Vmm, GalPipelineState State, long[] Keys)
@ -615,9 +626,14 @@ namespace Ryujinx.Graphics
if (Gpu.ResourceManager.MemoryRegionModified(Vmm, Key, Cb.Size, NvGpuBufferType.ConstBuffer)) if (Gpu.ResourceManager.MemoryRegionModified(Vmm, Key, Cb.Size, NvGpuBufferType.ConstBuffer))
{ {
IntPtr Source = Vmm.GetHostAddress(Cb.Position, Cb.Size); if (Vmm.TryGetHostAddress(Cb.Position, Cb.Size, out IntPtr CbPtr))
{
Gpu.Renderer.Buffer.SetData(Key, Cb.Size, Source); Gpu.Renderer.Buffer.SetData(Key, Cb.Size, CbPtr);
}
else
{
Gpu.Renderer.Buffer.SetData(Key, Vmm.ReadBytes(Cb.Position, Cb.Size));
}
} }
State.ConstBufferKeys[Stage][DeclInfo.Cbuf] = Key; State.ConstBufferKeys[Stage][DeclInfo.Cbuf] = Key;
@ -660,9 +676,14 @@ namespace Ryujinx.Graphics
{ {
if (!UsesLegacyQuads) if (!UsesLegacyQuads)
{ {
IntPtr DataAddress = Vmm.GetHostAddress(IbPosition, IbSize); if (Vmm.TryGetHostAddress(IbPosition, IbSize, out IntPtr IbPtr))
{
Gpu.Renderer.Rasterizer.CreateIbo(IboKey, IbSize, DataAddress); Gpu.Renderer.Rasterizer.CreateIbo(IboKey, IbSize, IbPtr);
}
else
{
Gpu.Renderer.Rasterizer.CreateIbo(IboKey, IbSize, Vmm.ReadBytes(IbPosition, IbSize));
}
} }
else else
{ {
@ -711,22 +732,22 @@ namespace Ryujinx.Graphics
Attribs[ArrayIndex] = new List<GalVertexAttrib>(); Attribs[ArrayIndex] = new List<GalVertexAttrib>();
} }
long VertexPosition = MakeInt64From2xInt32(NvGpuEngine3dReg.VertexArrayNAddress + ArrayIndex * 4); long VbPosition = MakeInt64From2xInt32(NvGpuEngine3dReg.VertexArrayNAddress + ArrayIndex * 4);
bool IsConst = ((Packed >> 6) & 1) != 0;
int Offset = (Packed >> 7) & 0x3fff; int Offset = (Packed >> 7) & 0x3fff;
GalVertexAttribSize Size = (GalVertexAttribSize)((Packed >> 21) & 0x3f);
GalVertexAttribType Type = (GalVertexAttribType)((Packed >> 27) & 0x7);
bool IsRgba = ((Packed >> 31) & 1) != 0;
//Note: 16 is the maximum size of an attribute, //Note: 16 is the maximum size of an attribute,
//having a component size of 32-bits with 4 elements (a vec4). //having a component size of 32-bits with 4 elements (a vec4).
IntPtr Pointer = Vmm.GetHostAddress(VertexPosition + Offset, 16); byte[] Data = Vmm.ReadBytes(VbPosition + Offset, 16);
Attribs[ArrayIndex].Add(new GalVertexAttrib( Attribs[ArrayIndex].Add(new GalVertexAttrib(Attr, IsConst, Offset, Data, Size, Type, IsRgba));
Attr,
((Packed >> 6) & 0x1) != 0,
Offset,
Pointer,
(GalVertexAttribSize)((Packed >> 21) & 0x3f),
(GalVertexAttribType)((Packed >> 27) & 0x7),
((Packed >> 31) & 0x1) != 0));
} }
State.VertexBindings = new GalVertexBinding[32]; State.VertexBindings = new GalVertexBinding[32];
@ -747,8 +768,8 @@ namespace Ryujinx.Graphics
continue; continue;
} }
long VertexPosition = MakeInt64From2xInt32(NvGpuEngine3dReg.VertexArrayNAddress + Index * 4); long VbPosition = MakeInt64From2xInt32(NvGpuEngine3dReg.VertexArrayNAddress + Index * 4);
long VertexEndPos = MakeInt64From2xInt32(NvGpuEngine3dReg.VertexArrayNEndAddr + Index * 2); long VbEndPos = MakeInt64From2xInt32(NvGpuEngine3dReg.VertexArrayNEndAddr + Index * 2);
int VertexDivisor = ReadRegister(NvGpuEngine3dReg.VertexArrayNDivisor + Index * 4); int VertexDivisor = ReadRegister(NvGpuEngine3dReg.VertexArrayNDivisor + Index * 4);
@ -758,26 +779,31 @@ namespace Ryujinx.Graphics
if (Instanced && VertexDivisor != 0) if (Instanced && VertexDivisor != 0)
{ {
VertexPosition += Stride * (CurrentInstance / VertexDivisor); VbPosition += Stride * (CurrentInstance / VertexDivisor);
} }
if (VertexPosition > VertexEndPos) if (VbPosition > VbEndPos)
{ {
//Instance is invalid, ignore the draw call //Instance is invalid, ignore the draw call
continue; continue;
} }
long VboKey = Vmm.GetPhysicalAddress(VertexPosition); long VboKey = Vmm.GetPhysicalAddress(VbPosition);
long VbSize = (VertexEndPos - VertexPosition) + 1; long VbSize = (VbEndPos - VbPosition) + 1;
bool VboCached = Gpu.Renderer.Rasterizer.IsVboCached(VboKey, VbSize); bool VboCached = Gpu.Renderer.Rasterizer.IsVboCached(VboKey, VbSize);
if (!VboCached || Gpu.ResourceManager.MemoryRegionModified(Vmm, VboKey, VbSize, NvGpuBufferType.Vertex)) if (!VboCached || Gpu.ResourceManager.MemoryRegionModified(Vmm, VboKey, VbSize, NvGpuBufferType.Vertex))
{ {
IntPtr DataAddress = Vmm.GetHostAddress(VertexPosition, VbSize); if (Vmm.TryGetHostAddress(VbPosition, VbSize, out IntPtr VbPtr))
{
Gpu.Renderer.Rasterizer.CreateVbo(VboKey, (int)VbSize, DataAddress); Gpu.Renderer.Rasterizer.CreateVbo(VboKey, (int)VbSize, VbPtr);
}
else
{
Gpu.Renderer.Rasterizer.CreateVbo(VboKey, Vmm.ReadBytes(VbPosition, VbSize));
}
} }
State.VertexBindings[Index].Enabled = true; State.VertexBindings[Index].Enabled = true;

View file

@ -1,4 +1,4 @@
namespace Ryujinx.Graphics namespace Ryujinx.Graphics.Graphics3d
{ {
enum NvGpuEngine3dReg enum NvGpuEngine3dReg
{ {

View file

@ -2,7 +2,7 @@ using Ryujinx.Graphics.Memory;
using Ryujinx.Graphics.Texture; using Ryujinx.Graphics.Texture;
using System.Collections.Generic; using System.Collections.Generic;
namespace Ryujinx.Graphics namespace Ryujinx.Graphics.Graphics3d
{ {
class NvGpuEngineM2mf : INvGpuEngine class NvGpuEngineM2mf : INvGpuEngine
{ {

View file

@ -1,4 +1,4 @@
namespace Ryujinx.Graphics namespace Ryujinx.Graphics.Graphics3d
{ {
enum NvGpuEngineM2mfReg enum NvGpuEngineM2mfReg
{ {

View file

@ -2,7 +2,7 @@ using Ryujinx.Graphics.Memory;
using Ryujinx.Graphics.Texture; using Ryujinx.Graphics.Texture;
using System.Collections.Generic; using System.Collections.Generic;
namespace Ryujinx.Graphics namespace Ryujinx.Graphics.Graphics3d
{ {
class NvGpuEngineP2mf : INvGpuEngine class NvGpuEngineP2mf : INvGpuEngine
{ {

View file

@ -1,4 +1,4 @@
namespace Ryujinx.Graphics namespace Ryujinx.Graphics.Graphics3d
{ {
enum NvGpuEngineP2mfReg enum NvGpuEngineP2mfReg
{ {

View file

@ -1,6 +1,6 @@
using Ryujinx.Graphics.Memory; using Ryujinx.Graphics.Memory;
namespace Ryujinx.Graphics namespace Ryujinx.Graphics.Graphics3d
{ {
class NvGpuFifo class NvGpuFifo
{ {

View file

@ -1,4 +1,4 @@
namespace Ryujinx.Graphics namespace Ryujinx.Graphics.Graphics3d
{ {
enum NvGpuFifoMeth enum NvGpuFifoMeth
{ {

View file

@ -1,6 +1,6 @@
using Ryujinx.Graphics.Memory; using Ryujinx.Graphics.Memory;
namespace Ryujinx.Graphics namespace Ryujinx.Graphics.Graphics3d
{ {
delegate void NvGpuMethod(NvGpuVmm Vmm, GpuMethodCall MethCall); delegate void NvGpuMethod(NvGpuVmm Vmm, GpuMethodCall MethCall);
} }

View file

@ -1,4 +1,4 @@
namespace Ryujinx.Graphics namespace Ryujinx.Graphics.Memory
{ {
public enum NvGpuBufferType public enum NvGpuBufferType
{ {

View file

@ -72,6 +72,28 @@ namespace Ryujinx.Graphics.Memory
} }
} }
public long MapLow(long PA, long Size)
{
lock (PageTable)
{
long VA = GetFreePosition(Size, 1, PageSize);
if (VA != -1 && (ulong)VA <= uint.MaxValue && (ulong)(VA + Size) <= uint.MaxValue)
{
for (long Offset = 0; Offset < Size; Offset += PageSize)
{
SetPte(VA + Offset, PA + Offset);
}
}
else
{
VA = -1;
}
return VA;
}
}
public long ReserveFixed(long VA, long Size) public long ReserveFixed(long VA, long Size)
{ {
lock (PageTable) lock (PageTable)
@ -122,11 +144,11 @@ namespace Ryujinx.Graphics.Memory
} }
} }
private long GetFreePosition(long Size, long Align = 1) private long GetFreePosition(long Size, long Align = 1, long Start = 1L << 32)
{ {
//Note: Address 0 is not considered valid by the driver, //Note: Address 0 is not considered valid by the driver,
//when 0 is returned it's considered a mapping error. //when 0 is returned it's considered a mapping error.
long Position = PageSize; long Position = Start;
long FreeSize = 0; long FreeSize = 0;
if (Align < 1) if (Align < 1)
@ -243,9 +265,9 @@ namespace Ryujinx.Graphics.Memory
return Cache.IsRegionModified(Memory, BufferType, PA, Size); return Cache.IsRegionModified(Memory, BufferType, PA, Size);
} }
public IntPtr GetHostAddress(long Position, long Size) public bool TryGetHostAddress(long Position, long Size, out IntPtr Ptr)
{ {
return Memory.GetHostAddress(GetPhysicalAddress(Position), Size); return Memory.TryGetHostAddress(GetPhysicalAddress(Position), Size, out Ptr);
} }
public byte ReadByte(long Position) public byte ReadByte(long Position)

View file

@ -1,4 +1,8 @@
using Ryujinx.Graphics.Gal; using Ryujinx.Graphics.Gal;
using Ryujinx.Graphics.Graphics3d;
using Ryujinx.Graphics.Memory;
using Ryujinx.Graphics.VDec;
using Ryujinx.Graphics.Vic;
namespace Ryujinx.Graphics namespace Ryujinx.Graphics
{ {
@ -16,6 +20,10 @@ namespace Ryujinx.Graphics
internal NvGpuEngineM2mf EngineM2mf { get; private set; } internal NvGpuEngineM2mf EngineM2mf { get; private set; }
internal NvGpuEngineP2mf EngineP2mf { get; private set; } internal NvGpuEngineP2mf EngineP2mf { get; private set; }
private CdmaProcessor CdmaProcessor;
internal VideoDecoder VideoDecoder { get; private set; }
internal VideoImageComposer VideoImageComposer { get; private set; }
public NvGpu(IGalRenderer Renderer) public NvGpu(IGalRenderer Renderer)
{ {
this.Renderer = Renderer; this.Renderer = Renderer;
@ -29,6 +37,26 @@ namespace Ryujinx.Graphics
Engine3d = new NvGpuEngine3d(this); Engine3d = new NvGpuEngine3d(this);
EngineM2mf = new NvGpuEngineM2mf(this); EngineM2mf = new NvGpuEngineM2mf(this);
EngineP2mf = new NvGpuEngineP2mf(this); EngineP2mf = new NvGpuEngineP2mf(this);
CdmaProcessor = new CdmaProcessor(this);
VideoDecoder = new VideoDecoder(this);
VideoImageComposer = new VideoImageComposer(this);
}
public void PushCommandBuffer(NvGpuVmm Vmm, int[] CmdBuffer)
{
lock (CdmaProcessor)
{
CdmaProcessor.PushCommands(Vmm, CmdBuffer);
}
}
public void UninitializeVideoDecoder()
{
lock (CdmaProcessor)
{
FFmpegWrapper.Uninitialize();
}
} }
} }
} }

View file

@ -14,6 +14,7 @@
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="FFmpeg.AutoGen" Version="4.0.0.4" />
<PackageReference Include="OpenTK.NetStandard" Version="1.0.4" /> <PackageReference Include="OpenTK.NetStandard" Version="1.0.4" />
</ItemGroup> </ItemGroup>

View file

@ -0,0 +1,75 @@
using System.IO;
namespace Ryujinx.Graphics.VDec
{
class BitStreamWriter
{
private const int BufferSize = 8;
private Stream BaseStream;
private int Buffer;
private int BufferPos;
public BitStreamWriter(Stream BaseStream)
{
this.BaseStream = BaseStream;
}
public void WriteBit(bool Value)
{
WriteBits(Value ? 1 : 0, 1);
}
public void WriteBits(int Value, int ValueSize)
{
int ValuePos = 0;
int Remaining = ValueSize;
while (Remaining > 0)
{
int CopySize = Remaining;
int Free = GetFreeBufferBits();
if (CopySize > Free)
{
CopySize = Free;
}
int Mask = (1 << CopySize) - 1;
int SrcShift = (ValueSize - ValuePos) - CopySize;
int DstShift = (BufferSize - BufferPos) - CopySize;
Buffer |= ((Value >> SrcShift) & Mask) << DstShift;
ValuePos += CopySize;
BufferPos += CopySize;
Remaining -= CopySize;
}
}
private int GetFreeBufferBits()
{
if (BufferPos == BufferSize)
{
Flush();
}
return BufferSize - BufferPos;
}
public void Flush()
{
if (BufferPos != 0)
{
BaseStream.WriteByte((byte)Buffer);
Buffer = 0;
BufferPos = 0;
}
}
}
}

View file

@ -0,0 +1,17 @@
using System;
namespace Ryujinx.Graphics.VDec
{
static class DecoderHelper
{
public static byte[] Combine(byte[] Arr0, byte[] Arr1)
{
byte[] Output = new byte[Arr0.Length + Arr1.Length];
Buffer.BlockCopy(Arr0, 0, Output, 0, Arr0.Length);
Buffer.BlockCopy(Arr1, 0, Output, Arr0.Length, Arr1.Length);
return Output;
}
}
}

View file

@ -0,0 +1,168 @@
using FFmpeg.AutoGen;
using System;
using System.Runtime.InteropServices;
namespace Ryujinx.Graphics.VDec
{
unsafe static class FFmpegWrapper
{
private static AVCodec* Codec;
private static AVCodecContext* Context;
private static AVFrame* Frame;
private static SwsContext* ScalerCtx;
private static int ScalerWidth;
private static int ScalerHeight;
public static bool IsInitialized { get; private set; }
public static void H264Initialize()
{
EnsureCodecInitialized(AVCodecID.AV_CODEC_ID_H264);
}
public static void Vp9Initialize()
{
EnsureCodecInitialized(AVCodecID.AV_CODEC_ID_VP9);
}
private static void EnsureCodecInitialized(AVCodecID CodecId)
{
if (IsInitialized)
{
Uninitialize();
}
Codec = ffmpeg.avcodec_find_decoder(CodecId);
Context = ffmpeg.avcodec_alloc_context3(Codec);
Frame = ffmpeg.av_frame_alloc();
ffmpeg.avcodec_open2(Context, Codec, null);
IsInitialized = true;
}
public static int DecodeFrame(byte[] Data)
{
if (!IsInitialized)
{
throw new InvalidOperationException("Tried to use uninitialized codec!");
}
AVPacket Packet;
ffmpeg.av_init_packet(&Packet);
fixed (byte* Ptr = Data)
{
Packet.data = Ptr;
Packet.size = Data.Length;
ffmpeg.avcodec_send_packet(Context, &Packet);
}
return ffmpeg.avcodec_receive_frame(Context, Frame);
}
public static FFmpegFrame GetFrame()
{
if (!IsInitialized)
{
throw new InvalidOperationException("Tried to use uninitialized codec!");
}
AVFrame ManagedFrame = Marshal.PtrToStructure<AVFrame>((IntPtr)Frame);
byte*[] Data = ManagedFrame.data.ToArray();
return new FFmpegFrame()
{
Width = ManagedFrame.width,
Height = ManagedFrame.height,
LumaPtr = Data[0],
ChromaBPtr = Data[1],
ChromaRPtr = Data[2]
};
}
public static FFmpegFrame GetFrameRgba()
{
if (!IsInitialized)
{
throw new InvalidOperationException("Tried to use uninitialized codec!");
}
AVFrame ManagedFrame = Marshal.PtrToStructure<AVFrame>((IntPtr)Frame);
EnsureScalerSetup(ManagedFrame.width, ManagedFrame.height);
byte*[] Data = ManagedFrame.data.ToArray();
int[] LineSizes = ManagedFrame.linesize.ToArray();
byte[] Dst = new byte[ManagedFrame.width * ManagedFrame.height * 4];
fixed (byte* Ptr = Dst)
{
byte*[] DstData = new byte*[] { Ptr };
int[] DstLineSizes = new int[] { ManagedFrame.width * 4 };
ffmpeg.sws_scale(ScalerCtx, Data, LineSizes, 0, ManagedFrame.height, DstData, DstLineSizes);
}
return new FFmpegFrame()
{
Width = ManagedFrame.width,
Height = ManagedFrame.height,
Data = Dst
};
}
private static void EnsureScalerSetup(int Width, int Height)
{
if (Width == 0 || Height == 0)
{
return;
}
if (ScalerCtx == null || ScalerWidth != Width || ScalerHeight != Height)
{
FreeScaler();
ScalerCtx = ffmpeg.sws_getContext(
Width, Height, AVPixelFormat.AV_PIX_FMT_YUV420P,
Width, Height, AVPixelFormat.AV_PIX_FMT_RGBA, 0, null, null, null);
ScalerWidth = Width;
ScalerHeight = Height;
}
}
public static void Uninitialize()
{
if (IsInitialized)
{
ffmpeg.av_frame_unref(Frame);
ffmpeg.av_free(Frame);
ffmpeg.avcodec_close(Context);
FreeScaler();
IsInitialized = false;
}
}
private static void FreeScaler()
{
if (ScalerCtx != null)
{
ffmpeg.sws_freeContext(ScalerCtx);
ScalerCtx = null;
}
}
}
}

View file

@ -0,0 +1,14 @@
namespace Ryujinx.Graphics.VDec
{
unsafe struct FFmpegFrame
{
public int Width;
public int Height;
public byte* LumaPtr;
public byte* ChromaBPtr;
public byte* ChromaRPtr;
public byte[] Data;
}
}

View file

@ -0,0 +1,79 @@
using System.IO;
namespace Ryujinx.Graphics.VDec
{
class H264BitStreamWriter : BitStreamWriter
{
public H264BitStreamWriter(Stream BaseStream) : base(BaseStream) { }
public void WriteU(int Value, int ValueSize)
{
WriteBits(Value, ValueSize);
}
public void WriteSe(int Value)
{
WriteExpGolombCodedInt(Value);
}
public void WriteUe(int Value)
{
WriteExpGolombCodedUInt((uint)Value);
}
public void End()
{
WriteBit(true);
Flush();
}
private void WriteExpGolombCodedInt(int Value)
{
int Sign = Value <= 0 ? 0 : 1;
if (Value < 0)
{
Value = -Value;
}
Value = (Value << 1) - Sign;
WriteExpGolombCodedUInt((uint)Value);
}
private void WriteExpGolombCodedUInt(uint Value)
{
int Size = 32 - CountLeadingZeros((int)Value + 1);
WriteBits(1, Size);
Value -= (1u << (Size - 1)) - 1;
WriteBits((int)Value, Size - 1);
}
private static readonly byte[] ClzNibbleTbl = { 4, 3, 2, 2, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0 };
private static int CountLeadingZeros(int Value)
{
if (Value == 0)
{
return 32;
}
int NibbleIdx = 32;
int PreCount, Count = 0;
do
{
NibbleIdx -= 4;
PreCount = ClzNibbleTbl[(Value >> NibbleIdx) & 0b1111];
Count += PreCount;
}
while (PreCount == 4);
return Count;
}
}
}

View file

@ -0,0 +1,238 @@
using System.IO;
namespace Ryujinx.Graphics.VDec
{
class H264Decoder
{
private int Log2MaxPicOrderCntLsbMinus4;
private bool DeltaPicOrderAlwaysZeroFlag;
private bool FrameMbsOnlyFlag;
private int PicWidthInMbs;
private int PicHeightInMapUnits;
private bool EntropyCodingModeFlag;
private bool BottomFieldPicOrderInFramePresentFlag;
private int NumRefIdxL0DefaultActiveMinus1;
private int NumRefIdxL1DefaultActiveMinus1;
private bool DeblockingFilterControlPresentFlag;
private bool RedundantPicCntPresentFlag;
private bool Transform8x8ModeFlag;
private bool MbAdaptiveFrameFieldFlag;
private bool Direct8x8InferenceFlag;
private bool WeightedPredFlag;
private bool ConstrainedIntraPredFlag;
private bool FieldPicFlag;
private bool BottomFieldFlag;
private int Log2MaxFrameNumMinus4;
private int ChromaFormatIdc;
private int PicOrderCntType;
private int PicInitQpMinus26;
private int ChromaQpIndexOffset;
private int ChromaQpIndexOffset2;
private int WeightedBipredIdc;
private int FrameNumber;
private byte[] ScalingMatrix4;
private byte[] ScalingMatrix8;
public void Decode(H264ParameterSets Params, H264Matrices Matrices, byte[] FrameData)
{
Log2MaxPicOrderCntLsbMinus4 = Params.Log2MaxPicOrderCntLsbMinus4;
DeltaPicOrderAlwaysZeroFlag = Params.DeltaPicOrderAlwaysZeroFlag;
FrameMbsOnlyFlag = Params.FrameMbsOnlyFlag;
PicWidthInMbs = Params.PicWidthInMbs;
PicHeightInMapUnits = Params.PicHeightInMapUnits;
EntropyCodingModeFlag = Params.EntropyCodingModeFlag;
BottomFieldPicOrderInFramePresentFlag = Params.BottomFieldPicOrderInFramePresentFlag;
NumRefIdxL0DefaultActiveMinus1 = Params.NumRefIdxL0DefaultActiveMinus1;
NumRefIdxL1DefaultActiveMinus1 = Params.NumRefIdxL1DefaultActiveMinus1;
DeblockingFilterControlPresentFlag = Params.DeblockingFilterControlPresentFlag;
RedundantPicCntPresentFlag = Params.RedundantPicCntPresentFlag;
Transform8x8ModeFlag = Params.Transform8x8ModeFlag;
MbAdaptiveFrameFieldFlag = ((Params.Flags >> 0) & 1) != 0;
Direct8x8InferenceFlag = ((Params.Flags >> 1) & 1) != 0;
WeightedPredFlag = ((Params.Flags >> 2) & 1) != 0;
ConstrainedIntraPredFlag = ((Params.Flags >> 3) & 1) != 0;
FieldPicFlag = ((Params.Flags >> 5) & 1) != 0;
BottomFieldFlag = ((Params.Flags >> 6) & 1) != 0;
Log2MaxFrameNumMinus4 = (int)(Params.Flags >> 8) & 0xf;
ChromaFormatIdc = (int)(Params.Flags >> 12) & 0x3;
PicOrderCntType = (int)(Params.Flags >> 14) & 0x3;
PicInitQpMinus26 = (int)(Params.Flags >> 16) & 0x3f;
ChromaQpIndexOffset = (int)(Params.Flags >> 22) & 0x1f;
ChromaQpIndexOffset2 = (int)(Params.Flags >> 27) & 0x1f;
WeightedBipredIdc = (int)(Params.Flags >> 32) & 0x3;
FrameNumber = (int)(Params.Flags >> 46) & 0x1ffff;
PicInitQpMinus26 = (PicInitQpMinus26 << 26) >> 26;
ChromaQpIndexOffset = (ChromaQpIndexOffset << 27) >> 27;
ChromaQpIndexOffset2 = (ChromaQpIndexOffset2 << 27) >> 27;
ScalingMatrix4 = Matrices.ScalingMatrix4;
ScalingMatrix8 = Matrices.ScalingMatrix8;
if (FFmpegWrapper.IsInitialized)
{
FFmpegWrapper.DecodeFrame(FrameData);
}
else
{
FFmpegWrapper.H264Initialize();
FFmpegWrapper.DecodeFrame(DecoderHelper.Combine(EncodeHeader(), FrameData));
}
}
private byte[] EncodeHeader()
{
using (MemoryStream Data = new MemoryStream())
{
H264BitStreamWriter Writer = new H264BitStreamWriter(Data);
//Sequence Parameter Set.
Writer.WriteU(1, 24);
Writer.WriteU(0, 1);
Writer.WriteU(3, 2);
Writer.WriteU(7, 5);
Writer.WriteU(100, 8);
Writer.WriteU(0, 8);
Writer.WriteU(31, 8);
Writer.WriteUe(0);
Writer.WriteUe(ChromaFormatIdc);
if (ChromaFormatIdc == 3)
{
Writer.WriteBit(false);
}
Writer.WriteUe(0);
Writer.WriteUe(0);
Writer.WriteBit(false);
Writer.WriteBit(false); //Scaling matrix present flag
Writer.WriteUe(Log2MaxFrameNumMinus4);
Writer.WriteUe(PicOrderCntType);
if (PicOrderCntType == 0)
{
Writer.WriteUe(Log2MaxPicOrderCntLsbMinus4);
}
else if (PicOrderCntType == 1)
{
Writer.WriteBit(DeltaPicOrderAlwaysZeroFlag);
Writer.WriteSe(0);
Writer.WriteSe(0);
Writer.WriteUe(0);
}
int PicHeightInMbs = PicHeightInMapUnits / (FrameMbsOnlyFlag ? 1 : 2);
Writer.WriteUe(16);
Writer.WriteBit(false);
Writer.WriteUe(PicWidthInMbs - 1);
Writer.WriteUe(PicHeightInMbs - 1);
Writer.WriteBit(FrameMbsOnlyFlag);
if (!FrameMbsOnlyFlag)
{
Writer.WriteBit(MbAdaptiveFrameFieldFlag);
}
Writer.WriteBit(Direct8x8InferenceFlag);
Writer.WriteBit(false); //Frame cropping flag
Writer.WriteBit(false); //VUI parameter present flag
Writer.End();
//Picture Parameter Set.
Writer.WriteU(1, 24);
Writer.WriteU(0, 1);
Writer.WriteU(3, 2);
Writer.WriteU(8, 5);
Writer.WriteUe(0);
Writer.WriteUe(0);
Writer.WriteBit(EntropyCodingModeFlag);
Writer.WriteBit(false);
Writer.WriteUe(0);
Writer.WriteUe(NumRefIdxL0DefaultActiveMinus1);
Writer.WriteUe(NumRefIdxL1DefaultActiveMinus1);
Writer.WriteBit(WeightedPredFlag);
Writer.WriteU(WeightedBipredIdc, 2);
Writer.WriteSe(PicInitQpMinus26);
Writer.WriteSe(0);
Writer.WriteSe(ChromaQpIndexOffset);
Writer.WriteBit(DeblockingFilterControlPresentFlag);
Writer.WriteBit(ConstrainedIntraPredFlag);
Writer.WriteBit(RedundantPicCntPresentFlag);
Writer.WriteBit(Transform8x8ModeFlag);
Writer.WriteBit(true);
for (int Index = 0; Index < 6; Index++)
{
Writer.WriteBit(true);
WriteScalingList(Writer, ScalingMatrix4, Index * 16, 16);
}
if (Transform8x8ModeFlag)
{
for (int Index = 0; Index < 2; Index++)
{
Writer.WriteBit(true);
WriteScalingList(Writer, ScalingMatrix8, Index * 64, 64);
}
}
Writer.WriteSe(ChromaQpIndexOffset2);
Writer.End();
return Data.ToArray();
}
}
//ZigZag LUTs from libavcodec.
private static readonly byte[] ZigZagDirect = new byte[]
{
0, 1, 8, 16, 9, 2, 3, 10,
17, 24, 32, 25, 18, 11, 4, 5,
12, 19, 26, 33, 40, 48, 41, 34,
27, 20, 13, 6, 7, 14, 21, 28,
35, 42, 49, 56, 57, 50, 43, 36,
29, 22, 15, 23, 30, 37, 44, 51,
58, 59, 52, 45, 38, 31, 39, 46,
53, 60, 61, 54, 47, 55, 62, 63
};
private static readonly byte[] ZigZagScan = new byte[]
{
0 + 0 * 4, 1 + 0 * 4, 0 + 1 * 4, 0 + 2 * 4,
1 + 1 * 4, 2 + 0 * 4, 3 + 0 * 4, 2 + 1 * 4,
1 + 2 * 4, 0 + 3 * 4, 1 + 3 * 4, 2 + 2 * 4,
3 + 1 * 4, 3 + 2 * 4, 2 + 3 * 4, 3 + 3 * 4
};
private static void WriteScalingList(H264BitStreamWriter Writer, byte[] List, int Start, int Count)
{
byte[] Scan = Count == 16 ? ZigZagScan : ZigZagDirect;
int LastScale = 8;
for (int Index = 0; Index < Count; Index++)
{
byte Value = List[Start + Scan[Index]];
int DeltaScale = Value - LastScale;
Writer.WriteSe(DeltaScale);
LastScale = Value;
}
}
}
}

View file

@ -0,0 +1,8 @@
namespace Ryujinx.Graphics.VDec
{
struct H264Matrices
{
public byte[] ScalingMatrix4;
public byte[] ScalingMatrix8;
}
}

View file

@ -0,0 +1,34 @@
using System.Runtime.InteropServices;
namespace Ryujinx.Graphics.VDec
{
[StructLayout(LayoutKind.Sequential, Pack = 4)]
struct H264ParameterSets
{
public int Log2MaxPicOrderCntLsbMinus4;
public bool DeltaPicOrderAlwaysZeroFlag;
public bool FrameMbsOnlyFlag;
public int PicWidthInMbs;
public int PicHeightInMapUnits;
public int Reserved6C;
public bool EntropyCodingModeFlag;
public bool BottomFieldPicOrderInFramePresentFlag;
public int NumRefIdxL0DefaultActiveMinus1;
public int NumRefIdxL1DefaultActiveMinus1;
public bool DeblockingFilterControlPresentFlag;
public bool RedundantPicCntPresentFlag;
public bool Transform8x8ModeFlag;
public int Unknown8C;
public int Unknown90;
public int Reserved94;
public int Unknown98;
public int Reserved9C;
public int ReservedA0;
public int UnknownA4;
public int ReservedA8;
public int UnknownAC;
public long Flags;
public int FrameNumber;
public int FrameNumber2;
}
}

View file

@ -0,0 +1,10 @@
namespace Ryujinx.Graphics.VDec
{
enum VideoCodec
{
H264 = 3,
Vp8 = 5,
H265 = 7,
Vp9 = 9
}
}

View file

@ -0,0 +1,280 @@
using ChocolArm64.Memory;
using Ryujinx.Graphics.Gal;
using Ryujinx.Graphics.Memory;
using Ryujinx.Graphics.Texture;
using Ryujinx.Graphics.Vic;
using System;
namespace Ryujinx.Graphics.VDec
{
unsafe class VideoDecoder
{
private NvGpu Gpu;
private H264Decoder H264Decoder;
private Vp9Decoder Vp9Decoder;
private VideoCodec CurrentVideoCodec;
private long DecoderContextAddress;
private long FrameDataAddress;
private long VpxCurrLumaAddress;
private long VpxRef0LumaAddress;
private long VpxRef1LumaAddress;
private long VpxRef2LumaAddress;
private long VpxCurrChromaAddress;
private long VpxRef0ChromaAddress;
private long VpxRef1ChromaAddress;
private long VpxRef2ChromaAddress;
private long VpxProbTablesAddress;
public VideoDecoder(NvGpu Gpu)
{
this.Gpu = Gpu;
H264Decoder = new H264Decoder();
Vp9Decoder = new Vp9Decoder();
}
public void Process(NvGpuVmm Vmm, int MethodOffset, int[] Arguments)
{
VideoDecoderMeth Method = (VideoDecoderMeth)MethodOffset;
switch (Method)
{
case VideoDecoderMeth.SetVideoCodec: SetVideoCodec (Vmm, Arguments); break;
case VideoDecoderMeth.Execute: Execute (Vmm, Arguments); break;
case VideoDecoderMeth.SetDecoderCtxAddr: SetDecoderCtxAddr (Vmm, Arguments); break;
case VideoDecoderMeth.SetFrameDataAddr: SetFrameDataAddr (Vmm, Arguments); break;
case VideoDecoderMeth.SetVpxCurrLumaAddr: SetVpxCurrLumaAddr (Vmm, Arguments); break;
case VideoDecoderMeth.SetVpxRef0LumaAddr: SetVpxRef0LumaAddr (Vmm, Arguments); break;
case VideoDecoderMeth.SetVpxRef1LumaAddr: SetVpxRef1LumaAddr (Vmm, Arguments); break;
case VideoDecoderMeth.SetVpxRef2LumaAddr: SetVpxRef2LumaAddr (Vmm, Arguments); break;
case VideoDecoderMeth.SetVpxCurrChromaAddr: SetVpxCurrChromaAddr(Vmm, Arguments); break;
case VideoDecoderMeth.SetVpxRef0ChromaAddr: SetVpxRef0ChromaAddr(Vmm, Arguments); break;
case VideoDecoderMeth.SetVpxRef1ChromaAddr: SetVpxRef1ChromaAddr(Vmm, Arguments); break;
case VideoDecoderMeth.SetVpxRef2ChromaAddr: SetVpxRef2ChromaAddr(Vmm, Arguments); break;
case VideoDecoderMeth.SetVpxProbTablesAddr: SetVpxProbTablesAddr(Vmm, Arguments); break;
}
}
private void SetVideoCodec(NvGpuVmm Vmm, int[] Arguments)
{
CurrentVideoCodec = (VideoCodec)Arguments[0];
}
private void Execute(NvGpuVmm Vmm, int[] Arguments)
{
if (CurrentVideoCodec == VideoCodec.H264)
{
int FrameDataSize = Vmm.ReadInt32(DecoderContextAddress + 0x48);
H264ParameterSets Params = MemoryHelper.Read<H264ParameterSets>(Vmm.Memory, Vmm.GetPhysicalAddress(DecoderContextAddress + 0x58));
H264Matrices Matrices = new H264Matrices()
{
ScalingMatrix4 = Vmm.ReadBytes(DecoderContextAddress + 0x1c0, 6 * 16),
ScalingMatrix8 = Vmm.ReadBytes(DecoderContextAddress + 0x220, 2 * 64)
};
byte[] FrameData = Vmm.ReadBytes(FrameDataAddress, FrameDataSize);
H264Decoder.Decode(Params, Matrices, FrameData);
}
else if (CurrentVideoCodec == VideoCodec.Vp9)
{
int FrameDataSize = Vmm.ReadInt32(DecoderContextAddress + 0x30);
Vp9FrameKeys Keys = new Vp9FrameKeys()
{
CurrKey = Vmm.GetPhysicalAddress(VpxCurrLumaAddress),
Ref0Key = Vmm.GetPhysicalAddress(VpxRef0LumaAddress),
Ref1Key = Vmm.GetPhysicalAddress(VpxRef1LumaAddress),
Ref2Key = Vmm.GetPhysicalAddress(VpxRef2LumaAddress)
};
Vp9FrameHeader Header = MemoryHelper.Read<Vp9FrameHeader>(Vmm.Memory, Vmm.GetPhysicalAddress(DecoderContextAddress + 0x48));
Vp9ProbabilityTables Probs = new Vp9ProbabilityTables()
{
SegmentationTreeProbs = Vmm.ReadBytes(VpxProbTablesAddress + 0x387, 0x7),
SegmentationPredProbs = Vmm.ReadBytes(VpxProbTablesAddress + 0x38e, 0x3),
Tx8x8Probs = Vmm.ReadBytes(VpxProbTablesAddress + 0x470, 0x2),
Tx16x16Probs = Vmm.ReadBytes(VpxProbTablesAddress + 0x472, 0x4),
Tx32x32Probs = Vmm.ReadBytes(VpxProbTablesAddress + 0x476, 0x6),
CoefProbs = Vmm.ReadBytes(VpxProbTablesAddress + 0x5a0, 0x900),
SkipProbs = Vmm.ReadBytes(VpxProbTablesAddress + 0x537, 0x3),
InterModeProbs = Vmm.ReadBytes(VpxProbTablesAddress + 0x400, 0x1c),
InterpFilterProbs = Vmm.ReadBytes(VpxProbTablesAddress + 0x52a, 0x8),
IsInterProbs = Vmm.ReadBytes(VpxProbTablesAddress + 0x41c, 0x4),
CompModeProbs = Vmm.ReadBytes(VpxProbTablesAddress + 0x532, 0x5),
SingleRefProbs = Vmm.ReadBytes(VpxProbTablesAddress + 0x580, 0xa),
CompRefProbs = Vmm.ReadBytes(VpxProbTablesAddress + 0x58a, 0x5),
YModeProbs0 = Vmm.ReadBytes(VpxProbTablesAddress + 0x480, 0x20),
YModeProbs1 = Vmm.ReadBytes(VpxProbTablesAddress + 0x47c, 0x4),
PartitionProbs = Vmm.ReadBytes(VpxProbTablesAddress + 0x4e0, 0x40),
MvJointProbs = Vmm.ReadBytes(VpxProbTablesAddress + 0x53b, 0x3),
MvSignProbs = Vmm.ReadBytes(VpxProbTablesAddress + 0x53e, 0x3),
MvClassProbs = Vmm.ReadBytes(VpxProbTablesAddress + 0x54c, 0x14),
MvClass0BitProbs = Vmm.ReadBytes(VpxProbTablesAddress + 0x540, 0x3),
MvBitsProbs = Vmm.ReadBytes(VpxProbTablesAddress + 0x56c, 0x14),
MvClass0FrProbs = Vmm.ReadBytes(VpxProbTablesAddress + 0x560, 0xc),
MvFrProbs = Vmm.ReadBytes(VpxProbTablesAddress + 0x542, 0x6),
MvClass0HpProbs = Vmm.ReadBytes(VpxProbTablesAddress + 0x548, 0x2),
MvHpProbs = Vmm.ReadBytes(VpxProbTablesAddress + 0x54a, 0x2)
};
byte[] FrameData = Vmm.ReadBytes(FrameDataAddress, FrameDataSize);
Vp9Decoder.Decode(Keys, Header, Probs, FrameData);
}
else
{
ThrowUnimplementedCodec();
}
}
private void SetDecoderCtxAddr(NvGpuVmm Vmm, int[] Arguments)
{
DecoderContextAddress = GetAddress(Arguments);
}
private void SetFrameDataAddr(NvGpuVmm Vmm, int[] Arguments)
{
FrameDataAddress = GetAddress(Arguments);
}
private void SetVpxCurrLumaAddr(NvGpuVmm Vmm, int[] Arguments)
{
VpxCurrLumaAddress = GetAddress(Arguments);
}
private void SetVpxRef0LumaAddr(NvGpuVmm Vmm, int[] Arguments)
{
VpxRef0LumaAddress = GetAddress(Arguments);
}
private void SetVpxRef1LumaAddr(NvGpuVmm Vmm, int[] Arguments)
{
VpxRef1LumaAddress = GetAddress(Arguments);
}
private void SetVpxRef2LumaAddr(NvGpuVmm Vmm, int[] Arguments)
{
VpxRef2LumaAddress = GetAddress(Arguments);
}
private void SetVpxCurrChromaAddr(NvGpuVmm Vmm, int[] Arguments)
{
VpxCurrChromaAddress = GetAddress(Arguments);
}
private void SetVpxRef0ChromaAddr(NvGpuVmm Vmm, int[] Arguments)
{
VpxRef0ChromaAddress = GetAddress(Arguments);
}
private void SetVpxRef1ChromaAddr(NvGpuVmm Vmm, int[] Arguments)
{
VpxRef1ChromaAddress = GetAddress(Arguments);
}
private void SetVpxRef2ChromaAddr(NvGpuVmm Vmm, int[] Arguments)
{
VpxRef2ChromaAddress = GetAddress(Arguments);
}
private void SetVpxProbTablesAddr(NvGpuVmm Vmm, int[] Arguments)
{
VpxProbTablesAddress = GetAddress(Arguments);
}
private static long GetAddress(int[] Arguments)
{
return (long)(uint)Arguments[0] << 8;
}
internal void CopyPlanes(NvGpuVmm Vmm, SurfaceOutputConfig OutputConfig)
{
switch (OutputConfig.PixelFormat)
{
case SurfacePixelFormat.RGBA8: CopyPlanesRgba8 (Vmm, OutputConfig); break;
case SurfacePixelFormat.YUV420P: CopyPlanesYuv420p(Vmm, OutputConfig); break;
default: ThrowUnimplementedPixelFormat(OutputConfig.PixelFormat); break;
}
}
private void CopyPlanesRgba8(NvGpuVmm Vmm, SurfaceOutputConfig OutputConfig)
{
FFmpegFrame Frame = FFmpegWrapper.GetFrameRgba();
if ((Frame.Width | Frame.Height) == 0)
{
return;
}
GalImage Image = new GalImage(
OutputConfig.SurfaceWidth,
OutputConfig.SurfaceHeight, 1,
OutputConfig.GobBlockHeight,
GalMemoryLayout.BlockLinear,
GalImageFormat.RGBA8 | GalImageFormat.Unorm);
ImageUtils.WriteTexture(Vmm, Image, Vmm.GetPhysicalAddress(OutputConfig.SurfaceLumaAddress), Frame.Data);
}
private void CopyPlanesYuv420p(NvGpuVmm Vmm, SurfaceOutputConfig OutputConfig)
{
FFmpegFrame Frame = FFmpegWrapper.GetFrame();
if ((Frame.Width | Frame.Height) == 0)
{
return;
}
int HalfSrcWidth = Frame.Width / 2;
int HalfWidth = Frame.Width / 2;
int HalfHeight = Frame.Height / 2;
int AlignedWidth = (OutputConfig.SurfaceWidth + 0xff) & ~0xff;
for (int Y = 0; Y < Frame.Height; Y++)
{
int Src = Y * Frame.Width;
int Dst = Y * AlignedWidth;
int Size = Frame.Width;
for (int Offset = 0; Offset < Size; Offset++)
{
Vmm.WriteByte(OutputConfig.SurfaceLumaAddress + Dst + Offset, *(Frame.LumaPtr + Src + Offset));
}
}
//Copy chroma data from both channels with interleaving.
for (int Y = 0; Y < HalfHeight; Y++)
{
int Src = Y * HalfSrcWidth;
int Dst = Y * AlignedWidth;
for (int X = 0; X < HalfWidth; X++)
{
Vmm.WriteByte(OutputConfig.SurfaceChromaUAddress + Dst + X * 2 + 0, *(Frame.ChromaBPtr + Src + X));
Vmm.WriteByte(OutputConfig.SurfaceChromaUAddress + Dst + X * 2 + 1, *(Frame.ChromaRPtr + Src + X));
}
}
}
private void ThrowUnimplementedCodec()
{
throw new NotImplementedException("Codec \"" + CurrentVideoCodec + "\" is not supported!");
}
private void ThrowUnimplementedPixelFormat(SurfacePixelFormat PixelFormat)
{
throw new NotImplementedException("Pixel format \"" + PixelFormat + "\" is not supported!");
}
}
}

View file

@ -0,0 +1,19 @@
namespace Ryujinx.Graphics.VDec
{
enum VideoDecoderMeth
{
SetVideoCodec = 0x80,
Execute = 0xc0,
SetDecoderCtxAddr = 0x101,
SetFrameDataAddr = 0x102,
SetVpxRef0LumaAddr = 0x10c,
SetVpxRef1LumaAddr = 0x10d,
SetVpxRef2LumaAddr = 0x10e,
SetVpxCurrLumaAddr = 0x10f,
SetVpxRef0ChromaAddr = 0x11d,
SetVpxRef1ChromaAddr = 0x11e,
SetVpxRef2ChromaAddr = 0x11f,
SetVpxCurrChromaAddr = 0x120,
SetVpxProbTablesAddr = 0x170
}
}

View file

@ -0,0 +1,879 @@
using System.Collections.Generic;
using System.IO;
namespace Ryujinx.Graphics.VDec
{
class Vp9Decoder
{
private const int DiffUpdateProbability = 252;
private const int FrameSyncCode = 0x498342;
private static readonly int[] MapLut = new int[]
{
20, 21, 22, 23, 24, 25, 0, 26, 27, 28, 29, 30, 31, 32, 33, 34,
35, 36, 37, 1, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49,
2, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 3, 62, 63,
64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 4, 74, 75, 76, 77, 78,
79, 80, 81, 82, 83, 84, 85, 5, 86, 87, 88, 89, 90, 91, 92, 93,
94, 95, 96, 97, 6, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108,
109, 7, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 8, 122,
123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 9, 134, 135, 136, 137,
138, 139, 140, 141, 142, 143, 144, 145, 10, 146, 147, 148, 149, 150, 151, 152,
153, 154, 155, 156, 157, 11, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167,
168, 169, 12, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 13,
182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 14, 194, 195, 196,
197, 198, 199, 200, 201, 202, 203, 204, 205, 15, 206, 207, 208, 209, 210, 211,
212, 213, 214, 215, 216, 217, 16, 218, 219, 220, 221, 222, 223, 224, 225, 226,
227, 228, 229, 17, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241,
18, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 19
};
private byte[] DefaultTx8x8Probs = new byte[] { 100, 66 };
private byte[] DefaultTx16x16Probs = new byte[] { 20, 152, 15, 101 };
private byte[] DefaultTx32x32Probs = new byte[] { 3, 136, 37, 5, 52, 13 };
private byte[] DefaultCoefProbs = new byte[]
{
195, 29, 183, 0, 84, 49, 136, 0, 8, 42, 71, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 31, 107, 169, 0, 35, 99, 159, 0,
17, 82, 140, 0, 8, 66, 114, 0, 2, 44, 76, 0, 1, 19, 32, 0,
40, 132, 201, 0, 29, 114, 187, 0, 13, 91, 157, 0, 7, 75, 127, 0,
3, 58, 95, 0, 1, 28, 47, 0, 69, 142, 221, 0, 42, 122, 201, 0,
15, 91, 159, 0, 6, 67, 121, 0, 1, 42, 77, 0, 1, 17, 31, 0,
102, 148, 228, 0, 67, 117, 204, 0, 17, 82, 154, 0, 6, 59, 114, 0,
2, 39, 75, 0, 1, 15, 29, 0, 156, 57, 233, 0, 119, 57, 212, 0,
58, 48, 163, 0, 29, 40, 124, 0, 12, 30, 81, 0, 3, 12, 31, 0,
191, 107, 226, 0, 124, 117, 204, 0, 25, 99, 155, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 29, 148, 210, 0, 37, 126, 194, 0,
8, 93, 157, 0, 2, 68, 118, 0, 1, 39, 69, 0, 1, 17, 33, 0,
41, 151, 213, 0, 27, 123, 193, 0, 3, 82, 144, 0, 1, 58, 105, 0,
1, 32, 60, 0, 1, 13, 26, 0, 59, 159, 220, 0, 23, 126, 198, 0,
4, 88, 151, 0, 1, 66, 114, 0, 1, 38, 71, 0, 1, 18, 34, 0,
114, 136, 232, 0, 51, 114, 207, 0, 11, 83, 155, 0, 3, 56, 105, 0,
1, 33, 65, 0, 1, 17, 34, 0, 149, 65, 234, 0, 121, 57, 215, 0,
61, 49, 166, 0, 28, 36, 114, 0, 12, 25, 76, 0, 3, 16, 42, 0,
214, 49, 220, 0, 132, 63, 188, 0, 42, 65, 137, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 85, 137, 221, 0, 104, 131, 216, 0,
49, 111, 192, 0, 21, 87, 155, 0, 2, 49, 87, 0, 1, 16, 28, 0,
89, 163, 230, 0, 90, 137, 220, 0, 29, 100, 183, 0, 10, 70, 135, 0,
2, 42, 81, 0, 1, 17, 33, 0, 108, 167, 237, 0, 55, 133, 222, 0,
15, 97, 179, 0, 4, 72, 135, 0, 1, 45, 85, 0, 1, 19, 38, 0,
124, 146, 240, 0, 66, 124, 224, 0, 17, 88, 175, 0, 4, 58, 122, 0,
1, 36, 75, 0, 1, 18, 37, 0, 141, 79, 241, 0, 126, 70, 227, 0,
66, 58, 182, 0, 30, 44, 136, 0, 12, 34, 96, 0, 2, 20, 47, 0,
229, 99, 249, 0, 143, 111, 235, 0, 46, 109, 192, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 82, 158, 236, 0, 94, 146, 224, 0,
25, 117, 191, 0, 9, 87, 149, 0, 3, 56, 99, 0, 1, 33, 57, 0,
83, 167, 237, 0, 68, 145, 222, 0, 10, 103, 177, 0, 2, 72, 131, 0,
1, 41, 79, 0, 1, 20, 39, 0, 99, 167, 239, 0, 47, 141, 224, 0,
10, 104, 178, 0, 2, 73, 133, 0, 1, 44, 85, 0, 1, 22, 47, 0,
127, 145, 243, 0, 71, 129, 228, 0, 17, 93, 177, 0, 3, 61, 124, 0,
1, 41, 84, 0, 1, 21, 52, 0, 157, 78, 244, 0, 140, 72, 231, 0,
69, 58, 184, 0, 31, 44, 137, 0, 14, 38, 105, 0, 8, 23, 61, 0,
125, 34, 187, 0, 52, 41, 133, 0, 6, 31, 56, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 37, 109, 153, 0, 51, 102, 147, 0,
23, 87, 128, 0, 8, 67, 101, 0, 1, 41, 63, 0, 1, 19, 29, 0,
31, 154, 185, 0, 17, 127, 175, 0, 6, 96, 145, 0, 2, 73, 114, 0,
1, 51, 82, 0, 1, 28, 45, 0, 23, 163, 200, 0, 10, 131, 185, 0,
2, 93, 148, 0, 1, 67, 111, 0, 1, 41, 69, 0, 1, 14, 24, 0,
29, 176, 217, 0, 12, 145, 201, 0, 3, 101, 156, 0, 1, 69, 111, 0,
1, 39, 63, 0, 1, 14, 23, 0, 57, 192, 233, 0, 25, 154, 215, 0,
6, 109, 167, 0, 3, 78, 118, 0, 1, 48, 69, 0, 1, 21, 29, 0,
202, 105, 245, 0, 108, 106, 216, 0, 18, 90, 144, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 33, 172, 219, 0, 64, 149, 206, 0,
14, 117, 177, 0, 5, 90, 141, 0, 2, 61, 95, 0, 1, 37, 57, 0,
33, 179, 220, 0, 11, 140, 198, 0, 1, 89, 148, 0, 1, 60, 104, 0,
1, 33, 57, 0, 1, 12, 21, 0, 30, 181, 221, 0, 8, 141, 198, 0,
1, 87, 145, 0, 1, 58, 100, 0, 1, 31, 55, 0, 1, 12, 20, 0,
32, 186, 224, 0, 7, 142, 198, 0, 1, 86, 143, 0, 1, 58, 100, 0,
1, 31, 55, 0, 1, 12, 22, 0, 57, 192, 227, 0, 20, 143, 204, 0,
3, 96, 154, 0, 1, 68, 112, 0, 1, 42, 69, 0, 1, 19, 32, 0,
212, 35, 215, 0, 113, 47, 169, 0, 29, 48, 105, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 74, 129, 203, 0, 106, 120, 203, 0,
49, 107, 178, 0, 19, 84, 144, 0, 4, 50, 84, 0, 1, 15, 25, 0,
71, 172, 217, 0, 44, 141, 209, 0, 15, 102, 173, 0, 6, 76, 133, 0,
2, 51, 89, 0, 1, 24, 42, 0, 64, 185, 231, 0, 31, 148, 216, 0,
8, 103, 175, 0, 3, 74, 131, 0, 1, 46, 81, 0, 1, 18, 30, 0,
65, 196, 235, 0, 25, 157, 221, 0, 5, 105, 174, 0, 1, 67, 120, 0,
1, 38, 69, 0, 1, 15, 30, 0, 65, 204, 238, 0, 30, 156, 224, 0,
7, 107, 177, 0, 2, 70, 124, 0, 1, 42, 73, 0, 1, 18, 34, 0,
225, 86, 251, 0, 144, 104, 235, 0, 42, 99, 181, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 85, 175, 239, 0, 112, 165, 229, 0,
29, 136, 200, 0, 12, 103, 162, 0, 6, 77, 123, 0, 2, 53, 84, 0,
75, 183, 239, 0, 30, 155, 221, 0, 3, 106, 171, 0, 1, 74, 128, 0,
1, 44, 76, 0, 1, 17, 28, 0, 73, 185, 240, 0, 27, 159, 222, 0,
2, 107, 172, 0, 1, 75, 127, 0, 1, 42, 73, 0, 1, 17, 29, 0,
62, 190, 238, 0, 21, 159, 222, 0, 2, 107, 172, 0, 1, 72, 122, 0,
1, 40, 71, 0, 1, 18, 32, 0, 61, 199, 240, 0, 27, 161, 226, 0,
4, 113, 180, 0, 1, 76, 129, 0, 1, 46, 80, 0, 1, 23, 41, 0,
7, 27, 153, 0, 5, 30, 95, 0, 1, 16, 30, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 50, 75, 127, 0, 57, 75, 124, 0,
27, 67, 108, 0, 10, 54, 86, 0, 1, 33, 52, 0, 1, 12, 18, 0,
43, 125, 151, 0, 26, 108, 148, 0, 7, 83, 122, 0, 2, 59, 89, 0,
1, 38, 60, 0, 1, 17, 27, 0, 23, 144, 163, 0, 13, 112, 154, 0,
2, 75, 117, 0, 1, 50, 81, 0, 1, 31, 51, 0, 1, 14, 23, 0,
18, 162, 185, 0, 6, 123, 171, 0, 1, 78, 125, 0, 1, 51, 86, 0,
1, 31, 54, 0, 1, 14, 23, 0, 15, 199, 227, 0, 3, 150, 204, 0,
1, 91, 146, 0, 1, 55, 95, 0, 1, 30, 53, 0, 1, 11, 20, 0,
19, 55, 240, 0, 19, 59, 196, 0, 3, 52, 105, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 41, 166, 207, 0, 104, 153, 199, 0,
31, 123, 181, 0, 14, 101, 152, 0, 5, 72, 106, 0, 1, 36, 52, 0,
35, 176, 211, 0, 12, 131, 190, 0, 2, 88, 144, 0, 1, 60, 101, 0,
1, 36, 60, 0, 1, 16, 28, 0, 28, 183, 213, 0, 8, 134, 191, 0,
1, 86, 142, 0, 1, 56, 96, 0, 1, 30, 53, 0, 1, 12, 20, 0,
20, 190, 215, 0, 4, 135, 192, 0, 1, 84, 139, 0, 1, 53, 91, 0,
1, 28, 49, 0, 1, 11, 20, 0, 13, 196, 216, 0, 2, 137, 192, 0,
1, 86, 143, 0, 1, 57, 99, 0, 1, 32, 56, 0, 1, 13, 24, 0,
211, 29, 217, 0, 96, 47, 156, 0, 22, 43, 87, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 78, 120, 193, 0, 111, 116, 186, 0,
46, 102, 164, 0, 15, 80, 128, 0, 2, 49, 76, 0, 1, 18, 28, 0,
71, 161, 203, 0, 42, 132, 192, 0, 10, 98, 150, 0, 3, 69, 109, 0,
1, 44, 70, 0, 1, 18, 29, 0, 57, 186, 211, 0, 30, 140, 196, 0,
4, 93, 146, 0, 1, 62, 102, 0, 1, 38, 65, 0, 1, 16, 27, 0,
47, 199, 217, 0, 14, 145, 196, 0, 1, 88, 142, 0, 1, 57, 98, 0,
1, 36, 62, 0, 1, 15, 26, 0, 26, 219, 229, 0, 5, 155, 207, 0,
1, 94, 151, 0, 1, 60, 104, 0, 1, 36, 62, 0, 1, 16, 28, 0,
233, 29, 248, 0, 146, 47, 220, 0, 43, 52, 140, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 100, 163, 232, 0, 179, 161, 222, 0,
63, 142, 204, 0, 37, 113, 174, 0, 26, 89, 137, 0, 18, 68, 97, 0,
85, 181, 230, 0, 32, 146, 209, 0, 7, 100, 164, 0, 3, 71, 121, 0,
1, 45, 77, 0, 1, 18, 30, 0, 65, 187, 230, 0, 20, 148, 207, 0,
2, 97, 159, 0, 1, 68, 116, 0, 1, 40, 70, 0, 1, 14, 29, 0,
40, 194, 227, 0, 8, 147, 204, 0, 1, 94, 155, 0, 1, 65, 112, 0,
1, 39, 66, 0, 1, 14, 26, 0, 16, 208, 228, 0, 3, 151, 207, 0,
1, 98, 160, 0, 1, 67, 117, 0, 1, 41, 74, 0, 1, 17, 31, 0,
17, 38, 140, 0, 7, 34, 80, 0, 1, 17, 29, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 37, 75, 128, 0, 41, 76, 128, 0,
26, 66, 116, 0, 12, 52, 94, 0, 2, 32, 55, 0, 1, 10, 16, 0,
50, 127, 154, 0, 37, 109, 152, 0, 16, 82, 121, 0, 5, 59, 85, 0,
1, 35, 54, 0, 1, 13, 20, 0, 40, 142, 167, 0, 17, 110, 157, 0,
2, 71, 112, 0, 1, 44, 72, 0, 1, 27, 45, 0, 1, 11, 17, 0,
30, 175, 188, 0, 9, 124, 169, 0, 1, 74, 116, 0, 1, 48, 78, 0,
1, 30, 49, 0, 1, 11, 18, 0, 10, 222, 223, 0, 2, 150, 194, 0,
1, 83, 128, 0, 1, 48, 79, 0, 1, 27, 45, 0, 1, 11, 17, 0,
36, 41, 235, 0, 29, 36, 193, 0, 10, 27, 111, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 85, 165, 222, 0, 177, 162, 215, 0,
110, 135, 195, 0, 57, 113, 168, 0, 23, 83, 120, 0, 10, 49, 61, 0,
85, 190, 223, 0, 36, 139, 200, 0, 5, 90, 146, 0, 1, 60, 103, 0,
1, 38, 65, 0, 1, 18, 30, 0, 72, 202, 223, 0, 23, 141, 199, 0,
2, 86, 140, 0, 1, 56, 97, 0, 1, 36, 61, 0, 1, 16, 27, 0,
55, 218, 225, 0, 13, 145, 200, 0, 1, 86, 141, 0, 1, 57, 99, 0,
1, 35, 61, 0, 1, 13, 22, 0, 15, 235, 212, 0, 1, 132, 184, 0,
1, 84, 139, 0, 1, 57, 97, 0, 1, 34, 56, 0, 1, 14, 23, 0,
181, 21, 201, 0, 61, 37, 123, 0, 10, 38, 71, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 47, 106, 172, 0, 95, 104, 173, 0,
42, 93, 159, 0, 18, 77, 131, 0, 4, 50, 81, 0, 1, 17, 23, 0,
62, 147, 199, 0, 44, 130, 189, 0, 28, 102, 154, 0, 18, 75, 115, 0,
2, 44, 65, 0, 1, 12, 19, 0, 55, 153, 210, 0, 24, 130, 194, 0,
3, 93, 146, 0, 1, 61, 97, 0, 1, 31, 50, 0, 1, 10, 16, 0,
49, 186, 223, 0, 17, 148, 204, 0, 1, 96, 142, 0, 1, 53, 83, 0,
1, 26, 44, 0, 1, 11, 17, 0, 13, 217, 212, 0, 2, 136, 180, 0,
1, 78, 124, 0, 1, 50, 83, 0, 1, 29, 49, 0, 1, 14, 23, 0,
197, 13, 247, 0, 82, 17, 222, 0, 25, 17, 162, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 126, 186, 247, 0, 234, 191, 243, 0,
176, 177, 234, 0, 104, 158, 220, 0, 66, 128, 186, 0, 55, 90, 137, 0,
111, 197, 242, 0, 46, 158, 219, 0, 9, 104, 171, 0, 2, 65, 125, 0,
1, 44, 80, 0, 1, 17, 91, 0, 104, 208, 245, 0, 39, 168, 224, 0,
3, 109, 162, 0, 1, 79, 124, 0, 1, 50, 102, 0, 1, 43, 102, 0,
84, 220, 246, 0, 31, 177, 231, 0, 2, 115, 180, 0, 1, 79, 134, 0,
1, 55, 77, 0, 1, 60, 79, 0, 43, 243, 240, 0, 8, 180, 217, 0,
1, 115, 166, 0, 1, 84, 121, 0, 1, 51, 67, 0, 1, 16, 6, 0
};
private byte[] DefaultSkipProbs = new byte[] { 192, 128, 64 };
private byte[] DefaultInterModeProbs = new byte[]
{
2, 173, 34, 0, 7, 145, 85, 0, 7, 166, 63, 0, 7, 94, 66, 0,
8, 64, 46, 0, 17, 81, 31, 0, 25, 29, 30, 0
};
private byte[] DefaultInterpFilterProbs = new byte[]
{
235, 162, 36, 255, 34, 3, 149, 144
};
private byte[] DefaultIsInterProbs = new byte[] { 9, 102, 187, 225 };
private byte[] DefaultCompModeProbs = new byte[] { 239, 183, 119, 96, 41 };
private byte[] DefaultSingleRefProbs = new byte[]
{
33, 16, 77, 74, 142, 142, 172, 170, 238, 247
};
private byte[] DefaultCompRefProbs = new byte[] { 50, 126, 123, 221, 226 };
private byte[] DefaultYModeProbs0 = new byte[]
{
65, 32, 18, 144, 162, 194, 41, 51, 132, 68, 18, 165, 217, 196, 45, 40,
173, 80, 19, 176, 240, 193, 64, 35, 221, 135, 38, 194, 248, 121, 96, 85
};
private byte[] DefaultYModeProbs1 = new byte[] { 98, 78, 46, 29 };
private byte[] DefaultPartitionProbs = new byte[]
{
199, 122, 141, 0, 147, 63, 159, 0, 148, 133, 118, 0, 121, 104, 114, 0,
174, 73, 87, 0, 92, 41, 83, 0, 82, 99, 50, 0, 53, 39, 39, 0,
177, 58, 59, 0, 68, 26, 63, 0, 52, 79, 25, 0, 17, 14, 12, 0,
222, 34, 30, 0, 72, 16, 44, 0, 58, 32, 12, 0, 10, 7, 6, 0
};
private byte[] DefaultMvJointProbs = new byte[] { 32, 64, 96 };
private byte[] DefaultMvSignProbs = new byte[] { 128, 128 };
private byte[] DefaultMvClassProbs = new byte[]
{
224, 144, 192, 168, 192, 176, 192, 198, 198, 245, 216, 128, 176, 160, 176, 176,
192, 198, 198, 208
};
private byte[] DefaultMvClass0BitProbs = new byte[] { 216, 208 };
private byte[] DefaultMvBitsProbs = new byte[]
{
136, 140, 148, 160, 176, 192, 224, 234, 234, 240, 136, 140, 148, 160, 176, 192,
224, 234, 234, 240
};
private byte[] DefaultMvClass0FrProbs = new byte[]
{
128, 128, 64, 96, 112, 64, 128, 128, 64, 96, 112, 64
};
private byte[] DefaultMvFrProbs = new byte[] { 64, 96, 64, 64, 96, 64 };
private byte[] DefaultMvClass0HpProbs = new byte[] { 160, 160 };
private byte[] DefaultMvHpProbs = new byte[] { 128, 128 };
private sbyte[] LoopFilterRefDeltas;
private sbyte[] LoopFilterModeDeltas;
private LinkedList<int> FrameSlotByLastUse;
private Dictionary<long, LinkedListNode<int>> CachedRefFrames;
public Vp9Decoder()
{
LoopFilterRefDeltas = new sbyte[4];
LoopFilterModeDeltas = new sbyte[2];
FrameSlotByLastUse = new LinkedList<int>();
for (int Slot = 0; Slot < 8; Slot++)
{
FrameSlotByLastUse.AddFirst(Slot);
}
CachedRefFrames = new Dictionary<long, LinkedListNode<int>>();
}
public void Decode(
Vp9FrameKeys Keys,
Vp9FrameHeader Header,
Vp9ProbabilityTables Probs,
byte[] FrameData)
{
bool IsKeyFrame = ((Header.Flags >> 0) & 1) != 0;
bool LastIsKeyFrame = ((Header.Flags >> 1) & 1) != 0;
bool FrameSizeChanged = ((Header.Flags >> 2) & 1) != 0;
bool ErrorResilientMode = ((Header.Flags >> 3) & 1) != 0;
bool LastShowFrame = ((Header.Flags >> 4) & 1) != 0;
bool IsFrameIntra = ((Header.Flags >> 5) & 1) != 0;
bool ShowFrame = !IsFrameIntra;
//Write compressed header.
byte[] CompressedHeaderData;
using (MemoryStream CompressedHeader = new MemoryStream())
{
VpxRangeEncoder Writer = new VpxRangeEncoder(CompressedHeader);
if (!Header.Lossless)
{
if ((uint)Header.TxMode >= 3)
{
Writer.Write(3, 2);
Writer.Write(Header.TxMode == 4);
}
else
{
Writer.Write(Header.TxMode, 2);
}
}
if (Header.TxMode == 4)
{
WriteProbabilityUpdate(Writer, Probs.Tx8x8Probs, DefaultTx8x8Probs);
WriteProbabilityUpdate(Writer, Probs.Tx16x16Probs, DefaultTx16x16Probs);
WriteProbabilityUpdate(Writer, Probs.Tx32x32Probs, DefaultTx32x32Probs);
}
WriteCoefProbabilityUpdate(Writer, Header.TxMode, Probs.CoefProbs, DefaultCoefProbs);
WriteProbabilityUpdate(Writer, Probs.SkipProbs, DefaultSkipProbs);
if (!IsFrameIntra)
{
WriteProbabilityUpdateAligned4(Writer, Probs.InterModeProbs, DefaultInterModeProbs);
if (Header.RawInterpolationFilter == 4)
{
WriteProbabilityUpdate(Writer, Probs.InterpFilterProbs, DefaultInterpFilterProbs);
}
WriteProbabilityUpdate(Writer, Probs.IsInterProbs, DefaultIsInterProbs);
if ((Header.RefFrameSignBias[1] & 1) != (Header.RefFrameSignBias[2] & 1) ||
(Header.RefFrameSignBias[1] & 1) != (Header.RefFrameSignBias[3] & 1))
{
if ((uint)Header.CompPredMode >= 1)
{
Writer.Write(1, 1);
Writer.Write(Header.CompPredMode == 2);
}
else
{
Writer.Write(0, 1);
}
}
if (Header.CompPredMode == 2)
{
WriteProbabilityUpdate(Writer, Probs.CompModeProbs, DefaultCompModeProbs);
}
if (Header.CompPredMode != 1)
{
WriteProbabilityUpdate(Writer, Probs.SingleRefProbs, DefaultSingleRefProbs);
}
if (Header.CompPredMode != 0)
{
WriteProbabilityUpdate(Writer, Probs.CompRefProbs, DefaultCompRefProbs);
}
for (int Index = 0; Index < 4; Index++)
{
int i = Index * 8;
int j = Index;
WriteProbabilityUpdate(Writer, Probs.YModeProbs0[i + 0], DefaultYModeProbs0[i + 0]);
WriteProbabilityUpdate(Writer, Probs.YModeProbs0[i + 1], DefaultYModeProbs0[i + 1]);
WriteProbabilityUpdate(Writer, Probs.YModeProbs0[i + 2], DefaultYModeProbs0[i + 2]);
WriteProbabilityUpdate(Writer, Probs.YModeProbs0[i + 3], DefaultYModeProbs0[i + 3]);
WriteProbabilityUpdate(Writer, Probs.YModeProbs0[i + 4], DefaultYModeProbs0[i + 4]);
WriteProbabilityUpdate(Writer, Probs.YModeProbs0[i + 5], DefaultYModeProbs0[i + 5]);
WriteProbabilityUpdate(Writer, Probs.YModeProbs0[i + 6], DefaultYModeProbs0[i + 6]);
WriteProbabilityUpdate(Writer, Probs.YModeProbs0[i + 7], DefaultYModeProbs0[i + 7]);
WriteProbabilityUpdate(Writer, Probs.YModeProbs1[j + 0], DefaultYModeProbs1[j + 0]);
}
WriteProbabilityUpdateAligned4(Writer, Probs.PartitionProbs, DefaultPartitionProbs);
for (int i = 0; i < 3; i++)
{
WriteMvProbabilityUpdate(Writer, Probs.MvJointProbs[i], DefaultMvJointProbs[i]);
}
for (int i = 0; i < 2; i++)
{
WriteMvProbabilityUpdate(Writer, Probs.MvSignProbs[i], DefaultMvSignProbs[i]);
for (int j = 0; j < 10; j++)
{
int Index = i * 10 + j;
WriteMvProbabilityUpdate(Writer, Probs.MvClassProbs[Index], DefaultMvClassProbs[Index]);
}
WriteMvProbabilityUpdate(Writer, Probs.MvClass0BitProbs[i], DefaultMvClass0BitProbs[i]);
for (int j = 0; j < 10; j++)
{
int Index = i * 10 + j;
WriteMvProbabilityUpdate(Writer, Probs.MvBitsProbs[Index], DefaultMvBitsProbs[Index]);
}
}
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 2; j++)
{
for (int k = 0; k < 3; k++)
{
int Index = i * 2 * 3 + j * 3 + k;
WriteMvProbabilityUpdate(Writer, Probs.MvClass0FrProbs[Index], DefaultMvClass0FrProbs[Index]);
}
}
for (int j = 0; j < 3; j++)
{
int Index = i * 3 + j;
WriteMvProbabilityUpdate(Writer, Probs.MvFrProbs[Index], DefaultMvFrProbs[Index]);
}
}
if (Header.AllowHighPrecisionMv)
{
for (int Index = 0; Index < 2; Index++)
{
WriteMvProbabilityUpdate(Writer, Probs.MvClass0HpProbs[Index], DefaultMvClass0HpProbs[Index]);
WriteMvProbabilityUpdate(Writer, Probs.MvHpProbs[Index], DefaultMvHpProbs[Index]);
}
}
}
Writer.End();
CompressedHeaderData = CompressedHeader.ToArray();
}
//Write uncompressed header.
using (MemoryStream EncodedHeader = new MemoryStream())
{
VpxBitStreamWriter Writer = new VpxBitStreamWriter(EncodedHeader);
Writer.WriteU(2, 2); //Frame marker.
Writer.WriteU(0, 2); //Profile.
Writer.WriteBit(false); //Show existing frame.
Writer.WriteBit(!IsKeyFrame);
Writer.WriteBit(ShowFrame);
Writer.WriteBit(ErrorResilientMode);
if (IsKeyFrame)
{
Writer.WriteU(FrameSyncCode, 24);
Writer.WriteU(0, 3); //Color space.
Writer.WriteU(0, 1); //Color range.
Writer.WriteU(Header.CurrentFrame.Width - 1, 16);
Writer.WriteU(Header.CurrentFrame.Height - 1, 16);
Writer.WriteBit(false); //Render and frame size different.
CachedRefFrames.Clear();
//On key frames, all frame slots are set to the current frame,
//so the value of the selected slot doesn't really matter.
GetNewFrameSlot(Keys.CurrKey);
}
else
{
if (!ShowFrame)
{
Writer.WriteBit(IsFrameIntra);
}
if (!ErrorResilientMode)
{
Writer.WriteU(0, 2); //Reset frame context.
}
int RefreshFrameFlags = 1 << GetNewFrameSlot(Keys.CurrKey);
if (IsFrameIntra)
{
Writer.WriteU(FrameSyncCode, 24);
Writer.WriteU(RefreshFrameFlags, 8);
Writer.WriteU(Header.CurrentFrame.Width - 1, 16);
Writer.WriteU(Header.CurrentFrame.Height - 1, 16);
Writer.WriteBit(false); //Render and frame size different.
}
else
{
Writer.WriteU(RefreshFrameFlags, 8);
int[] RefFrameIndex = new int[]
{
GetFrameSlot(Keys.Ref0Key),
GetFrameSlot(Keys.Ref1Key),
GetFrameSlot(Keys.Ref2Key)
};
byte[] RefFrameSignBias = Header.RefFrameSignBias;
for (int Index = 1; Index < 4; Index++)
{
Writer.WriteU(RefFrameIndex[Index - 1], 3);
Writer.WriteU(RefFrameSignBias[Index], 1);
}
Writer.WriteBit(true); //Frame size with refs.
Writer.WriteBit(false); //Render and frame size different.
Writer.WriteBit(Header.AllowHighPrecisionMv);
Writer.WriteBit(Header.RawInterpolationFilter == 4);
if (Header.RawInterpolationFilter != 4)
{
Writer.WriteU(Header.RawInterpolationFilter, 2);
}
}
}
if (!ErrorResilientMode)
{
Writer.WriteBit(false); //Refresh frame context.
Writer.WriteBit(true); //Frame parallel decoding mode.
}
Writer.WriteU(0, 2); //Frame context index.
Writer.WriteU(Header.LoopFilterLevel, 6);
Writer.WriteU(Header.LoopFilterSharpness, 3);
Writer.WriteBit(Header.LoopFilterDeltaEnabled);
if (Header.LoopFilterDeltaEnabled)
{
bool[] UpdateLoopFilterRefDeltas = new bool[4];
bool[] UpdateLoopFilterModeDeltas = new bool[2];
bool LoopFilterDeltaUpdate = false;
for (int Index = 0; Index < Header.LoopFilterRefDeltas.Length; Index++)
{
sbyte Old = LoopFilterRefDeltas[Index];
sbyte New = Header.LoopFilterRefDeltas[Index];
LoopFilterDeltaUpdate |= (UpdateLoopFilterRefDeltas[Index] = Old != New);
}
for (int Index = 0; Index < Header.LoopFilterModeDeltas.Length; Index++)
{
sbyte Old = LoopFilterModeDeltas[Index];
sbyte New = Header.LoopFilterModeDeltas[Index];
LoopFilterDeltaUpdate |= (UpdateLoopFilterModeDeltas[Index] = Old != New);
}
Writer.WriteBit(LoopFilterDeltaUpdate);
if (LoopFilterDeltaUpdate)
{
for (int Index = 0; Index < Header.LoopFilterRefDeltas.Length; Index++)
{
Writer.WriteBit(UpdateLoopFilterRefDeltas[Index]);
if (UpdateLoopFilterRefDeltas[Index])
{
Writer.WriteS(Header.LoopFilterRefDeltas[Index], 6);
}
}
for (int Index = 0; Index < Header.LoopFilterModeDeltas.Length; Index++)
{
Writer.WriteBit(UpdateLoopFilterModeDeltas[Index]);
if (UpdateLoopFilterModeDeltas[Index])
{
Writer.WriteS(Header.LoopFilterModeDeltas[Index], 6);
}
}
}
}
Writer.WriteU(Header.BaseQIndex, 8);
Writer.WriteDeltaQ(Header.DeltaQYDc);
Writer.WriteDeltaQ(Header.DeltaQUvDc);
Writer.WriteDeltaQ(Header.DeltaQUvAc);
Writer.WriteBit(false); //Segmentation enabled (TODO).
int MinTileColsLog2 = CalcMinLog2TileCols(Header.CurrentFrame.Width);
int MaxTileColsLog2 = CalcMaxLog2TileCols(Header.CurrentFrame.Width);
int TileColsLog2Diff = Header.TileColsLog2 - MinTileColsLog2;
int TileColsLog2IncMask = (1 << TileColsLog2Diff) - 1;
//If it's less than the maximum, we need to add an extra 0 on the bitstream
//to indicate that it should stop reading.
if (Header.TileColsLog2 < MaxTileColsLog2)
{
Writer.WriteU(TileColsLog2IncMask << 1, TileColsLog2Diff + 1);
}
else
{
Writer.WriteU(TileColsLog2IncMask, TileColsLog2Diff);
}
bool TileRowsLog2IsNonZero = Header.TileRowsLog2 != 0;
Writer.WriteBit(TileRowsLog2IsNonZero);
if (TileRowsLog2IsNonZero)
{
Writer.WriteBit(Header.TileRowsLog2 > 1);
}
Writer.WriteU(CompressedHeaderData.Length, 16);
Writer.Flush();
EncodedHeader.Write(CompressedHeaderData, 0, CompressedHeaderData.Length);
if (!FFmpegWrapper.IsInitialized)
{
FFmpegWrapper.Vp9Initialize();
}
FFmpegWrapper.DecodeFrame(DecoderHelper.Combine(EncodedHeader.ToArray(), FrameData));
}
LoopFilterRefDeltas = Header.LoopFilterRefDeltas;
LoopFilterModeDeltas = Header.LoopFilterModeDeltas;
}
private int GetNewFrameSlot(long Key)
{
LinkedListNode<int> Node = FrameSlotByLastUse.Last;
FrameSlotByLastUse.RemoveLast();
FrameSlotByLastUse.AddFirst(Node);
CachedRefFrames[Key] = Node;
return Node.Value;
}
private int GetFrameSlot(long Key)
{
if (CachedRefFrames.TryGetValue(Key, out LinkedListNode<int> Node))
{
FrameSlotByLastUse.Remove(Node);
FrameSlotByLastUse.AddFirst(Node);
return Node.Value;
}
//Reference frame was lost.
//What we should do in this case?
return 0;
}
private void WriteProbabilityUpdate(VpxRangeEncoder Writer, byte[] New, byte[] Old)
{
for (int Offset = 0; Offset < New.Length; Offset++)
{
WriteProbabilityUpdate(Writer, New[Offset], Old[Offset]);
}
}
private void WriteCoefProbabilityUpdate(VpxRangeEncoder Writer, int TxMode, byte[] New, byte[] Old)
{
//Note: There's 1 byte added on each packet for alignment,
//this byte is ignored when doing updates.
const int BlockBytes = 2 * 2 * 6 * 6 * 4;
bool NeedsUpdate(int BaseIndex)
{
int Index = BaseIndex;
for (int i = 0; i < 2; i++)
for (int j = 0; j < 2; j++)
for (int k = 0; k < 6; k++)
for (int l = 0; l < 6; l++)
{
if (New[Index + 0] != Old[Index + 0] ||
New[Index + 1] != Old[Index + 1] ||
New[Index + 2] != Old[Index + 2])
{
return true;
}
Index += 4;
}
return false;
}
for (int BlockIndex = 0; BlockIndex < 4; BlockIndex++)
{
int BaseIndex = BlockIndex * BlockBytes;
bool Update = NeedsUpdate(BaseIndex);
Writer.Write(Update);
if (Update)
{
int Index = BaseIndex;
for (int i = 0; i < 2; i++)
for (int j = 0; j < 2; j++)
for (int k = 0; k < 6; k++)
for (int l = 0; l < 6; l++)
{
if (k != 0 || l < 3)
{
WriteProbabilityUpdate(Writer, New[Index + 0], Old[Index + 0]);
WriteProbabilityUpdate(Writer, New[Index + 1], Old[Index + 1]);
WriteProbabilityUpdate(Writer, New[Index + 2], Old[Index + 2]);
}
Index += 4;
}
}
if (BlockIndex == TxMode)
{
break;
}
}
}
private void WriteProbabilityUpdateAligned4(VpxRangeEncoder Writer, byte[] New, byte[] Old)
{
for (int Offset = 0; Offset < New.Length; Offset += 4)
{
WriteProbabilityUpdate(Writer, New[Offset + 0], Old[Offset + 0]);
WriteProbabilityUpdate(Writer, New[Offset + 1], Old[Offset + 1]);
WriteProbabilityUpdate(Writer, New[Offset + 2], Old[Offset + 2]);
}
}
private void WriteProbabilityUpdate(VpxRangeEncoder Writer, byte New, byte Old)
{
bool Update = New != Old;
Writer.Write(Update, DiffUpdateProbability);
if (Update)
{
WriteProbabilityDelta(Writer, New, Old);
}
}
private void WriteProbabilityDelta(VpxRangeEncoder Writer, int New, int Old)
{
int Delta = RemapProbability(New, Old);
EncodeTermSubExp(Writer, Delta);
}
private int RemapProbability(int New, int Old)
{
New--;
Old--;
int Index;
if (Old * 2 <= 0xff)
{
Index = RecenterNonNeg(New, Old) - 1;
}
else
{
Index = RecenterNonNeg(0xff - 1 - New, 0xff - 1 - Old) - 1;
}
return MapLut[Index];
}
private int RecenterNonNeg(int New, int Old)
{
if (New > Old * 2)
{
return New;
}
else if (New >= Old)
{
return (New - Old) * 2;
}
else /* if (New < Old) */
{
return (Old - New) * 2 - 1;
}
}
private void EncodeTermSubExp(VpxRangeEncoder Writer, int Value)
{
if (WriteLessThan(Writer, Value, 16))
{
Writer.Write(Value, 4);
}
else if (WriteLessThan(Writer, Value, 32))
{
Writer.Write(Value - 16, 4);
}
else if (WriteLessThan(Writer, Value, 64))
{
Writer.Write(Value - 32, 5);
}
else
{
Value -= 64;
const int Size = 8;
int Mask = (1 << Size) - 191;
int Delta = Value - Mask;
if (Delta < 0)
{
Writer.Write(Value, Size - 1);
}
else
{
Writer.Write(Delta / 2 + Mask, Size - 1);
Writer.Write(Delta & 1, 1);
}
}
}
private bool WriteLessThan(VpxRangeEncoder Writer, int Value, int Test)
{
bool IsLessThan = Value < Test;
Writer.Write(!IsLessThan);
return IsLessThan;
}
private void WriteMvProbabilityUpdate(VpxRangeEncoder Writer, byte New, byte Old)
{
bool Update = New != Old;
Writer.Write(Update, DiffUpdateProbability);
if (Update)
{
Writer.Write(New >> 1, 7);
}
}
private static int CalcMinLog2TileCols(int FrameWidth)
{
int Sb64Cols = (FrameWidth + 63) / 64;
int MinLog2 = 0;
while ((64 << MinLog2) < Sb64Cols)
{
MinLog2++;
}
return MinLog2;
}
private static int CalcMaxLog2TileCols(int FrameWidth)
{
int Sb64Cols = (FrameWidth + 63) / 64;
int MaxLog2 = 1;
while ((Sb64Cols >> MaxLog2) >= 4)
{
MaxLog2++;
}
return MaxLog2 - 1;
}
}
}

View file

@ -0,0 +1,79 @@
using System.Runtime.InteropServices;
namespace Ryujinx.Graphics.VDec
{
[StructLayout(LayoutKind.Sequential, Pack = 2)]
struct Vp9FrameDimensions
{
public short Width;
public short Height;
public short SubsamplingX; //?
public short SubsamplingY; //?
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
struct Vp9FrameHeader
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 3)]
public Vp9FrameDimensions[] RefFrames;
public Vp9FrameDimensions CurrentFrame;
public int Flags;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)]
public byte[] RefFrameSignBias;
public byte LoopFilterLevel;
public byte LoopFilterSharpness;
public byte BaseQIndex;
public sbyte DeltaQYDc;
public sbyte DeltaQUvDc;
public sbyte DeltaQUvAc;
[MarshalAs(UnmanagedType.I1)]
public bool Lossless;
public byte TxMode;
[MarshalAs(UnmanagedType.I1)]
public bool AllowHighPrecisionMv;
public byte RawInterpolationFilter;
public byte CompPredMode;
public byte FixCompRef;
public byte VarCompRef0;
public byte VarCompRef1;
public byte TileColsLog2;
public byte TileRowsLog2;
[MarshalAs(UnmanagedType.I1)]
public bool SegmentationEnabled;
[MarshalAs(UnmanagedType.I1)]
public bool SegmentationUpdate;
[MarshalAs(UnmanagedType.I1)]
public bool SegmentationTemporalUpdate;
[MarshalAs(UnmanagedType.I1)]
public bool SegmentationAbsOrDeltaUpdate;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 8 * 4, ArraySubType = UnmanagedType.I1)]
public bool[] FeatureEnabled;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 8 * 4)]
public short[] FeatureData;
[MarshalAs(UnmanagedType.I1)]
public bool LoopFilterDeltaEnabled;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)]
public sbyte[] LoopFilterRefDeltas;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 2)]
public sbyte[] LoopFilterModeDeltas;
}
}

View file

@ -0,0 +1,10 @@
namespace Ryujinx.Graphics.VDec
{
struct Vp9FrameKeys
{
public long CurrKey;
public long Ref0Key;
public long Ref1Key;
public long Ref2Key;
}
}

View file

@ -0,0 +1,31 @@
namespace Ryujinx.Graphics.VDec
{
struct Vp9ProbabilityTables
{
public byte[] SegmentationTreeProbs;
public byte[] SegmentationPredProbs;
public byte[] Tx8x8Probs;
public byte[] Tx16x16Probs;
public byte[] Tx32x32Probs;
public byte[] CoefProbs;
public byte[] SkipProbs;
public byte[] InterModeProbs;
public byte[] InterpFilterProbs;
public byte[] IsInterProbs;
public byte[] CompModeProbs;
public byte[] SingleRefProbs;
public byte[] CompRefProbs;
public byte[] YModeProbs0;
public byte[] YModeProbs1;
public byte[] PartitionProbs;
public byte[] MvJointProbs;
public byte[] MvSignProbs;
public byte[] MvClassProbs;
public byte[] MvClass0BitProbs;
public byte[] MvBitsProbs;
public byte[] MvClass0FrProbs;
public byte[] MvFrProbs;
public byte[] MvClass0HpProbs;
public byte[] MvHpProbs;
}
}

View file

@ -0,0 +1,38 @@
using System.IO;
namespace Ryujinx.Graphics.VDec
{
class VpxBitStreamWriter : BitStreamWriter
{
public VpxBitStreamWriter(Stream BaseStream) : base(BaseStream) { }
public void WriteU(int Value, int ValueSize)
{
WriteBits(Value, ValueSize);
}
public void WriteS(int Value, int ValueSize)
{
bool Sign = Value < 0;
if (Sign)
{
Value = -Value;
}
WriteBits((Value << 1) | (Sign ? 1 : 0), ValueSize + 1);
}
public void WriteDeltaQ(int Value)
{
bool DeltaCoded = Value != 0;
WriteBit(DeltaCoded);
if (DeltaCoded)
{
WriteBits(Value, 4);
}
}
}
}

View file

@ -0,0 +1,134 @@
using System.IO;
namespace Ryujinx.Graphics.VDec
{
class VpxRangeEncoder
{
private const int HalfProbability = 128;
private static readonly int[] NormLut = new int[]
{
0, 7, 6, 6, 5, 5, 5, 5, 4, 4, 4, 4, 4, 4, 4, 4,
3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
};
private Stream BaseStream;
private uint LowValue;
private uint Range;
private int Count;
public VpxRangeEncoder(Stream BaseStream)
{
this.BaseStream = BaseStream;
Range = 0xff;
Count = -24;
Write(false);
}
public void WriteByte(byte Value)
{
Write(Value, 8);
}
public void Write(int Value, int ValueSize)
{
for (int Bit = ValueSize - 1; Bit >= 0; Bit--)
{
Write(((Value >> Bit) & 1) != 0);
}
}
public void Write(bool Bit)
{
Write(Bit, HalfProbability);
}
public void Write(bool Bit, int Probability)
{
uint Range = this.Range;
uint Split = 1 + (((Range - 1) * (uint)Probability) >> 8);
Range = Split;
if (Bit)
{
LowValue += Split;
Range = this.Range - Split;
}
int Shift = NormLut[Range];
Range <<= Shift;
Count += Shift;
if (Count >= 0)
{
int Offset = Shift - Count;
if (((LowValue << (Offset - 1)) >> 31) != 0)
{
long CurrentPos = BaseStream.Position;
BaseStream.Seek(-1, SeekOrigin.Current);
while (BaseStream.Position >= 0 && PeekByte() == 0xff)
{
BaseStream.WriteByte(0);
BaseStream.Seek(-2, SeekOrigin.Current);
}
BaseStream.WriteByte((byte)(PeekByte() + 1));
BaseStream.Seek(CurrentPos, SeekOrigin.Begin);
}
BaseStream.WriteByte((byte)(LowValue >> (24 - Offset)));
LowValue <<= Offset;
Shift = Count;
LowValue &= 0xffffff;
Count -= 8;
}
LowValue <<= Shift;
this.Range = Range;
}
private byte PeekByte()
{
byte Value = (byte)BaseStream.ReadByte();
BaseStream.Seek(-1, SeekOrigin.Current);
return Value;
}
public void End()
{
for (int Index = 0; Index < 32; Index++)
{
Write(false);
}
}
}
}

View file

@ -0,0 +1,69 @@
using Ryujinx.Graphics.Memory;
using System;
namespace Ryujinx.Graphics.Vic
{
class StructUnpacker
{
private NvGpuVmm Vmm;
private long Position;
private ulong Buffer;
private int BuffPos;
public StructUnpacker(NvGpuVmm Vmm, long Position)
{
this.Vmm = Vmm;
this.Position = Position;
BuffPos = 64;
}
public int Read(int Bits)
{
if ((uint)Bits > 32)
{
throw new ArgumentOutOfRangeException(nameof(Bits));
}
int Value = 0;
while (Bits > 0)
{
RefillBufferIfNeeded();
int ReadBits = Bits;
int MaxReadBits = 64 - BuffPos;
if (ReadBits > MaxReadBits)
{
ReadBits = MaxReadBits;
}
Value <<= ReadBits;
Value |= (int)(Buffer >> BuffPos) & (int)(0xffffffff >> (32 - ReadBits));
BuffPos += ReadBits;
Bits -= ReadBits;
}
return Value;
}
private void RefillBufferIfNeeded()
{
if (BuffPos >= 64)
{
Buffer = Vmm.ReadUInt64(Position);
Position += 8;
BuffPos = 0;
}
}
}
}

View file

@ -0,0 +1,33 @@
namespace Ryujinx.Graphics.Vic
{
struct SurfaceOutputConfig
{
public SurfacePixelFormat PixelFormat;
public int SurfaceWidth;
public int SurfaceHeight;
public int GobBlockHeight;
public long SurfaceLumaAddress;
public long SurfaceChromaUAddress;
public long SurfaceChromaVAddress;
public SurfaceOutputConfig(
SurfacePixelFormat PixelFormat,
int SurfaceWidth,
int SurfaceHeight,
int GobBlockHeight,
long OutputSurfaceLumaAddress,
long OutputSurfaceChromaUAddress,
long OutputSurfaceChromaVAddress)
{
this.PixelFormat = PixelFormat;
this.SurfaceWidth = SurfaceWidth;
this.SurfaceHeight = SurfaceHeight;
this.GobBlockHeight = GobBlockHeight;
this.SurfaceLumaAddress = OutputSurfaceLumaAddress;
this.SurfaceChromaUAddress = OutputSurfaceChromaUAddress;
this.SurfaceChromaVAddress = OutputSurfaceChromaVAddress;
}
}
}

View file

@ -0,0 +1,8 @@
namespace Ryujinx.Graphics.Vic
{
enum SurfacePixelFormat
{
RGBA8 = 0x1f,
YUV420P = 0x44
}
}

View file

@ -0,0 +1,107 @@
using Ryujinx.Graphics.Memory;
namespace Ryujinx.Graphics.Vic
{
class VideoImageComposer
{
private NvGpu Gpu;
private long ConfigStructAddress;
private long OutputSurfaceLumaAddress;
private long OutputSurfaceChromaUAddress;
private long OutputSurfaceChromaVAddress;
public VideoImageComposer(NvGpu Gpu)
{
this.Gpu = Gpu;
}
public void Process(NvGpuVmm Vmm, int MethodOffset, int[] Arguments)
{
VideoImageComposerMeth Method = (VideoImageComposerMeth)MethodOffset;
switch (Method)
{
case VideoImageComposerMeth.Execute:
Execute(Vmm, Arguments);
break;
case VideoImageComposerMeth.SetConfigStructOffset:
SetConfigStructOffset(Vmm, Arguments);
break;
case VideoImageComposerMeth.SetOutputSurfaceLumaOffset:
SetOutputSurfaceLumaOffset(Vmm, Arguments);
break;
case VideoImageComposerMeth.SetOutputSurfaceChromaUOffset:
SetOutputSurfaceChromaUOffset(Vmm, Arguments);
break;
case VideoImageComposerMeth.SetOutputSurfaceChromaVOffset:
SetOutputSurfaceChromaVOffset(Vmm, Arguments);
break;
}
}
private void Execute(NvGpuVmm Vmm, int[] Arguments)
{
StructUnpacker Unpacker = new StructUnpacker(Vmm, ConfigStructAddress + 0x20);
SurfacePixelFormat PixelFormat = (SurfacePixelFormat)Unpacker.Read(7);
int ChromaLocHoriz = Unpacker.Read(2);
int ChromaLocVert = Unpacker.Read(2);
int BlockLinearKind = Unpacker.Read(4);
int BlockLinearHeightLog2 = Unpacker.Read(4);
int Reserved0 = Unpacker.Read(3);
int Reserved1 = Unpacker.Read(10);
int SurfaceWidthMinus1 = Unpacker.Read(14);
int SurfaceHeightMinus1 = Unpacker.Read(14);
int GobBlockHeight = 1 << BlockLinearHeightLog2;
int SurfaceWidth = SurfaceWidthMinus1 + 1;
int SurfaceHeight = SurfaceHeightMinus1 + 1;
SurfaceOutputConfig OutputConfig = new SurfaceOutputConfig(
PixelFormat,
SurfaceWidth,
SurfaceHeight,
GobBlockHeight,
OutputSurfaceLumaAddress,
OutputSurfaceChromaUAddress,
OutputSurfaceChromaVAddress);
Gpu.VideoDecoder.CopyPlanes(Vmm, OutputConfig);
}
private void SetConfigStructOffset(NvGpuVmm Vmm, int[] Arguments)
{
ConfigStructAddress = GetAddress(Arguments);
}
private void SetOutputSurfaceLumaOffset(NvGpuVmm Vmm, int[] Arguments)
{
OutputSurfaceLumaAddress = GetAddress(Arguments);
}
private void SetOutputSurfaceChromaUOffset(NvGpuVmm Vmm, int[] Arguments)
{
OutputSurfaceChromaUAddress = GetAddress(Arguments);
}
private void SetOutputSurfaceChromaVOffset(NvGpuVmm Vmm, int[] Arguments)
{
OutputSurfaceChromaVAddress = GetAddress(Arguments);
}
private static long GetAddress(int[] Arguments)
{
return (long)(uint)Arguments[0] << 8;
}
}
}

View file

@ -0,0 +1,12 @@
namespace Ryujinx.Graphics.Vic
{
enum VideoImageComposerMeth
{
Execute = 0xc0,
SetControlParams = 0x1c1,
SetConfigStructOffset = 0x1c2,
SetOutputSurfaceLumaOffset = 0x1c8,
SetOutputSurfaceChromaUOffset = 0x1c9,
SetOutputSurfaceChromaVOffset = 0x1ca
}
}

126
Ryujinx.HLE/DeviceMemory.cs Normal file
View file

@ -0,0 +1,126 @@
using System;
using System.Runtime.InteropServices;
namespace Ryujinx.HLE
{
class DeviceMemory : IDisposable
{
public const long RamSize = 4L * 1024 * 1024 * 1024;
public IntPtr RamPointer { get; private set; }
private unsafe byte* _ramPtr;
public unsafe DeviceMemory()
{
RamPointer = Marshal.AllocHGlobal(new IntPtr(RamSize));
_ramPtr = (byte*)RamPointer;
}
public sbyte ReadSByte(long position)
{
return (sbyte)ReadByte(position);
}
public short ReadInt16(long position)
{
return (short)ReadUInt16(position);
}
public int ReadInt32(long position)
{
return (int)ReadUInt32(position);
}
public long ReadInt64(long position)
{
return (long)ReadUInt64(position);
}
public unsafe byte ReadByte(long position)
{
return *(_ramPtr + position);
}
public unsafe ushort ReadUInt16(long position)
{
return *((ushort*)(_ramPtr + position));
}
public unsafe uint ReadUInt32(long position)
{
return *((uint*)(_ramPtr + position));
}
public unsafe ulong ReadUInt64(long position)
{
return *((ulong*)(_ramPtr + position));
}
public void WriteSByte(long position, sbyte value)
{
WriteByte(position, (byte)value);
}
public void WriteInt16(long position, short value)
{
WriteUInt16(position, (ushort)value);
}
public void WriteInt32(long position, int value)
{
WriteUInt32(position, (uint)value);
}
public void WriteInt64(long position, long value)
{
WriteUInt64(position, (ulong)value);
}
public unsafe void WriteByte(long position, byte value)
{
*(_ramPtr + position) = value;
}
public unsafe void WriteUInt16(long position, ushort value)
{
*((ushort*)(_ramPtr + position)) = value;
}
public unsafe void WriteUInt32(long position, uint value)
{
*((uint*)(_ramPtr + position)) = value;
}
public unsafe void WriteUInt64(long position, ulong value)
{
*((ulong*)(_ramPtr + position)) = value;
}
public void FillWithZeros(long position, int size)
{
int size8 = size & ~(8 - 1);
for (int offs = 0; offs < size8; offs += 8)
{
WriteInt64(position + offs, 0);
}
for (int offs = size8; offs < (size - size8); offs++)
{
WriteByte(position + offs, 0);
}
}
public void Dispose()
{
Dispose(true);
}
protected virtual void Dispose(bool disposing)
{
Marshal.FreeHGlobal(RamPointer);
}
}
}

View file

@ -4,6 +4,6 @@ namespace Ryujinx.HLE.Exceptions
{ {
public class InvalidNpdmException : Exception public class InvalidNpdmException : Exception
{ {
public InvalidNpdmException(string ExMsg) : base(ExMsg) { } public InvalidNpdmException(string message) : base(message) { }
} }
} }

View file

@ -8,6 +8,6 @@ namespace Ryujinx.HLE.Exceptions
public UndefinedInstructionException() : base() { } public UndefinedInstructionException() : base() { }
public UndefinedInstructionException(long Position, int OpCode) : base(string.Format(ExMsg, Position, OpCode)) { } public UndefinedInstructionException(long position, int opCode) : base(string.Format(ExMsg, position, opCode)) { }
} }
} }

View file

@ -9,297 +9,297 @@ namespace Ryujinx.HLE.FileSystem.Content
{ {
internal class ContentManager internal class ContentManager
{ {
private Dictionary<StorageId, LinkedList<LocationEntry>> LocationEntries; private Dictionary<StorageId, LinkedList<LocationEntry>> _locationEntries;
private Dictionary<string, long> SharedFontTitleDictionary; private Dictionary<string, long> _sharedFontTitleDictionary;
private SortedDictionary<(ulong, ContentType), string> ContentDictionary; private SortedDictionary<(ulong, ContentType), string> _contentDictionary;
private Switch Device; private Switch _device;
public ContentManager(Switch Device) public ContentManager(Switch device)
{ {
ContentDictionary = new SortedDictionary<(ulong, ContentType), string>(); _contentDictionary = new SortedDictionary<(ulong, ContentType), string>();
LocationEntries = new Dictionary<StorageId, LinkedList<LocationEntry>>(); _locationEntries = new Dictionary<StorageId, LinkedList<LocationEntry>>();
SharedFontTitleDictionary = new Dictionary<string, long>() _sharedFontTitleDictionary = new Dictionary<string, long>
{ {
{ "FontStandard", 0x0100000000000811 }, { "FontStandard", 0x0100000000000811 },
{ "FontChineseSimplified", 0x0100000000000814 }, { "FontChineseSimplified", 0x0100000000000814 },
{ "FontExtendedChineseSimplified", 0x0100000000000814 }, { "FontExtendedChineseSimplified", 0x0100000000000814 },
{ "FontKorean", 0x0100000000000812 }, { "FontKorean", 0x0100000000000812 },
{ "FontChineseTraditional", 0x0100000000000813 }, { "FontChineseTraditional", 0x0100000000000813 },
{ "FontNintendoExtended" , 0x0100000000000810 }, { "FontNintendoExtended", 0x0100000000000810 }
}; };
this.Device = Device; _device = device;
} }
public void LoadEntries() public void LoadEntries()
{ {
ContentDictionary = new SortedDictionary<(ulong, ContentType), string>(); _contentDictionary = new SortedDictionary<(ulong, ContentType), string>();
foreach (StorageId StorageId in Enum.GetValues(typeof(StorageId))) foreach (StorageId storageId in Enum.GetValues(typeof(StorageId)))
{ {
string ContentDirectory = null; string contentDirectory = null;
string ContentPathString = null; string contentPathString = null;
string RegisteredDirectory = null; string registeredDirectory = null;
try try
{ {
ContentPathString = LocationHelper.GetContentRoot(StorageId); contentPathString = LocationHelper.GetContentRoot(storageId);
ContentDirectory = LocationHelper.GetRealPath(Device.FileSystem, ContentPathString); contentDirectory = LocationHelper.GetRealPath(_device.FileSystem, contentPathString);
RegisteredDirectory = Path.Combine(ContentDirectory, "registered"); registeredDirectory = Path.Combine(contentDirectory, "registered");
} }
catch (NotSupportedException NEx) catch (NotSupportedException)
{ {
continue; continue;
} }
Directory.CreateDirectory(RegisteredDirectory); Directory.CreateDirectory(registeredDirectory);
LinkedList<LocationEntry> LocationList = new LinkedList<LocationEntry>(); LinkedList<LocationEntry> locationList = new LinkedList<LocationEntry>();
void AddEntry(LocationEntry Entry) void AddEntry(LocationEntry entry)
{ {
LocationList.AddLast(Entry); locationList.AddLast(entry);
} }
foreach (string DirectoryPath in Directory.EnumerateDirectories(RegisteredDirectory)) foreach (string directoryPath in Directory.EnumerateDirectories(registeredDirectory))
{ {
if (Directory.GetFiles(DirectoryPath).Length > 0) if (Directory.GetFiles(directoryPath).Length > 0)
{ {
string NcaName = new DirectoryInfo(DirectoryPath).Name.Replace(".nca", string.Empty); string ncaName = new DirectoryInfo(directoryPath).Name.Replace(".nca", string.Empty);
using (FileStream NcaFile = new FileStream(Directory.GetFiles(DirectoryPath)[0], FileMode.Open, FileAccess.Read)) using (FileStream ncaFile = new FileStream(Directory.GetFiles(directoryPath)[0], FileMode.Open, FileAccess.Read))
{ {
Nca Nca = new Nca(Device.System.KeySet, NcaFile, false); Nca nca = new Nca(_device.System.KeySet, ncaFile, false);
string SwitchPath = Path.Combine(ContentPathString + ":", string switchPath = Path.Combine(contentPathString + ":",
NcaFile.Name.Replace(ContentDirectory, string.Empty).TrimStart('\\')); ncaFile.Name.Replace(contentDirectory, string.Empty).TrimStart('\\'));
// Change path format to switch's // Change path format to switch's
SwitchPath = SwitchPath.Replace('\\', '/'); switchPath = switchPath.Replace('\\', '/');
LocationEntry Entry = new LocationEntry(SwitchPath, LocationEntry entry = new LocationEntry(switchPath,
0, 0,
(long)Nca.Header.TitleId, (long)nca.Header.TitleId,
Nca.Header.ContentType); nca.Header.ContentType);
AddEntry(Entry); AddEntry(entry);
ContentDictionary.Add((Nca.Header.TitleId, Nca.Header.ContentType), NcaName); _contentDictionary.Add((nca.Header.TitleId, nca.Header.ContentType), ncaName);
NcaFile.Close(); ncaFile.Close();
Nca.Dispose(); nca.Dispose();
NcaFile.Dispose(); ncaFile.Dispose();
} }
} }
} }
foreach (string FilePath in Directory.EnumerateFiles(ContentDirectory)) foreach (string filePath in Directory.EnumerateFiles(contentDirectory))
{ {
if (Path.GetExtension(FilePath) == ".nca") if (Path.GetExtension(filePath) == ".nca")
{ {
string NcaName = Path.GetFileNameWithoutExtension(FilePath); string ncaName = Path.GetFileNameWithoutExtension(filePath);
using (FileStream NcaFile = new FileStream(FilePath, FileMode.Open, FileAccess.Read)) using (FileStream ncaFile = new FileStream(filePath, FileMode.Open, FileAccess.Read))
{ {
Nca Nca = new Nca(Device.System.KeySet, NcaFile, false); Nca nca = new Nca(_device.System.KeySet, ncaFile, false);
string SwitchPath = Path.Combine(ContentPathString + ":", string switchPath = Path.Combine(contentPathString + ":",
FilePath.Replace(ContentDirectory, string.Empty).TrimStart('\\')); filePath.Replace(contentDirectory, string.Empty).TrimStart('\\'));
// Change path format to switch's // Change path format to switch's
SwitchPath = SwitchPath.Replace('\\', '/'); switchPath = switchPath.Replace('\\', '/');
LocationEntry Entry = new LocationEntry(SwitchPath, LocationEntry entry = new LocationEntry(switchPath,
0, 0,
(long)Nca.Header.TitleId, (long)nca.Header.TitleId,
Nca.Header.ContentType); nca.Header.ContentType);
AddEntry(Entry); AddEntry(entry);
ContentDictionary.Add((Nca.Header.TitleId, Nca.Header.ContentType), NcaName); _contentDictionary.Add((nca.Header.TitleId, nca.Header.ContentType), ncaName);
NcaFile.Close(); ncaFile.Close();
Nca.Dispose(); nca.Dispose();
NcaFile.Dispose(); ncaFile.Dispose();
} }
} }
} }
if(LocationEntries.ContainsKey(StorageId) && LocationEntries[StorageId]?.Count == 0) if(_locationEntries.ContainsKey(storageId) && _locationEntries[storageId]?.Count == 0)
{ {
LocationEntries.Remove(StorageId); _locationEntries.Remove(storageId);
} }
if (!LocationEntries.ContainsKey(StorageId)) if (!_locationEntries.ContainsKey(storageId))
{ {
LocationEntries.Add(StorageId, LocationList); _locationEntries.Add(storageId, locationList);
} }
} }
} }
public void ClearEntry(long TitleId, ContentType ContentType,StorageId StorageId) public void ClearEntry(long titleId, ContentType contentType,StorageId storageId)
{ {
RemoveLocationEntry(TitleId, ContentType, StorageId); RemoveLocationEntry(titleId, contentType, storageId);
} }
public void RefreshEntries(StorageId StorageId, int Flag) public void RefreshEntries(StorageId storageId, int flag)
{ {
LinkedList<LocationEntry> LocationList = LocationEntries[StorageId]; LinkedList<LocationEntry> locationList = _locationEntries[storageId];
LinkedListNode<LocationEntry> LocationEntry = LocationList.First; LinkedListNode<LocationEntry> locationEntry = locationList.First;
while (LocationEntry != null) while (locationEntry != null)
{ {
LinkedListNode<LocationEntry> NextLocationEntry = LocationEntry.Next; LinkedListNode<LocationEntry> nextLocationEntry = locationEntry.Next;
if (LocationEntry.Value.Flag == Flag) if (locationEntry.Value.Flag == flag)
{ {
LocationList.Remove(LocationEntry.Value); locationList.Remove(locationEntry.Value);
} }
LocationEntry = NextLocationEntry; locationEntry = nextLocationEntry;
} }
} }
public bool HasNca(string NcaId, StorageId StorageId) public bool HasNca(string ncaId, StorageId storageId)
{ {
if (ContentDictionary.ContainsValue(NcaId)) if (_contentDictionary.ContainsValue(ncaId))
{ {
var Content = ContentDictionary.FirstOrDefault(x => x.Value == NcaId); var content = _contentDictionary.FirstOrDefault(x => x.Value == ncaId);
long TitleId = (long)Content.Key.Item1; long titleId = (long)content.Key.Item1;
ContentType ContentType = Content.Key.Item2; ContentType contentType = content.Key.Item2;
StorageId Storage = GetInstalledStorage(TitleId, ContentType, StorageId); StorageId storage = GetInstalledStorage(titleId, contentType, storageId);
return Storage == StorageId; return storage == storageId;
} }
return false; return false;
} }
public UInt128 GetInstalledNcaId(long TitleId, ContentType ContentType) public UInt128 GetInstalledNcaId(long titleId, ContentType contentType)
{ {
if (ContentDictionary.ContainsKey(((ulong)TitleId,ContentType))) if (_contentDictionary.ContainsKey(((ulong)titleId,contentType)))
{ {
return new UInt128(ContentDictionary[((ulong)TitleId,ContentType)]); return new UInt128(_contentDictionary[((ulong)titleId,contentType)]);
} }
return new UInt128(); return new UInt128();
} }
public StorageId GetInstalledStorage(long TitleId, ContentType ContentType, StorageId StorageId) public StorageId GetInstalledStorage(long titleId, ContentType contentType, StorageId storageId)
{ {
LocationEntry LocationEntry = GetLocation(TitleId, ContentType, StorageId); LocationEntry locationEntry = GetLocation(titleId, contentType, storageId);
return LocationEntry.ContentPath != null ? return locationEntry.ContentPath != null ?
LocationHelper.GetStorageId(LocationEntry.ContentPath) : StorageId.None; LocationHelper.GetStorageId(locationEntry.ContentPath) : StorageId.None;
} }
public string GetInstalledContentPath(long TitleId, StorageId StorageId, ContentType ContentType) public string GetInstalledContentPath(long titleId, StorageId storageId, ContentType contentType)
{ {
LocationEntry LocationEntry = GetLocation(TitleId, ContentType, StorageId); LocationEntry locationEntry = GetLocation(titleId, contentType, storageId);
if (VerifyContentType(LocationEntry, ContentType)) if (VerifyContentType(locationEntry, contentType))
{ {
return LocationEntry.ContentPath; return locationEntry.ContentPath;
} }
return string.Empty; return string.Empty;
} }
public void RedirectLocation(LocationEntry NewEntry, StorageId StorageId) public void RedirectLocation(LocationEntry newEntry, StorageId storageId)
{ {
LocationEntry LocationEntry = GetLocation(NewEntry.TitleId, NewEntry.ContentType, StorageId); LocationEntry locationEntry = GetLocation(newEntry.TitleId, newEntry.ContentType, storageId);
if (LocationEntry.ContentPath != null) if (locationEntry.ContentPath != null)
{ {
RemoveLocationEntry(NewEntry.TitleId, NewEntry.ContentType, StorageId); RemoveLocationEntry(newEntry.TitleId, newEntry.ContentType, storageId);
} }
AddLocationEntry(NewEntry, StorageId); AddLocationEntry(newEntry, storageId);
} }
private bool VerifyContentType(LocationEntry LocationEntry, ContentType ContentType) private bool VerifyContentType(LocationEntry locationEntry, ContentType contentType)
{ {
if (LocationEntry.ContentPath == null) if (locationEntry.ContentPath == null)
{ {
return false; return false;
} }
StorageId StorageId = LocationHelper.GetStorageId(LocationEntry.ContentPath); StorageId storageId = LocationHelper.GetStorageId(locationEntry.ContentPath);
string InstalledPath = Device.FileSystem.SwitchPathToSystemPath(LocationEntry.ContentPath); string installedPath = _device.FileSystem.SwitchPathToSystemPath(locationEntry.ContentPath);
if (!string.IsNullOrWhiteSpace(InstalledPath)) if (!string.IsNullOrWhiteSpace(installedPath))
{ {
if (File.Exists(InstalledPath)) if (File.Exists(installedPath))
{ {
FileStream File = new FileStream(InstalledPath, FileMode.Open, FileAccess.Read); FileStream file = new FileStream(installedPath, FileMode.Open, FileAccess.Read);
Nca Nca = new Nca(Device.System.KeySet, File, false); Nca nca = new Nca(_device.System.KeySet, file, false);
bool ContentCheck = Nca.Header.ContentType == ContentType; bool contentCheck = nca.Header.ContentType == contentType;
Nca.Dispose(); nca.Dispose();
File.Dispose(); file.Dispose();
return ContentCheck; return contentCheck;
} }
} }
return false; return false;
} }
private void AddLocationEntry(LocationEntry Entry, StorageId StorageId) private void AddLocationEntry(LocationEntry entry, StorageId storageId)
{ {
LinkedList<LocationEntry> LocationList = null; LinkedList<LocationEntry> locationList = null;
if (LocationEntries.ContainsKey(StorageId)) if (_locationEntries.ContainsKey(storageId))
{ {
LocationList = LocationEntries[StorageId]; locationList = _locationEntries[storageId];
} }
if (LocationList != null) if (locationList != null)
{ {
if (LocationList.Contains(Entry)) if (locationList.Contains(entry))
{ {
LocationList.Remove(Entry); locationList.Remove(entry);
} }
LocationList.AddLast(Entry); locationList.AddLast(entry);
} }
} }
private void RemoveLocationEntry(long TitleId, ContentType ContentType, StorageId StorageId) private void RemoveLocationEntry(long titleId, ContentType contentType, StorageId storageId)
{ {
LinkedList<LocationEntry> LocationList = null; LinkedList<LocationEntry> locationList = null;
if (LocationEntries.ContainsKey(StorageId)) if (_locationEntries.ContainsKey(storageId))
{ {
LocationList = LocationEntries[StorageId]; locationList = _locationEntries[storageId];
} }
if (LocationList != null) if (locationList != null)
{ {
LocationEntry Entry = LocationEntry entry =
LocationList.ToList().Find(x => x.TitleId == TitleId && x.ContentType == ContentType); locationList.ToList().Find(x => x.TitleId == titleId && x.ContentType == contentType);
if (Entry.ContentPath != null) if (entry.ContentPath != null)
{ {
LocationList.Remove(Entry); locationList.Remove(entry);
} }
} }
} }
public bool TryGetFontTitle(string FontName, out long TitleId) public bool TryGetFontTitle(string fontName, out long titleId)
{ {
return SharedFontTitleDictionary.TryGetValue(FontName, out TitleId); return _sharedFontTitleDictionary.TryGetValue(fontName, out titleId);
} }
private LocationEntry GetLocation(long TitleId, ContentType ContentType,StorageId StorageId) private LocationEntry GetLocation(long titleId, ContentType contentType,StorageId storageId)
{ {
LinkedList<LocationEntry> LocationList = LocationEntries[StorageId]; LinkedList<LocationEntry> locationList = _locationEntries[storageId];
return LocationList.ToList().Find(x => x.TitleId == TitleId && x.ContentType == ContentType); return locationList.ToList().Find(x => x.TitleId == titleId && x.ContentType == contentType);
} }
} }
} }

View file

@ -1,7 +1,4 @@
using System; using LibHac;
using System.Collections.Generic;
using System.Text;
using LibHac;
namespace Ryujinx.HLE.FileSystem.Content namespace Ryujinx.HLE.FileSystem.Content
{ {
@ -12,17 +9,17 @@ namespace Ryujinx.HLE.FileSystem.Content
public long TitleId { get; private set; } public long TitleId { get; private set; }
public ContentType ContentType { get; private set; } public ContentType ContentType { get; private set; }
public LocationEntry(string ContentPath, int Flag, long TitleId, ContentType ContentType) public LocationEntry(string contentPath, int flag, long titleId, ContentType contentType)
{ {
this.ContentPath = ContentPath; ContentPath = contentPath;
this.Flag = Flag; Flag = flag;
this.TitleId = TitleId; TitleId = titleId;
this.ContentType = ContentType; ContentType = contentType;
} }
public void SetFlag(int Flag) public void SetFlag(int flag)
{ {
this.Flag = Flag; Flag = flag;
} }
} }
} }

View file

@ -7,30 +7,30 @@ namespace Ryujinx.HLE.FileSystem.Content
{ {
internal static class LocationHelper internal static class LocationHelper
{ {
public static string GetRealPath(VirtualFileSystem FileSystem, string SwitchContentPath) public static string GetRealPath(VirtualFileSystem fileSystem, string switchContentPath)
{ {
string BasePath = FileSystem.GetBasePath(); string basePath = fileSystem.GetBasePath();
switch (SwitchContentPath) switch (switchContentPath)
{ {
case ContentPath.SystemContent: case ContentPath.SystemContent:
return Path.Combine(FileSystem.GetBasePath(), SystemNandPath, "Contents"); return Path.Combine(fileSystem.GetBasePath(), SystemNandPath, "Contents");
case ContentPath.UserContent: case ContentPath.UserContent:
return Path.Combine(FileSystem.GetBasePath(), UserNandPath, "Contents"); return Path.Combine(fileSystem.GetBasePath(), UserNandPath, "Contents");
case ContentPath.SdCardContent: case ContentPath.SdCardContent:
return Path.Combine(FileSystem.GetSdCardPath(), "Nintendo", "Contents"); return Path.Combine(fileSystem.GetSdCardPath(), "Nintendo", "Contents");
case ContentPath.System: case ContentPath.System:
return Path.Combine(BasePath, SystemNandPath); return Path.Combine(basePath, SystemNandPath);
case ContentPath.User: case ContentPath.User:
return Path.Combine(BasePath, UserNandPath); return Path.Combine(basePath, UserNandPath);
default: default:
throw new NotSupportedException($"Content Path `{SwitchContentPath}` is not supported."); throw new NotSupportedException($"Content Path `{switchContentPath}` is not supported.");
} }
} }
public static string GetContentPath(ContentStorageId ContentStorageId) public static string GetContentPath(ContentStorageId contentStorageId)
{ {
switch (ContentStorageId) switch (contentStorageId)
{ {
case ContentStorageId.NandSystem: case ContentStorageId.NandSystem:
return ContentPath.SystemContent; return ContentPath.SystemContent;
@ -39,13 +39,13 @@ namespace Ryujinx.HLE.FileSystem.Content
case ContentStorageId.SdCard: case ContentStorageId.SdCard:
return ContentPath.SdCardContent; return ContentPath.SdCardContent;
default: default:
throw new NotSupportedException($"Content Storage `{ContentStorageId}` is not supported."); throw new NotSupportedException($"Content Storage `{contentStorageId}` is not supported.");
} }
} }
public static string GetContentRoot(StorageId StorageId) public static string GetContentRoot(StorageId storageId)
{ {
switch (StorageId) switch (storageId)
{ {
case StorageId.NandSystem: case StorageId.NandSystem:
return ContentPath.SystemContent; return ContentPath.SystemContent;
@ -54,15 +54,15 @@ namespace Ryujinx.HLE.FileSystem.Content
case StorageId.SdCard: case StorageId.SdCard:
return ContentPath.SdCardContent; return ContentPath.SdCardContent;
default: default:
throw new NotSupportedException($"Storage Id `{StorageId}` is not supported."); throw new NotSupportedException($"Storage Id `{storageId}` is not supported.");
} }
} }
public static StorageId GetStorageId(string ContentPathString) public static StorageId GetStorageId(string contentPathString)
{ {
string CleanedPath = ContentPathString.Split(':')[0]; string cleanedPath = contentPathString.Split(':')[0];
switch (CleanedPath) switch (cleanedPath)
{ {
case ContentPath.SystemContent: case ContentPath.SystemContent:
case ContentPath.System: case ContentPath.System:

View file

@ -10,228 +10,228 @@ namespace Ryujinx.HLE.FileSystem
{ {
class FileSystemProvider : IFileSystemProvider class FileSystemProvider : IFileSystemProvider
{ {
private readonly string BasePath; private readonly string _basePath;
private readonly string RootPath; private readonly string _rootPath;
public FileSystemProvider(string BasePath, string RootPath) public FileSystemProvider(string basePath, string rootPath)
{ {
this.BasePath = BasePath; _basePath = basePath;
this.RootPath = RootPath; _rootPath = rootPath;
CheckIfDescendentOfRootPath(BasePath); CheckIfDescendentOfRootPath(basePath);
} }
public long CreateDirectory(string Name) public long CreateDirectory(string name)
{ {
CheckIfDescendentOfRootPath(Name); CheckIfDescendentOfRootPath(name);
if (Directory.Exists(Name)) if (Directory.Exists(name))
{ {
return MakeError(ErrorModule.Fs, FsErr.PathAlreadyExists); return MakeError(ErrorModule.Fs, FsErr.PathAlreadyExists);
} }
Directory.CreateDirectory(Name); Directory.CreateDirectory(name);
return 0; return 0;
} }
public long CreateFile(string Name, long Size) public long CreateFile(string name, long size)
{ {
CheckIfDescendentOfRootPath(Name); CheckIfDescendentOfRootPath(name);
if (File.Exists(Name)) if (File.Exists(name))
{ {
return MakeError(ErrorModule.Fs, FsErr.PathAlreadyExists); return MakeError(ErrorModule.Fs, FsErr.PathAlreadyExists);
} }
using (FileStream NewFile = File.Create(Name)) using (FileStream newFile = File.Create(name))
{ {
NewFile.SetLength(Size); newFile.SetLength(size);
} }
return 0; return 0;
} }
public long DeleteDirectory(string Name, bool Recursive) public long DeleteDirectory(string name, bool recursive)
{ {
CheckIfDescendentOfRootPath(Name); CheckIfDescendentOfRootPath(name);
string DirName = Name; string dirName = name;
if (!Directory.Exists(DirName)) if (!Directory.Exists(dirName))
{ {
return MakeError(ErrorModule.Fs, FsErr.PathDoesNotExist); return MakeError(ErrorModule.Fs, FsErr.PathDoesNotExist);
} }
Directory.Delete(DirName, Recursive); Directory.Delete(dirName, recursive);
return 0; return 0;
} }
public long DeleteFile(string Name) public long DeleteFile(string name)
{ {
CheckIfDescendentOfRootPath(Name); CheckIfDescendentOfRootPath(name);
if (!File.Exists(Name)) if (!File.Exists(name))
{ {
return MakeError(ErrorModule.Fs, FsErr.PathDoesNotExist); return MakeError(ErrorModule.Fs, FsErr.PathDoesNotExist);
} }
else else
{ {
File.Delete(Name); File.Delete(name);
} }
return 0; return 0;
} }
public DirectoryEntry[] GetDirectories(string Path) public DirectoryEntry[] GetDirectories(string path)
{ {
CheckIfDescendentOfRootPath(Path); CheckIfDescendentOfRootPath(path);
List<DirectoryEntry> Entries = new List<DirectoryEntry>(); List<DirectoryEntry> entries = new List<DirectoryEntry>();
foreach(string Directory in Directory.EnumerateDirectories(Path)) foreach(string directory in Directory.EnumerateDirectories(path))
{ {
DirectoryEntry DirectoryEntry = new DirectoryEntry(Directory, DirectoryEntryType.Directory); DirectoryEntry directoryEntry = new DirectoryEntry(directory, DirectoryEntryType.Directory);
Entries.Add(DirectoryEntry); entries.Add(directoryEntry);
} }
return Entries.ToArray(); return entries.ToArray();
} }
public DirectoryEntry[] GetEntries(string Path) public DirectoryEntry[] GetEntries(string path)
{ {
CheckIfDescendentOfRootPath(Path); CheckIfDescendentOfRootPath(path);
if (Directory.Exists(Path)) if (Directory.Exists(path))
{ {
List<DirectoryEntry> Entries = new List<DirectoryEntry>(); List<DirectoryEntry> entries = new List<DirectoryEntry>();
foreach (string Directory in Directory.EnumerateDirectories(Path)) foreach (string directory in Directory.EnumerateDirectories(path))
{ {
DirectoryEntry DirectoryEntry = new DirectoryEntry(Directory, DirectoryEntryType.Directory); DirectoryEntry directoryEntry = new DirectoryEntry(directory, DirectoryEntryType.Directory);
Entries.Add(DirectoryEntry); entries.Add(directoryEntry);
} }
foreach (string File in Directory.EnumerateFiles(Path)) foreach (string file in Directory.EnumerateFiles(path))
{ {
FileInfo FileInfo = new FileInfo(File); FileInfo fileInfo = new FileInfo(file);
DirectoryEntry DirectoryEntry = new DirectoryEntry(File, DirectoryEntryType.File, FileInfo.Length); DirectoryEntry directoryEntry = new DirectoryEntry(file, DirectoryEntryType.File, fileInfo.Length);
Entries.Add(DirectoryEntry); entries.Add(directoryEntry);
} }
} }
return null; return null;
} }
public DirectoryEntry[] GetFiles(string Path) public DirectoryEntry[] GetFiles(string path)
{ {
CheckIfDescendentOfRootPath(Path); CheckIfDescendentOfRootPath(path);
List<DirectoryEntry> Entries = new List<DirectoryEntry>(); List<DirectoryEntry> entries = new List<DirectoryEntry>();
foreach (string File in Directory.EnumerateFiles(Path)) foreach (string file in Directory.EnumerateFiles(path))
{ {
FileInfo FileInfo = new FileInfo(File); FileInfo fileInfo = new FileInfo(file);
DirectoryEntry DirectoryEntry = new DirectoryEntry(File, DirectoryEntryType.File, FileInfo.Length); DirectoryEntry directoryEntry = new DirectoryEntry(file, DirectoryEntryType.File, fileInfo.Length);
Entries.Add(DirectoryEntry); entries.Add(directoryEntry);
} }
return Entries.ToArray(); return entries.ToArray();
} }
public long GetFreeSpace(ServiceCtx Context) public long GetFreeSpace(ServiceCtx context)
{ {
return Context.Device.FileSystem.GetDrive().AvailableFreeSpace; return context.Device.FileSystem.GetDrive().AvailableFreeSpace;
} }
public string GetFullPath(string Name) public string GetFullPath(string name)
{ {
if (Name.StartsWith("//")) if (name.StartsWith("//"))
{ {
Name = Name.Substring(2); name = name.Substring(2);
} }
else if (Name.StartsWith('/')) else if (name.StartsWith('/'))
{ {
Name = Name.Substring(1); name = name.Substring(1);
} }
else else
{ {
return null; return null;
} }
string FullPath = Path.Combine(BasePath, Name); string fullPath = Path.Combine(_basePath, name);
CheckIfDescendentOfRootPath(FullPath); CheckIfDescendentOfRootPath(fullPath);
return FullPath; return fullPath;
} }
public long GetTotalSpace(ServiceCtx Context) public long GetTotalSpace(ServiceCtx context)
{ {
return Context.Device.FileSystem.GetDrive().TotalSize; return context.Device.FileSystem.GetDrive().TotalSize;
} }
public bool DirectoryExists(string Name) public bool DirectoryExists(string name)
{ {
CheckIfDescendentOfRootPath(Name); CheckIfDescendentOfRootPath(name);
return Directory.Exists(Name); return Directory.Exists(name);
} }
public bool FileExists(string Name) public bool FileExists(string name)
{ {
CheckIfDescendentOfRootPath(Name); CheckIfDescendentOfRootPath(name);
return File.Exists(Name); return File.Exists(name);
} }
public long OpenDirectory(string Name, int FilterFlags, out IDirectory DirectoryInterface) public long OpenDirectory(string name, int filterFlags, out IDirectory directoryInterface)
{ {
CheckIfDescendentOfRootPath(Name); CheckIfDescendentOfRootPath(name);
if (Directory.Exists(Name)) if (Directory.Exists(name))
{ {
DirectoryInterface = new IDirectory(Name, FilterFlags, this); directoryInterface = new IDirectory(name, filterFlags, this);
return 0; return 0;
} }
DirectoryInterface = null; directoryInterface = null;
return MakeError(ErrorModule.Fs, FsErr.PathDoesNotExist); return MakeError(ErrorModule.Fs, FsErr.PathDoesNotExist);
} }
public long OpenFile(string Name, out IFile FileInterface) public long OpenFile(string name, out IFile fileInterface)
{ {
CheckIfDescendentOfRootPath(Name); CheckIfDescendentOfRootPath(name);
if (File.Exists(Name)) if (File.Exists(name))
{ {
FileStream Stream = new FileStream(Name, FileMode.Open); FileStream stream = new FileStream(name, FileMode.Open);
FileInterface = new IFile(Stream, Name); fileInterface = new IFile(stream, name);
return 0; return 0;
} }
FileInterface = null; fileInterface = null;
return MakeError(ErrorModule.Fs, FsErr.PathDoesNotExist); return MakeError(ErrorModule.Fs, FsErr.PathDoesNotExist);
} }
public long RenameDirectory(string OldName, string NewName) public long RenameDirectory(string oldName, string newName)
{ {
CheckIfDescendentOfRootPath(OldName); CheckIfDescendentOfRootPath(oldName);
CheckIfDescendentOfRootPath(NewName); CheckIfDescendentOfRootPath(newName);
if (Directory.Exists(OldName)) if (Directory.Exists(oldName))
{ {
Directory.Move(OldName, NewName); Directory.Move(oldName, newName);
} }
else else
{ {
@ -241,14 +241,14 @@ namespace Ryujinx.HLE.FileSystem
return 0; return 0;
} }
public long RenameFile(string OldName, string NewName) public long RenameFile(string oldName, string newName)
{ {
CheckIfDescendentOfRootPath(OldName); CheckIfDescendentOfRootPath(oldName);
CheckIfDescendentOfRootPath(NewName); CheckIfDescendentOfRootPath(newName);
if (File.Exists(OldName)) if (File.Exists(oldName))
{ {
File.Move(OldName, NewName); File.Move(oldName, newName);
} }
else else
{ {
@ -258,24 +258,24 @@ namespace Ryujinx.HLE.FileSystem
return 0; return 0;
} }
public void CheckIfDescendentOfRootPath(string Path) public void CheckIfDescendentOfRootPath(string path)
{ {
DirectoryInfo PathInfo = new DirectoryInfo(Path); DirectoryInfo pathInfo = new DirectoryInfo(path);
DirectoryInfo RootInfo = new DirectoryInfo(RootPath); DirectoryInfo rootInfo = new DirectoryInfo(_rootPath);
while (PathInfo.Parent != null) while (pathInfo.Parent != null)
{ {
if (PathInfo.Parent.FullName == RootInfo.FullName) if (pathInfo.Parent.FullName == rootInfo.FullName)
{ {
return; return;
} }
else else
{ {
PathInfo = PathInfo.Parent; pathInfo = pathInfo.Parent;
} }
} }
throw new InvalidOperationException($"Path {Path} is not a child directory of {RootPath}"); throw new InvalidOperationException($"Path {path} is not a child directory of {_rootPath}");
} }
} }
} }

View file

@ -1,41 +1,40 @@
using Ryujinx.HLE.HOS; using Ryujinx.HLE.HOS;
using Ryujinx.HLE.HOS.Services.FspSrv; using Ryujinx.HLE.HOS.Services.FspSrv;
using System;
namespace Ryujinx.HLE.FileSystem namespace Ryujinx.HLE.FileSystem
{ {
interface IFileSystemProvider interface IFileSystemProvider
{ {
long CreateFile(string Name, long Size); long CreateFile(string name, long size);
long CreateDirectory(string Name); long CreateDirectory(string name);
long RenameFile(string OldName, string NewName); long RenameFile(string oldName, string newName);
long RenameDirectory(string OldName, string NewName); long RenameDirectory(string oldName, string newName);
DirectoryEntry[] GetEntries(string Path); DirectoryEntry[] GetEntries(string path);
DirectoryEntry[] GetDirectories(string Path); DirectoryEntry[] GetDirectories(string path);
DirectoryEntry[] GetFiles(string Path); DirectoryEntry[] GetFiles(string path);
long DeleteFile(string Name); long DeleteFile(string name);
long DeleteDirectory(string Name, bool Recursive); long DeleteDirectory(string name, bool recursive);
bool FileExists(string Name); bool FileExists(string name);
bool DirectoryExists(string Name); bool DirectoryExists(string name);
long OpenFile(string Name, out IFile FileInterface); long OpenFile(string name, out IFile fileInterface);
long OpenDirectory(string Name, int FilterFlags, out IDirectory DirectoryInterface); long OpenDirectory(string name, int filterFlags, out IDirectory directoryInterface);
string GetFullPath(string Name); string GetFullPath(string name);
long GetFreeSpace(ServiceCtx Context); long GetFreeSpace(ServiceCtx context);
long GetTotalSpace(ServiceCtx Context); long GetTotalSpace(ServiceCtx context);
} }
} }

View file

@ -12,98 +12,98 @@ namespace Ryujinx.HLE.FileSystem
{ {
class PFsProvider : IFileSystemProvider class PFsProvider : IFileSystemProvider
{ {
private Pfs Pfs; private Pfs _pfs;
public PFsProvider(Pfs Pfs) public PFsProvider(Pfs pfs)
{ {
this.Pfs = Pfs; _pfs = pfs;
} }
public long CreateDirectory(string Name) public long CreateDirectory(string name)
{ {
throw new NotSupportedException(); throw new NotSupportedException();
} }
public long CreateFile(string Name, long Size) public long CreateFile(string name, long size)
{ {
throw new NotSupportedException(); throw new NotSupportedException();
} }
public long DeleteDirectory(string Name, bool Recursive) public long DeleteDirectory(string name, bool recursive)
{ {
throw new NotSupportedException(); throw new NotSupportedException();
} }
public long DeleteFile(string Name) public long DeleteFile(string name)
{ {
throw new NotSupportedException(); throw new NotSupportedException();
} }
public DirectoryEntry[] GetDirectories(string Path) public DirectoryEntry[] GetDirectories(string path)
{ {
return new DirectoryEntry[0]; return new DirectoryEntry[0];
} }
public DirectoryEntry[] GetEntries(string Path) public DirectoryEntry[] GetEntries(string path)
{ {
List<DirectoryEntry> Entries = new List<DirectoryEntry>(); List<DirectoryEntry> entries = new List<DirectoryEntry>();
foreach (PfsFileEntry File in Pfs.Files) foreach (PfsFileEntry file in _pfs.Files)
{ {
DirectoryEntry DirectoryEntry = new DirectoryEntry(File.Name, DirectoryEntryType.File, File.Size); DirectoryEntry directoryEntry = new DirectoryEntry(file.Name, DirectoryEntryType.File, file.Size);
Entries.Add(DirectoryEntry); entries.Add(directoryEntry);
} }
return Entries.ToArray(); return entries.ToArray();
} }
public DirectoryEntry[] GetFiles(string Path) public DirectoryEntry[] GetFiles(string path)
{ {
List<DirectoryEntry> Entries = new List<DirectoryEntry>(); List<DirectoryEntry> entries = new List<DirectoryEntry>();
foreach (PfsFileEntry File in Pfs.Files) foreach (PfsFileEntry file in _pfs.Files)
{ {
DirectoryEntry DirectoryEntry = new DirectoryEntry(File.Name, DirectoryEntryType.File, File.Size); DirectoryEntry directoryEntry = new DirectoryEntry(file.Name, DirectoryEntryType.File, file.Size);
Entries.Add(DirectoryEntry); entries.Add(directoryEntry);
} }
return Entries.ToArray(); return entries.ToArray();
} }
public long GetFreeSpace(ServiceCtx Context) public long GetFreeSpace(ServiceCtx context)
{ {
return 0; return 0;
} }
public string GetFullPath(string Name) public string GetFullPath(string name)
{ {
return Name; return name;
} }
public long GetTotalSpace(ServiceCtx Context) public long GetTotalSpace(ServiceCtx context)
{ {
return Pfs.Files.Sum(x => x.Size); return _pfs.Files.Sum(x => x.Size);
} }
public bool DirectoryExists(string Name) public bool DirectoryExists(string name)
{ {
return Name == "/" ? true : false; return name == "/";
} }
public bool FileExists(string Name) public bool FileExists(string name)
{ {
Name = Name.TrimStart('/'); name = name.TrimStart('/');
return Pfs.FileExists(Name); return _pfs.FileExists(name);
} }
public long OpenDirectory(string Name, int FilterFlags, out IDirectory DirectoryInterface) public long OpenDirectory(string name, int filterFlags, out IDirectory directoryInterface)
{ {
if (Name == "/") if (name == "/")
{ {
DirectoryInterface = new IDirectory(Name, FilterFlags, this); directoryInterface = new IDirectory(name, filterFlags, this);
return 0; return 0;
} }
@ -111,34 +111,34 @@ namespace Ryujinx.HLE.FileSystem
throw new NotSupportedException(); throw new NotSupportedException();
} }
public long OpenFile(string Name, out IFile FileInterface) public long OpenFile(string name, out IFile fileInterface)
{ {
Name = Name.TrimStart('/'); name = name.TrimStart('/');
if (Pfs.FileExists(Name)) if (_pfs.FileExists(name))
{ {
Stream Stream = Pfs.OpenFile(Name); Stream stream = _pfs.OpenFile(name);
FileInterface = new IFile(Stream, Name); fileInterface = new IFile(stream, name);
return 0; return 0;
} }
FileInterface = null; fileInterface = null;
return MakeError(ErrorModule.Fs, FsErr.PathDoesNotExist); return MakeError(ErrorModule.Fs, FsErr.PathDoesNotExist);
} }
public long RenameDirectory(string OldName, string NewName) public long RenameDirectory(string oldName, string newName)
{ {
throw new NotSupportedException(); throw new NotSupportedException();
} }
public long RenameFile(string OldName, string NewName) public long RenameFile(string oldName, string newName)
{ {
throw new NotSupportedException(); throw new NotSupportedException();
} }
public void CheckIfOutsideBasePath(string Path) public void CheckIfOutsideBasePath(string path)
{ {
throw new NotSupportedException(); throw new NotSupportedException();
} }

View file

@ -12,150 +12,150 @@ namespace Ryujinx.HLE.FileSystem
{ {
class RomFsProvider : IFileSystemProvider class RomFsProvider : IFileSystemProvider
{ {
private Romfs RomFs; private Romfs _romFs;
public RomFsProvider(Stream StorageStream) public RomFsProvider(Stream storageStream)
{ {
RomFs = new Romfs(StorageStream); _romFs = new Romfs(storageStream);
} }
public long CreateDirectory(string Name) public long CreateDirectory(string name)
{ {
throw new NotSupportedException(); throw new NotSupportedException();
} }
public long CreateFile(string Name, long Size) public long CreateFile(string name, long size)
{ {
throw new NotSupportedException(); throw new NotSupportedException();
} }
public long DeleteDirectory(string Name, bool Recursive) public long DeleteDirectory(string name, bool recursive)
{ {
throw new NotSupportedException(); throw new NotSupportedException();
} }
public long DeleteFile(string Name) public long DeleteFile(string name)
{ {
throw new NotSupportedException(); throw new NotSupportedException();
} }
public DirectoryEntry[] GetDirectories(string Path) public DirectoryEntry[] GetDirectories(string path)
{ {
List<DirectoryEntry> Directories = new List<DirectoryEntry>(); List<DirectoryEntry> directories = new List<DirectoryEntry>();
foreach(RomfsDir Directory in RomFs.Directories) foreach(RomfsDir directory in _romFs.Directories)
{ {
DirectoryEntry DirectoryEntry = new DirectoryEntry(Directory.Name, DirectoryEntryType.Directory); DirectoryEntry directoryEntry = new DirectoryEntry(directory.Name, DirectoryEntryType.Directory);
Directories.Add(DirectoryEntry); directories.Add(directoryEntry);
} }
return Directories.ToArray(); return directories.ToArray();
} }
public DirectoryEntry[] GetEntries(string Path) public DirectoryEntry[] GetEntries(string path)
{ {
List<DirectoryEntry> Entries = new List<DirectoryEntry>(); List<DirectoryEntry> entries = new List<DirectoryEntry>();
foreach (RomfsDir Directory in RomFs.Directories) foreach (RomfsDir directory in _romFs.Directories)
{ {
DirectoryEntry DirectoryEntry = new DirectoryEntry(Directory.Name, DirectoryEntryType.Directory); DirectoryEntry directoryEntry = new DirectoryEntry(directory.Name, DirectoryEntryType.Directory);
Entries.Add(DirectoryEntry); entries.Add(directoryEntry);
} }
foreach (RomfsFile File in RomFs.Files) foreach (RomfsFile file in _romFs.Files)
{ {
DirectoryEntry DirectoryEntry = new DirectoryEntry(File.Name, DirectoryEntryType.File, File.DataLength); DirectoryEntry directoryEntry = new DirectoryEntry(file.Name, DirectoryEntryType.File, file.DataLength);
Entries.Add(DirectoryEntry); entries.Add(directoryEntry);
} }
return Entries.ToArray(); return entries.ToArray();
} }
public DirectoryEntry[] GetFiles(string Path) public DirectoryEntry[] GetFiles(string path)
{ {
List<DirectoryEntry> Files = new List<DirectoryEntry>(); List<DirectoryEntry> files = new List<DirectoryEntry>();
foreach (RomfsFile File in RomFs.Files) foreach (RomfsFile file in _romFs.Files)
{ {
DirectoryEntry DirectoryEntry = new DirectoryEntry(File.Name, DirectoryEntryType.File, File.DataLength); DirectoryEntry directoryEntry = new DirectoryEntry(file.Name, DirectoryEntryType.File, file.DataLength);
Files.Add(DirectoryEntry); files.Add(directoryEntry);
} }
return Files.ToArray(); return files.ToArray();
} }
public long GetFreeSpace(ServiceCtx Context) public long GetFreeSpace(ServiceCtx context)
{ {
return 0; return 0;
} }
public string GetFullPath(string Name) public string GetFullPath(string name)
{ {
return Name; return name;
} }
public long GetTotalSpace(ServiceCtx Context) public long GetTotalSpace(ServiceCtx context)
{ {
return RomFs.Files.Sum(x => x.DataLength); return _romFs.Files.Sum(x => x.DataLength);
} }
public bool DirectoryExists(string Name) public bool DirectoryExists(string name)
{ {
return RomFs.Directories.Exists(x=>x.Name == Name); return _romFs.Directories.Exists(x=>x.Name == name);
} }
public bool FileExists(string Name) public bool FileExists(string name)
{ {
return RomFs.FileExists(Name); return _romFs.FileExists(name);
} }
public long OpenDirectory(string Name, int FilterFlags, out IDirectory DirectoryInterface) public long OpenDirectory(string name, int filterFlags, out IDirectory directoryInterface)
{ {
RomfsDir Directory = RomFs.Directories.Find(x => x.Name == Name); RomfsDir directory = _romFs.Directories.Find(x => x.Name == name);
if (Directory != null) if (directory != null)
{ {
DirectoryInterface = new IDirectory(Name, FilterFlags, this); directoryInterface = new IDirectory(name, filterFlags, this);
return 0; return 0;
} }
DirectoryInterface = null; directoryInterface = null;
return MakeError(ErrorModule.Fs, FsErr.PathDoesNotExist); return MakeError(ErrorModule.Fs, FsErr.PathDoesNotExist);
} }
public long OpenFile(string Name, out IFile FileInterface) public long OpenFile(string name, out IFile fileInterface)
{ {
if (RomFs.FileExists(Name)) if (_romFs.FileExists(name))
{ {
Stream Stream = RomFs.OpenFile(Name); Stream stream = _romFs.OpenFile(name);
FileInterface = new IFile(Stream, Name); fileInterface = new IFile(stream, name);
return 0; return 0;
} }
FileInterface = null; fileInterface = null;
return MakeError(ErrorModule.Fs, FsErr.PathDoesNotExist); return MakeError(ErrorModule.Fs, FsErr.PathDoesNotExist);
} }
public long RenameDirectory(string OldName, string NewName) public long RenameDirectory(string oldName, string newName)
{ {
throw new NotSupportedException(); throw new NotSupportedException();
} }
public long RenameFile(string OldName, string NewName) public long RenameFile(string oldName, string newName)
{ {
throw new NotSupportedException(); throw new NotSupportedException();
} }
public void CheckIfOutsideBasePath(string Path) public void CheckIfOutsideBasePath(string path)
{ {
throw new NotSupportedException(); throw new NotSupportedException();
} }

View file

@ -7,42 +7,39 @@ namespace Ryujinx.HLE.FileSystem
{ {
static class SaveHelper static class SaveHelper
{ {
public static string GetSavePath(SaveInfo SaveMetaData, ServiceCtx Context) public static string GetSavePath(SaveInfo saveMetaData, ServiceCtx context)
{ {
string BaseSavePath = NandPath; string baseSavePath = NandPath;
long CurrentTitleId = SaveMetaData.TitleId; long currentTitleId = saveMetaData.TitleId;
switch (SaveMetaData.SaveSpaceId) switch (saveMetaData.SaveSpaceId)
{ {
case SaveSpaceId.NandUser: case SaveSpaceId.NandUser:
BaseSavePath = UserNandPath; baseSavePath = UserNandPath;
break; break;
case SaveSpaceId.NandSystem: case SaveSpaceId.NandSystem:
BaseSavePath = SystemNandPath; baseSavePath = SystemNandPath;
break; break;
case SaveSpaceId.SdCard: case SaveSpaceId.SdCard:
BaseSavePath = Path.Combine(SdCardPath, "Nintendo"); baseSavePath = Path.Combine(SdCardPath, "Nintendo");
break; break;
} }
BaseSavePath = Path.Combine(BaseSavePath, "save"); baseSavePath = Path.Combine(baseSavePath, "save");
if (SaveMetaData.TitleId == 0 && SaveMetaData.SaveDataType == SaveDataType.SaveData) if (saveMetaData.TitleId == 0 && saveMetaData.SaveDataType == SaveDataType.SaveData)
{ {
if (Context.Process.MetaData != null) currentTitleId = context.Process.TitleId;
{
CurrentTitleId = Context.Process.MetaData.ACI0.TitleId;
}
} }
string SaveAccount = SaveMetaData.UserId.IsZero() ? "savecommon" : SaveMetaData.UserId.ToString(); string saveAccount = saveMetaData.UserId.IsZero() ? "savecommon" : saveMetaData.UserId.ToString();
string SavePath = Path.Combine(BaseSavePath, string savePath = Path.Combine(baseSavePath,
SaveMetaData.SaveId.ToString("x16"), saveMetaData.SaveId.ToString("x16"),
SaveAccount, saveAccount,
SaveMetaData.SaveDataType == SaveDataType.SaveData ? CurrentTitleId.ToString("x16") : string.Empty); saveMetaData.SaveDataType == SaveDataType.SaveData ? currentTitleId.ToString("x16") : string.Empty);
return SavePath; return savePath;
} }
} }
} }

View file

@ -4,25 +4,25 @@ namespace Ryujinx.HLE.FileSystem
{ {
struct SaveInfo struct SaveInfo
{ {
public long TitleId { get; private set; } public long TitleId { get; private set; }
public long SaveId { get; private set; } public long SaveId { get; private set; }
public UInt128 UserId { get; private set; } public UInt128 UserId { get; private set; }
public SaveDataType SaveDataType { get; private set; } public SaveDataType SaveDataType { get; private set; }
public SaveSpaceId SaveSpaceId { get; private set; } public SaveSpaceId SaveSpaceId { get; private set; }
public SaveInfo( public SaveInfo(
long TitleId, long titleId,
long SaveId, long saveId,
SaveDataType SaveDataType, SaveDataType saveDataType,
UInt128 UserId, UInt128 userId,
SaveSpaceId SaveSpaceId) SaveSpaceId saveSpaceId)
{ {
this.TitleId = TitleId; TitleId = titleId;
this.UserId = UserId; UserId = userId;
this.SaveId = SaveId; SaveId = saveId;
this.SaveDataType = SaveDataType; SaveDataType = saveDataType;
this.SaveSpaceId = SaveSpaceId; SaveSpaceId = saveSpaceId;
} }
} }
} }

View file

@ -18,40 +18,40 @@ namespace Ryujinx.HLE.FileSystem
public Stream RomFs { get; private set; } public Stream RomFs { get; private set; }
public void LoadRomFs(string FileName) public void LoadRomFs(string fileName)
{ {
RomFs = new FileStream(FileName, FileMode.Open, FileAccess.Read); RomFs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
} }
public void SetRomFs(Stream RomfsStream) public void SetRomFs(Stream romfsStream)
{ {
RomFs?.Close(); RomFs?.Close();
RomFs = RomfsStream; RomFs = romfsStream;
} }
public string GetFullPath(string BasePath, string FileName) public string GetFullPath(string basePath, string fileName)
{ {
if (FileName.StartsWith("//")) if (fileName.StartsWith("//"))
{ {
FileName = FileName.Substring(2); fileName = fileName.Substring(2);
} }
else if (FileName.StartsWith('/')) else if (fileName.StartsWith('/'))
{ {
FileName = FileName.Substring(1); fileName = fileName.Substring(1);
} }
else else
{ {
return null; return null;
} }
string FullPath = Path.GetFullPath(Path.Combine(BasePath, FileName)); string fullPath = Path.GetFullPath(Path.Combine(basePath, fileName));
if (!FullPath.StartsWith(GetBasePath())) if (!fullPath.StartsWith(GetBasePath()))
{ {
return null; return null;
} }
return FullPath; return fullPath;
} }
public string GetSdCardPath() => MakeDirAndGetFullPath(SdCardPath); public string GetSdCardPath() => MakeDirAndGetFullPath(SdCardPath);
@ -60,84 +60,84 @@ namespace Ryujinx.HLE.FileSystem
public string GetSystemPath() => MakeDirAndGetFullPath(SystemPath); public string GetSystemPath() => MakeDirAndGetFullPath(SystemPath);
public string GetGameSavePath(SaveInfo Save, ServiceCtx Context) public string GetGameSavePath(SaveInfo save, ServiceCtx context)
{ {
return MakeDirAndGetFullPath(SaveHelper.GetSavePath(Save, Context)); return MakeDirAndGetFullPath(SaveHelper.GetSavePath(save, context));
} }
public string GetFullPartitionPath(string PartitionPath) public string GetFullPartitionPath(string partitionPath)
{ {
return MakeDirAndGetFullPath(PartitionPath); return MakeDirAndGetFullPath(partitionPath);
} }
public string SwitchPathToSystemPath(string SwitchPath) public string SwitchPathToSystemPath(string switchPath)
{ {
string[] Parts = SwitchPath.Split(":"); string[] parts = switchPath.Split(":");
if (Parts.Length != 2) if (parts.Length != 2)
{ {
return null; return null;
} }
return GetFullPath(MakeDirAndGetFullPath(Parts[0]), Parts[1]); return GetFullPath(MakeDirAndGetFullPath(parts[0]), parts[1]);
} }
public string SystemPathToSwitchPath(string SystemPath) public string SystemPathToSwitchPath(string systemPath)
{ {
string BaseSystemPath = GetBasePath() + Path.DirectorySeparatorChar; string baseSystemPath = GetBasePath() + Path.DirectorySeparatorChar;
if (SystemPath.StartsWith(BaseSystemPath)) if (systemPath.StartsWith(baseSystemPath))
{ {
string RawPath = SystemPath.Replace(BaseSystemPath, ""); string rawPath = systemPath.Replace(baseSystemPath, "");
int FirstSeparatorOffset = RawPath.IndexOf(Path.DirectorySeparatorChar); int firstSeparatorOffset = rawPath.IndexOf(Path.DirectorySeparatorChar);
if (FirstSeparatorOffset == -1) if (firstSeparatorOffset == -1)
{ {
return $"{RawPath}:/"; return $"{rawPath}:/";
} }
string BasePath = RawPath.Substring(0, FirstSeparatorOffset); string basePath = rawPath.Substring(0, firstSeparatorOffset);
string FileName = RawPath.Substring(FirstSeparatorOffset + 1); string fileName = rawPath.Substring(firstSeparatorOffset + 1);
return $"{BasePath}:/{FileName}"; return $"{basePath}:/{fileName}";
} }
return null; return null;
} }
private string MakeDirAndGetFullPath(string Dir) private string MakeDirAndGetFullPath(string dir)
{ {
// Handles Common Switch Content Paths // Handles Common Switch Content Paths
switch (Dir) switch (dir)
{ {
case ContentPath.SdCard: case ContentPath.SdCard:
case "@Sdcard": case "@Sdcard":
Dir = SdCardPath; dir = SdCardPath;
break; break;
case ContentPath.User: case ContentPath.User:
Dir = UserNandPath; dir = UserNandPath;
break; break;
case ContentPath.System: case ContentPath.System:
Dir = SystemNandPath; dir = SystemNandPath;
break; break;
case ContentPath.SdCardContent: case ContentPath.SdCardContent:
Dir = Path.Combine(SdCardPath, "Nintendo", "Contents"); dir = Path.Combine(SdCardPath, "Nintendo", "Contents");
break; break;
case ContentPath.UserContent: case ContentPath.UserContent:
Dir = Path.Combine(UserNandPath, "Contents"); dir = Path.Combine(UserNandPath, "Contents");
break; break;
case ContentPath.SystemContent: case ContentPath.SystemContent:
Dir = Path.Combine(SystemNandPath, "Contents"); dir = Path.Combine(SystemNandPath, "Contents");
break; break;
} }
string FullPath = Path.Combine(GetBasePath(), Dir); string fullPath = Path.Combine(GetBasePath(), dir);
if (!Directory.Exists(FullPath)) if (!Directory.Exists(fullPath))
{ {
Directory.CreateDirectory(FullPath); Directory.CreateDirectory(fullPath);
} }
return FullPath; return fullPath;
} }
public DriveInfo GetDrive() public DriveInfo GetDrive()
@ -147,9 +147,9 @@ namespace Ryujinx.HLE.FileSystem
public string GetBasePath() public string GetBasePath()
{ {
string AppDataPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData); string appDataPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
return Path.Combine(AppDataPath, BasePath); return Path.Combine(appDataPath, BasePath);
} }
public void Dispose() public void Dispose()

View file

@ -4,22 +4,22 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler.Ast
{ {
public class ArraySubscriptingExpression : BaseNode public class ArraySubscriptingExpression : BaseNode
{ {
private BaseNode LeftNode; private BaseNode _leftNode;
private BaseNode Subscript; private BaseNode _subscript;
public ArraySubscriptingExpression(BaseNode LeftNode, BaseNode Subscript) : base(NodeType.ArraySubscriptingExpression) public ArraySubscriptingExpression(BaseNode leftNode, BaseNode subscript) : base(NodeType.ArraySubscriptingExpression)
{ {
this.LeftNode = LeftNode; _leftNode = leftNode;
this.Subscript = Subscript; _subscript = subscript;
} }
public override void PrintLeft(TextWriter Writer) public override void PrintLeft(TextWriter writer)
{ {
Writer.Write("("); writer.Write("(");
LeftNode.Print(Writer); _leftNode.Print(writer);
Writer.Write(")["); writer.Write(")[");
Subscript.Print(Writer); _subscript.Print(writer);
Writer.Write("]"); writer.Write("]");
} }
} }
} }

View file

@ -4,20 +4,20 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler.Ast
{ {
public class ArrayType : BaseNode public class ArrayType : BaseNode
{ {
private BaseNode Base; private BaseNode _base;
private BaseNode DimensionExpression; private BaseNode _dimensionExpression;
private string DimensionString; private string _dimensionString;
public ArrayType(BaseNode Base, BaseNode DimensionExpression = null) : base(NodeType.ArrayType) public ArrayType(BaseNode Base, BaseNode dimensionExpression = null) : base(NodeType.ArrayType)
{ {
this.Base = Base; _base = Base;
this.DimensionExpression = DimensionExpression; _dimensionExpression = dimensionExpression;
} }
public ArrayType(BaseNode Base, string DimensionString) : base(NodeType.ArrayType) public ArrayType(BaseNode Base, string dimensionString) : base(NodeType.ArrayType)
{ {
this.Base = Base; _base = Base;
this.DimensionString = DimensionString; _dimensionString = dimensionString;
} }
public override bool HasRightPart() public override bool HasRightPart()
@ -30,30 +30,30 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler.Ast
return true; return true;
} }
public override void PrintLeft(TextWriter Writer) public override void PrintLeft(TextWriter writer)
{ {
Base.PrintLeft(Writer); _base.PrintLeft(writer);
} }
public override void PrintRight(TextWriter Writer) public override void PrintRight(TextWriter writer)
{ {
// FIXME: detect if previous char was a ]. // FIXME: detect if previous char was a ].
Writer.Write(" "); writer.Write(" ");
Writer.Write("["); writer.Write("[");
if (DimensionString != null) if (_dimensionString != null)
{ {
Writer.Write(DimensionString); writer.Write(_dimensionString);
} }
else if (DimensionExpression != null) else if (_dimensionExpression != null)
{ {
DimensionExpression.Print(Writer); _dimensionExpression.Print(writer);
} }
Writer.Write("]"); writer.Write("]");
Base.PrintRight(Writer); _base.PrintRight(writer);
} }
} }
} }

View file

@ -4,7 +4,7 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler.Ast
{ {
public enum NodeType public enum NodeType
{ {
CVQualifierType, CvQualifierType,
SimpleReferenceType, SimpleReferenceType,
NameType, NameType,
EncodedFunction, EncodedFunction,
@ -62,22 +62,22 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler.Ast
{ {
public NodeType Type { get; protected set; } public NodeType Type { get; protected set; }
public BaseNode(NodeType Type) public BaseNode(NodeType type)
{ {
this.Type = Type; Type = type;
} }
public virtual void Print(TextWriter Writer) public virtual void Print(TextWriter writer)
{ {
PrintLeft(Writer); PrintLeft(writer);
if (HasRightPart()) if (HasRightPart())
{ {
PrintRight(Writer); PrintRight(writer);
} }
} }
public abstract void PrintLeft(TextWriter Writer); public abstract void PrintLeft(TextWriter writer);
public virtual bool HasRightPart() public virtual bool HasRightPart()
{ {
@ -99,15 +99,15 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler.Ast
return null; return null;
} }
public virtual void PrintRight(TextWriter Writer) {} public virtual void PrintRight(TextWriter writer) {}
public override string ToString() public override string ToString()
{ {
StringWriter Writer = new StringWriter(); StringWriter writer = new StringWriter();
Print(Writer); Print(writer);
return Writer.ToString(); return writer.ToString();
} }
} }
} }

View file

@ -4,37 +4,37 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler.Ast
{ {
public class BinaryExpression : BaseNode public class BinaryExpression : BaseNode
{ {
private BaseNode LeftPart; private BaseNode _leftPart;
private string Name; private string _name;
private BaseNode RightPart; private BaseNode _rightPart;
public BinaryExpression(BaseNode LeftPart, string Name, BaseNode RightPart) : base(NodeType.BinaryExpression) public BinaryExpression(BaseNode leftPart, string name, BaseNode rightPart) : base(NodeType.BinaryExpression)
{ {
this.LeftPart = LeftPart; _leftPart = leftPart;
this.Name = Name; _name = name;
this.RightPart = RightPart; _rightPart = rightPart;
} }
public override void PrintLeft(TextWriter Writer) public override void PrintLeft(TextWriter writer)
{ {
if (Name.Equals(">")) if (_name.Equals(">"))
{ {
Writer.Write("("); writer.Write("(");
} }
Writer.Write("("); writer.Write("(");
LeftPart.Print(Writer); _leftPart.Print(writer);
Writer.Write(") "); writer.Write(") ");
Writer.Write(Name); writer.Write(_name);
Writer.Write(" ("); writer.Write(" (");
RightPart.Print(Writer); _rightPart.Print(writer);
Writer.Write(")"); writer.Write(")");
if (Name.Equals(">")) if (_name.Equals(">"))
{ {
Writer.Write(")"); writer.Write(")");
} }
} }
} }

View file

@ -4,37 +4,37 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler.Ast
{ {
public class BracedExpression : BaseNode public class BracedExpression : BaseNode
{ {
private BaseNode Element; private BaseNode _element;
private BaseNode Expression; private BaseNode _expression;
private bool IsArrayExpression; private bool _isArrayExpression;
public BracedExpression(BaseNode Element, BaseNode Expression, bool IsArrayExpression) : base(NodeType.BracedExpression) public BracedExpression(BaseNode element, BaseNode expression, bool isArrayExpression) : base(NodeType.BracedExpression)
{ {
this.Element = Element; _element = element;
this.Expression = Expression; _expression = expression;
this.IsArrayExpression = IsArrayExpression; _isArrayExpression = isArrayExpression;
} }
public override void PrintLeft(TextWriter Writer) public override void PrintLeft(TextWriter writer)
{ {
if (IsArrayExpression) if (_isArrayExpression)
{ {
Writer.Write("["); writer.Write("[");
Element.Print(Writer); _element.Print(writer);
Writer.Write("]"); writer.Write("]");
} }
else else
{ {
Writer.Write("."); writer.Write(".");
Element.Print(Writer); _element.Print(writer);
} }
if (!Expression.GetType().Equals(NodeType.BracedExpression) || !Expression.GetType().Equals(NodeType.BracedRangeExpression)) if (!_expression.GetType().Equals(NodeType.BracedExpression) || !_expression.GetType().Equals(NodeType.BracedRangeExpression))
{ {
Writer.Write(" = "); writer.Write(" = ");
} }
Expression.Print(Writer); _expression.Print(writer);
} }
} }
} }

View file

@ -4,31 +4,31 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler.Ast
{ {
public class BracedRangeExpression : BaseNode public class BracedRangeExpression : BaseNode
{ {
private BaseNode FirstNode; private BaseNode _firstNode;
private BaseNode LastNode; private BaseNode _lastNode;
private BaseNode Expression; private BaseNode _expression;
public BracedRangeExpression(BaseNode FirstNode, BaseNode LastNode, BaseNode Expression) : base(NodeType.BracedRangeExpression) public BracedRangeExpression(BaseNode firstNode, BaseNode lastNode, BaseNode expression) : base(NodeType.BracedRangeExpression)
{ {
this.FirstNode = FirstNode; _firstNode = firstNode;
this.LastNode = LastNode; _lastNode = lastNode;
this.Expression = Expression; _expression = expression;
} }
public override void PrintLeft(TextWriter Writer) public override void PrintLeft(TextWriter writer)
{ {
Writer.Write("["); writer.Write("[");
FirstNode.Print(Writer); _firstNode.Print(writer);
Writer.Write(" ... "); writer.Write(" ... ");
LastNode.Print(Writer); _lastNode.Print(writer);
Writer.Write("]"); writer.Write("]");
if (!Expression.GetType().Equals(NodeType.BracedExpression) || !Expression.GetType().Equals(NodeType.BracedRangeExpression)) if (!_expression.GetType().Equals(NodeType.BracedExpression) || !_expression.GetType().Equals(NodeType.BracedRangeExpression))
{ {
Writer.Write(" = "); writer.Write(" = ");
} }
Expression.Print(Writer); _expression.Print(writer);
} }
} }
} }

View file

@ -5,20 +5,20 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler.Ast
{ {
public class CallExpression : NodeArray public class CallExpression : NodeArray
{ {
private BaseNode Callee; private BaseNode _callee;
public CallExpression(BaseNode Callee, List<BaseNode> Nodes) : base(Nodes, NodeType.CallExpression) public CallExpression(BaseNode callee, List<BaseNode> nodes) : base(nodes, NodeType.CallExpression)
{ {
this.Callee = Callee; _callee = callee;
} }
public override void PrintLeft(TextWriter Writer) public override void PrintLeft(TextWriter writer)
{ {
Callee.Print(Writer); _callee.Print(writer);
Writer.Write("("); writer.Write("(");
Writer.Write(string.Join<BaseNode>(", ", Nodes.ToArray())); writer.Write(string.Join<BaseNode>(", ", Nodes.ToArray()));
Writer.Write(")"); writer.Write(")");
} }
} }
} }

View file

@ -4,25 +4,25 @@ namespace Ryujinx.HLE.HOS.Diagnostics.Demangler.Ast
{ {
public class CastExpression : BaseNode public class CastExpression : BaseNode
{ {
private string Kind; private string _kind;
private BaseNode To; private BaseNode _to;
private BaseNode From; private BaseNode _from;
public CastExpression(string Kind, BaseNode To, BaseNode From) : base(NodeType.CastExpression) public CastExpression(string kind, BaseNode to, BaseNode from) : base(NodeType.CastExpression)
{ {
this.Kind = Kind; _kind = kind;
this.To = To; _to = to;
this.From = From; _from = from;
} }
public override void PrintLeft(TextWriter Writer) public override void PrintLeft(TextWriter writer)
{ {
Writer.Write(Kind); writer.Write(_kind);
Writer.Write("<"); writer.Write("<");
To.PrintLeft(Writer); _to.PrintLeft(writer);
Writer.Write(">("); writer.Write(">(");
From.PrintLeft(Writer); _from.PrintLeft(writer);
Writer.Write(")"); writer.Write(")");
} }
} }
} }

Some files were not shown because too many files have changed in this diff Show more