using System.Buffers.Binary; using System.Text; namespace EvilEngine.Adapters.Tests.Support; public static class Ps3Files { public static byte[] ParamSfo(params (string Key, object Value)[] values) { var keys = new MemoryStream(); var data = new MemoryStream(); var entries = new List<(int Key, ushort Format, int Length, int Max, int Data)>(); foreach (var (key, value) in values.OrderBy(value => value.Key, StringComparer.Ordinal)) { var keyAt = (int)keys.Length; keys.Write(Encoding.ASCII.GetBytes(key + "\0")); var dataAt = (int)data.Length; byte[] bytes; ushort format; if (value is uint number) { bytes = new byte[4]; BinaryPrimitives.WriteUInt32LittleEndian(bytes, number); format = 0x0404; } else { bytes = Encoding.UTF8.GetBytes((string)value + "\0"); format = 0x0204; } var max = (bytes.Length + 3) & ~3; data.Write(bytes); data.Write(new byte[max - bytes.Length]); entries.Add((keyAt, format, bytes.Length, max, dataAt)); } while (keys.Length % 4 != 0) keys.WriteByte(0); var keyTable = 20 + entries.Count * 16; var dataTable = keyTable + (int)keys.Length; var sfo = new byte[dataTable + data.Length]; "\0PSF"u8.CopyTo(sfo); BinaryPrimitives.WriteUInt32LittleEndian(sfo.AsSpan(4), 0x101); BinaryPrimitives.WriteUInt32LittleEndian(sfo.AsSpan(8), (uint)keyTable); BinaryPrimitives.WriteUInt32LittleEndian(sfo.AsSpan(12), (uint)dataTable); BinaryPrimitives.WriteUInt32LittleEndian(sfo.AsSpan(16), (uint)entries.Count); for (var i = 0; i < entries.Count; i++) { var entry = sfo.AsSpan(20 + i * 16); BinaryPrimitives.WriteUInt16LittleEndian(entry, (ushort)entries[i].Key); BinaryPrimitives.WriteUInt16LittleEndian(entry[2..], entries[i].Format); BinaryPrimitives.WriteUInt32LittleEndian(entry[4..], (uint)entries[i].Length); BinaryPrimitives.WriteUInt32LittleEndian(entry[8..], (uint)entries[i].Max); BinaryPrimitives.WriteUInt32LittleEndian(entry[12..], (uint)entries[i].Data); } keys.ToArray().CopyTo(sfo, keyTable); data.ToArray().CopyTo(sfo, dataTable); return sfo; } public static byte[] DiscSfb(string titleId) { var sfb = new byte[0x600]; ".SFB"u8.CopyTo(sfb); BinaryPrimitives.WriteUInt32BigEndian(sfb.AsSpan(4), 0x10000); Entry(sfb, 0x20, "HYBRID_FLAG", 0x200, "gu"); Entry(sfb, 0x40, "TITLE_ID", 0x220, titleId); return sfb; } private static void Entry(byte[] sfb, int at, string key, int offset, string value) { Encoding.ASCII.GetBytes(key).CopyTo(sfb, at); BinaryPrimitives.WriteUInt32BigEndian(sfb.AsSpan(at + 16), (uint)offset); BinaryPrimitives.WriteUInt32BigEndian(sfb.AsSpan(at + 20), 0x10); Encoding.ASCII.GetBytes(value).CopyTo(sfb, offset); } }