Finished reformatting; fixed name violations, other IDE Messages; Massive code cleanup

This commit is contained in:
Michael 2021-02-06 22:53:40 -06:00
parent ff33cd3254
commit 8283d95680
42 changed files with 7653 additions and 6650 deletions

View file

@ -1,10 +1,9 @@
using System.Reflection; using System.Reflection;
using System.Resources; using System.Resources;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
using System.Security.Permissions;
[assembly: AssemblyTitle("libWiiSharp_Modified")] [assembly: AssemblyTitle("libWiiSharp_Modified")]
[assembly: AssemblyDescription("a wii related .NET library modified to add features for othe programs.")] [assembly: AssemblyDescription("A wii related .NET library modified to add features for othe programs.")]
[assembly: AssemblyConfiguration("")] [assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Leathl,SC reproductions")] [assembly: AssemblyCompany("Leathl,SC reproductions")]
[assembly: AssemblyProduct("libWiiSharp_Modified")] [assembly: AssemblyProduct("libWiiSharp_Modified")]
@ -15,5 +14,3 @@ using System.Security.Permissions;
[assembly: AssemblyFileVersion("0.4.0.0")] [assembly: AssemblyFileVersion("0.4.0.0")]
[assembly: NeutralResourcesLanguage("en")] [assembly: NeutralResourcesLanguage("en")]
[assembly: AssemblyVersion("0.4.0.0")] [assembly: AssemblyVersion("0.4.0.0")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]

451
BNS.cs
View file

@ -29,52 +29,56 @@ namespace libWiiSharp
private BNS_Header bnsHeader = new BNS_Header(); private BNS_Header bnsHeader = new BNS_Header();
private BNS_Info bnsInfo = new BNS_Info(); private BNS_Info bnsInfo = new BNS_Info();
private BNS_Data bnsData = new BNS_Data(); private BNS_Data bnsData = new BNS_Data();
private int[,] lSamples = new int[2, 2]; // Unused
//private int[,] lSamples = new int[2, 2];
private int[,] rlSamples = new int[2, 2]; private int[,] rlSamples = new int[2, 2];
private int[] tlSamples = new int[2]; private int[] tlSamples = new int[2];
// Unused
/*
private int[] hbcDefTbl = new int[16] private int[] hbcDefTbl = new int[16]
{ {
674, 674,
1040, 1040,
3598, 3598,
-1738, -1738,
2270, 2270,
-583, -583,
3967, 3967,
-1969, -1969,
1516, 1516,
381, 381,
3453, 3453,
-1468, -1468,
2606, 2606,
-617, -617,
3795, 3795,
-1759 -1759
}; };
private int[] defTbl = new int[16] */
{ private readonly int[] defTbl = new int[16]
1820, {
-856, 1820,
3238, -856,
-1514, 3238,
2333, -1514,
-550, 2333,
3336, -550,
-1376, 3336,
2444, -1376,
-949, 2444,
3666, -949,
-1764, 3666,
2654, -1764,
-701, 2654,
3420, -701,
-1398 3420,
}; -1398
};
private int[] pHist1 = new int[2]; private int[] pHist1 = new int[2];
private int[] pHist2 = new int[2]; private int[] pHist2 = new int[2];
private int tempSampleCount; private int tempSampleCount;
private byte[] waveFile; private byte[] waveFile;
private bool loopFromWave; private readonly bool loopFromWave;
private bool converted; private bool converted;
private bool toMono; private bool toMono;
private bool isDisposed; private bool isDisposed;
@ -84,8 +88,8 @@ namespace libWiiSharp
/// </summary> /// </summary>
public bool HasLoop public bool HasLoop
{ {
get => this.bnsInfo.HasLoop == (byte) 1; get => bnsInfo.HasLoop == 1;
set => this.bnsInfo.HasLoop = value ? (byte) 1 : (byte) 0; set => bnsInfo.HasLoop = value ? 1 : 0;
} }
/// <summary> /// <summary>
@ -93,8 +97,8 @@ namespace libWiiSharp
/// </summary> /// </summary>
public uint LoopStart public uint LoopStart
{ {
get => this.bnsInfo.LoopStart; get => bnsInfo.LoopStart;
set => this.bnsInfo.LoopStart = value; set => bnsInfo.LoopStart = value;
} }
/// <summary> /// <summary>
@ -102,8 +106,8 @@ namespace libWiiSharp
/// </summary> /// </summary>
public uint TotalSampleCount public uint TotalSampleCount
{ {
get => this.bnsInfo.LoopEnd; get => bnsInfo.LoopEnd;
set => this.bnsInfo.LoopEnd = value; set => bnsInfo.LoopEnd = value;
} }
/// <summary> /// <summary>
@ -112,8 +116,8 @@ namespace libWiiSharp
/// </summary> /// </summary>
public bool StereoToMono public bool StereoToMono
{ {
get => this.toMono; get => toMono;
set => this.toMono = value; set => toMono = value;
} }
public event EventHandler<ProgressChangedEventArgs> Progress; public event EventHandler<ProgressChangedEventArgs> Progress;
@ -123,7 +127,10 @@ namespace libWiiSharp
} }
public BNS(string waveFile) => this.waveFile = File.ReadAllBytes(waveFile); public BNS(string waveFile)
{
this.waveFile = File.ReadAllBytes(waveFile);
}
public BNS(string waveFile, bool loopFromWave) public BNS(string waveFile, bool loopFromWave)
{ {
@ -131,7 +138,10 @@ namespace libWiiSharp
this.loopFromWave = loopFromWave; this.loopFromWave = loopFromWave;
} }
public BNS(byte[] waveFile) => this.waveFile = waveFile; public BNS(byte[] waveFile)
{
this.waveFile = waveFile;
}
public BNS(byte[] waveFile, bool loopFromWave) public BNS(byte[] waveFile, bool loopFromWave)
{ {
@ -141,31 +151,31 @@ namespace libWiiSharp
#region IDisposable Members #region IDisposable Members
~BNS() => this.Dispose(false); ~BNS() => Dispose(false);
public void Dispose() public void Dispose()
{ {
this.Dispose(true); Dispose(true);
GC.SuppressFinalize((object) this); GC.SuppressFinalize(this);
} }
protected virtual void Dispose(bool disposing) protected virtual void Dispose(bool disposing)
{ {
if (disposing && !this.isDisposed) if (disposing && !isDisposed)
{ {
this.bnsHeader = (BNS_Header) null; bnsHeader = null;
this.bnsInfo = (BNS_Info) null; bnsInfo = null;
this.bnsData = (BNS_Data) null; bnsData = null;
this.lSamples = (int[,]) null; //this.lSamples = (int[,])null;
this.rlSamples = (int[,]) null; rlSamples = null;
this.tlSamples = (int[]) null; tlSamples = null;
this.hbcDefTbl = (int[]) null; //this.hbcDefTbl = (int[])null;
this.pHist1 = (int[]) null; pHist1 = null;
this.pHist2 = (int[]) null; pHist2 = null;
this.waveFile = (byte[]) null; waveFile = null;
} }
this.isDisposed = true; isDisposed = true;
} }
#endregion #endregion
@ -179,7 +189,7 @@ namespace libWiiSharp
/// <returns></returns> /// <returns></returns>
public static int GetBnsLength(byte[] bnsFile) public static int GetBnsLength(byte[] bnsFile)
{ {
uint sampleRate = (uint) Shared.Swap(BitConverter.ToUInt16(bnsFile, 44)); uint sampleRate = Shared.Swap(BitConverter.ToUInt16(bnsFile, 44));
uint sampleCount = Shared.Swap(BitConverter.ToUInt32(bnsFile, 52)); uint sampleCount = Shared.Swap(BitConverter.ToUInt32(bnsFile, 52));
return (int)(sampleCount / sampleRate); return (int)(sampleCount / sampleRate);
@ -188,13 +198,19 @@ namespace libWiiSharp
/// <summary> /// <summary>
/// Converts the Wave file to BNS /// Converts the Wave file to BNS
/// </summary> /// </summary>
public void Convert() => this.convert(this.waveFile, this.loopFromWave); public void Convert()
{
Convert(waveFile, loopFromWave);
}
/// <summary> /// <summary>
/// Returns the BNS file as a Byte Array. If not already converted, it will be done first. /// Returns the BNS file as a Byte Array. If not already converted, it will be done first.
/// </summary> /// </summary>
/// <returns></returns> /// <returns></returns>
public byte[] ToByteArray() => this.ToMemoryStream().ToArray(); public byte[] ToByteArray()
{
return ToMemoryStream().ToArray();
}
/// <summary> /// <summary>
/// Returns the BNS file as a Memory Stream. If not already converted, it will be done first. /// Returns the BNS file as a Memory Stream. If not already converted, it will be done first.
@ -202,14 +218,17 @@ namespace libWiiSharp
/// <returns></returns> /// <returns></returns>
public MemoryStream ToMemoryStream() public MemoryStream ToMemoryStream()
{ {
if (!this.converted) if (!converted)
this.convert(this.waveFile, this.loopFromWave); {
Convert(waveFile, loopFromWave);
}
MemoryStream memoryStream = new MemoryStream(); MemoryStream memoryStream = new MemoryStream();
try try
{ {
this.bnsHeader.Write((Stream) memoryStream); bnsHeader.Write(memoryStream);
this.bnsInfo.Write((Stream) memoryStream); bnsInfo.Write(memoryStream);
this.bnsData.Write((Stream) memoryStream); bnsData.Write(memoryStream);
return memoryStream; return memoryStream;
} }
catch catch
@ -226,12 +245,13 @@ namespace libWiiSharp
public void Save(string destinationFile) public void Save(string destinationFile)
{ {
if (File.Exists(destinationFile)) if (File.Exists(destinationFile))
File.Delete(destinationFile);
using (FileStream fileStream = new FileStream(destinationFile, FileMode.Create))
{ {
byte[] array = this.ToMemoryStream().ToArray(); File.Delete(destinationFile);
fileStream.Write(array, 0, array.Length);
} }
using FileStream fileStream = new FileStream(destinationFile, FileMode.Create);
byte[] array = ToMemoryStream().ToArray();
fileStream.Write(array, 0, array.Length);
} }
/// <summary> /// <summary>
@ -240,83 +260,96 @@ namespace libWiiSharp
/// <param name="loopStartSample"></param> /// <param name="loopStartSample"></param>
public void SetLoop(int loopStartSample) public void SetLoop(int loopStartSample)
{ {
this.bnsInfo.HasLoop = (byte) 1; bnsInfo.HasLoop = 1;
this.bnsInfo.LoopStart = (uint) loopStartSample; bnsInfo.LoopStart = (uint)loopStartSample;
} }
#endregion #endregion
#region Private Functions #region Private Functions
private void convert(byte[] waveFile, bool loopFromWave) private void Convert(byte[] waveFile, bool loopFromWave)
{ {
Wave wave = new Wave(waveFile); Wave wave = new Wave(waveFile);
int numLoops = wave.NumLoops; int numLoops = wave.NumLoops;
int loopStart = wave.LoopStart; int loopStart = wave.LoopStart;
this.bnsInfo.ChannelCount = (byte) wave.NumChannels; bnsInfo.ChannelCount = (byte)wave.NumChannels;
this.bnsInfo.SampleRate = (ushort) wave.SampleRate; bnsInfo.SampleRate = (ushort)wave.SampleRate;
if (this.bnsInfo.ChannelCount > (byte) 2 || this.bnsInfo.ChannelCount < (byte) 1) if (bnsInfo.ChannelCount > 2 || bnsInfo.ChannelCount < 1)
throw new Exception("Unsupported Amount of Channels!");
if (wave.BitDepth != 16)
throw new Exception("Only 16bit Wave files are supported!");
this.bnsData.Data = wave.DataFormat == 1 ? this.Encode(wave.SampleData) : throw new Exception("The format of this Wave file is not supported!");
if (this.bnsInfo.ChannelCount == (byte) 1)
{ {
this.bnsHeader.InfoLength = 96U; throw new Exception("Unsupported Amount of Channels!");
this.bnsHeader.DataOffset = 128U;
this.bnsInfo.Size = 96U;
this.bnsInfo.Channel1StartOffset = 28U;
this.bnsInfo.Channel2StartOffset = 0U;
this.bnsInfo.Channel1Start = 40U;
this.bnsInfo.Coefficients1Offset = 0U;
} }
this.bnsData.Size = (uint) (this.bnsData.Data.Length + 8);
this.bnsHeader.DataLength = this.bnsData.Size; if (wave.BitDepth != 16)
this.bnsHeader.FileSize = (uint) this.bnsHeader.Size + this.bnsInfo.Size + this.bnsData.Size; {
throw new Exception("Only 16bit Wave files are supported!");
}
bnsData.Data = wave.DataFormat == 1 ? Encode(wave.SampleData) : throw new Exception("The format of this Wave file is not supported!");
if (bnsInfo.ChannelCount == 1)
{
bnsHeader.InfoLength = 96U;
bnsHeader.DataOffset = 128U;
bnsInfo.Size = 96U;
bnsInfo.Channel1StartOffset = 28U;
bnsInfo.Channel2StartOffset = 0U;
bnsInfo.Channel1Start = 40U;
bnsInfo.Coefficients1Offset = 0U;
}
bnsData.Size = (uint)(bnsData.Data.Length + 8);
bnsHeader.DataLength = bnsData.Size;
bnsHeader.FileSize = bnsHeader.Size + bnsInfo.Size + bnsData.Size;
if (loopFromWave && numLoops == 1 && loopStart != -1) if (loopFromWave && numLoops == 1 && loopStart != -1)
{ {
this.bnsInfo.LoopStart = (uint) loopStart; bnsInfo.LoopStart = (uint)loopStart;
this.bnsInfo.HasLoop = (byte) 1; bnsInfo.HasLoop = 1;
} }
this.bnsInfo.LoopEnd = (uint) this.tempSampleCount; bnsInfo.LoopEnd = (uint)tempSampleCount;
for (int index = 0; index < 16; ++index) for (int index = 0; index < 16; ++index)
{ {
this.bnsInfo.Coefficients1[index] = this.defTbl[index]; bnsInfo.Coefficients1[index] = defTbl[index];
if (this.bnsInfo.ChannelCount == (byte) 2) if (bnsInfo.ChannelCount == 2)
this.bnsInfo.Coefficients2[index] = this.defTbl[index]; {
bnsInfo.Coefficients2[index] = defTbl[index];
}
} }
this.converted = true; converted = true;
} }
private byte[] Encode(byte[] inputFrames) private byte[] Encode(byte[] inputFrames)
{ {
int[] inputBuffer = new int[14]; int[] inputBuffer = new int[14];
this.tempSampleCount = inputFrames.Length / (this.bnsInfo.ChannelCount == (byte) 2 ? 4 : 2); tempSampleCount = inputFrames.Length / (bnsInfo.ChannelCount == 2 ? 4 : 2);
int num1 = inputFrames.Length / (this.bnsInfo.ChannelCount == (byte) 2 ? 4 : 2) % 14; int num1 = inputFrames.Length / (bnsInfo.ChannelCount == 2 ? 4 : 2) % 14;
Array.Resize<byte>(ref inputFrames, inputFrames.Length + (14 - num1) * (this.bnsInfo.ChannelCount == (byte) 2 ? 4 : 2)); Array.Resize<byte>(ref inputFrames, inputFrames.Length + (14 - num1) * (bnsInfo.ChannelCount == 2 ? 4 : 2));
int num2 = inputFrames.Length / (this.bnsInfo.ChannelCount == (byte) 2 ? 4 : 2); int num2 = inputFrames.Length / (bnsInfo.ChannelCount == 2 ? 4 : 2);
int num3 = (num2 + 13) / 14; int num3 = (num2 + 13) / 14;
List<int> intList1 = new List<int>(); List<int> intList1 = new List<int>();
List<int> intList2 = new List<int>(); List<int> intList2 = new List<int>();
int startIndex = 0; int startIndex = 0;
if (this.toMono && this.bnsInfo.ChannelCount == (byte) 2) if (toMono && bnsInfo.ChannelCount == 2)
this.bnsInfo.ChannelCount = (byte) 1; {
else if (this.toMono) bnsInfo.ChannelCount = 1;
this.toMono = false; }
else if (toMono)
{
toMono = false;
}
for (int index = 0; index < num2; ++index) for (int index = 0; index < num2; ++index)
{ {
intList1.Add((int) BitConverter.ToInt16(inputFrames, startIndex)); intList1.Add(BitConverter.ToInt16(inputFrames, startIndex));
startIndex += 2; startIndex += 2;
if (this.bnsInfo.ChannelCount == (byte) 2 || this.toMono) if (bnsInfo.ChannelCount == 2 || toMono)
{ {
intList2.Add((int) BitConverter.ToInt16(inputFrames, startIndex)); intList2.Add(BitConverter.ToInt16(inputFrames, startIndex));
startIndex += 2; startIndex += 2;
} }
} }
byte[] numArray1 = new byte[this.bnsInfo.ChannelCount == (byte) 2 ? num3 * 16 : num3 * 8]; byte[] numArray1 = new byte[bnsInfo.ChannelCount == 2 ? num3 * 16 : num3 * 8];
int num4 = 0; int num4 = 0;
int num5 = num3 * 8; int num5 = num3 * 8;
this.bnsInfo.Channel2Start = this.bnsInfo.ChannelCount == (byte) 2 ? (uint) num5 : 0U; bnsInfo.Channel2Start = bnsInfo.ChannelCount == 2 ? (uint)num5 : 0U;
int[] array1 = intList1.ToArray(); int[] array1 = intList1.ToArray();
int[] array2 = intList2.ToArray(); int[] array2 = intList2.ToArray();
for (int index1 = 0; index1 < num3; ++index1) for (int index1 = 0; index1 < num3; ++index1)
@ -326,31 +359,45 @@ namespace libWiiSharp
if (index1 % (num3 / 100) != 0) if (index1 % (num3 / 100) != 0)
{ {
if (index1 + 1 != num3) if (index1 + 1 != num3)
goto label_14; {
goto label_14;
}
} }
this.ChangeProgress((index1 + 1) * 100 / num3); ChangeProgress((index1 + 1) * 100 / num3);
} }
catch catch
{ {
} }
label_14: label_14:
for (int index2 = 0; index2 < 14; ++index2) for (int index2 = 0; index2 < 14; ++index2)
{
inputBuffer[index2] = array1[index1 * 14 + index2]; inputBuffer[index2] = array1[index1 * 14 + index2];
byte[] numArray2 = this.RepackAdpcm(0, this.defTbl, inputBuffer); }
byte[] numArray2 = RepackAdpcm(0, defTbl, inputBuffer);
for (int index2 = 0; index2 < 8; ++index2) for (int index2 = 0; index2 < 8; ++index2)
{
numArray1[num4 + index2] = numArray2[index2]; numArray1[num4 + index2] = numArray2[index2];
}
num4 += 8; num4 += 8;
if (this.bnsInfo.ChannelCount == (byte) 2) if (bnsInfo.ChannelCount == 2)
{ {
for (int index2 = 0; index2 < 14; ++index2) for (int index2 = 0; index2 < 14; ++index2)
{
inputBuffer[index2] = array2[index1 * 14 + index2]; inputBuffer[index2] = array2[index1 * 14 + index2];
byte[] numArray3 = this.RepackAdpcm(1, this.defTbl, inputBuffer); }
byte[] numArray3 = RepackAdpcm(1, defTbl, inputBuffer);
for (int index2 = 0; index2 < 8; ++index2) for (int index2 = 0; index2 < 8; ++index2)
{
numArray1[num5 + index2] = numArray3[index2]; numArray1[num5 + index2] = numArray3[index2];
}
num5 += 8; num5 += 8;
} }
} }
this.bnsInfo.LoopEnd = (uint) (num3 * 7); bnsInfo.LoopEnd = (uint)(num3 * 7);
return numArray1; return numArray1;
} }
@ -361,15 +408,19 @@ namespace libWiiSharp
double num1 = 999999999.0; double num1 = 999999999.0;
for (int tableIndex = 0; tableIndex < 8; ++tableIndex) for (int tableIndex = 0; tableIndex < 8; ++tableIndex)
{ {
double outError; byte[] numArray3 = CompressAdpcm(index, table, tableIndex, inputBuffer, out double outError);
byte[] numArray3 = this.CompressAdpcm(index, table, tableIndex, inputBuffer, out outError);
if (outError < num1) if (outError < num1)
{ {
num1 = outError; num1 = outError;
for (int index1 = 0; index1 < 8; ++index1) for (int index1 = 0; index1 < 8; ++index1)
{
numArray1[index1] = numArray3[index1]; numArray1[index1] = numArray3[index1];
}
for (int index1 = 0; index1 < 2; ++index1) for (int index1 = 0; index1 < 2; ++index1)
numArray2[index1] = this.tlSamples[index1]; {
numArray2[index1] = tlSamples[index1];
}
} }
} }
for (int index1 = 0; index1 < 2; ++index1) for (int index1 = 0; index1 < 2; ++index1)
@ -395,27 +446,30 @@ namespace libWiiSharp
int num1 = 0; int num1 = 0;
int num2 = table[2 * tableIndex]; int num2 = table[2 * tableIndex];
int num3 = table[2 * tableIndex + 1]; int num3 = table[2 * tableIndex + 1];
int stdExponent = this.DetermineStdExponent(index, table, tableIndex, inputBuffer); int stdExponent = DetermineStdExponent(index, table, tableIndex, inputBuffer);
while (stdExponent <= 15) while (stdExponent <= 15)
{ {
bool flag = false; bool flag = false;
num1 = 0; num1 = 0;
numArray[0] = (byte) (stdExponent | tableIndex << 4); numArray[0] = (byte)(stdExponent | tableIndex << 4);
for (int index1 = 0; index1 < 2; ++index1) for (int index1 = 0; index1 < 2; ++index1)
this.tlSamples[index1] = this.rlSamples[index, index1]; {
tlSamples[index1] = rlSamples[index, index1];
}
int num4 = 0; int num4 = 0;
for (int index1 = 0; index1 < 14; ++index1) for (int index1 = 0; index1 < 14; ++index1)
{ {
int num5 = this.tlSamples[1] * num2 + this.tlSamples[0] * num3 >> 11; int num5 = tlSamples[1] * num2 + tlSamples[0] * num3 >> 11;
int input1 = inputBuffer[index1] - num5 >> stdExponent; int input1 = inputBuffer[index1] - num5 >> stdExponent;
if (input1 <= 7 && input1 >= -8) if (input1 <= 7 && input1 >= -8)
{ {
int num6 = this.Clamp(input1, -8, 7); int num6 = Clamp(input1, -8, 7);
numArray[index1 / 2 + 1] = (index1 & 1) == 0 ? (byte) (num6 << 4) : (byte) ((uint) numArray[index1 / 2 + 1] | (uint) (num6 & 15)); numArray[index1 / 2 + 1] = (index1 & 1) == 0 ? (byte)(num6 << 4) : (byte)(numArray[index1 / 2 + 1] | (uint)(num6 & 15));
int input2 = num5 + (num6 << stdExponent); int input2 = num5 + (num6 << stdExponent);
this.tlSamples[0] = this.tlSamples[1]; tlSamples[0] = tlSamples[1];
this.tlSamples[1] = this.Clamp(input2, (int) short.MinValue, (int) short.MaxValue); tlSamples[1] = Clamp(input2, short.MinValue, short.MaxValue);
num1 += (int) Math.Pow((double) (this.tlSamples[1] - inputBuffer[index1]), 2.0); num1 += (int)Math.Pow(tlSamples[1] - inputBuffer[index1], 2.0);
} }
else else
{ {
@ -425,11 +479,16 @@ namespace libWiiSharp
} }
} }
if (!flag) if (!flag)
{
num4 = 14; num4 = 14;
}
if (num4 == 14) if (num4 == 14)
{
break; break;
}
} }
outError = (double) num1; outError = num1;
return numArray; return numArray;
} }
@ -440,39 +499,54 @@ namespace libWiiSharp
int num2 = table[2 * tableIndex]; int num2 = table[2 * tableIndex];
int num3 = table[2 * tableIndex + 1]; int num3 = table[2 * tableIndex + 1];
for (int index1 = 0; index1 < 2; ++index1) for (int index1 = 0; index1 < 2; ++index1)
numArray[index1] = this.rlSamples[index, index1]; {
numArray[index1] = rlSamples[index, index1];
}
for (int index1 = 0; index1 < 14; ++index1) for (int index1 = 0; index1 < 14; ++index1)
{ {
int num4 = numArray[1] * num2 + numArray[0] * num3 >> 11; int num4 = numArray[1] * num2 + numArray[0] * num3 >> 11;
int num5 = inputBuffer[index1] - num4; int num5 = inputBuffer[index1] - num4;
if (num5 > num1) if (num5 > num1)
{
num1 = num5; num1 = num5;
}
numArray[0] = numArray[1]; numArray[0] = numArray[1];
numArray[1] = inputBuffer[index1]; numArray[1] = inputBuffer[index1];
} }
return this.FindExponent((double) num1); return FindExponent(num1);
} }
private int FindExponent(double residual) private int FindExponent(double residual)
{ {
int num = 0; int num = 0;
for (; residual > 7.5 || residual < -8.5; residual /= 2.0) for (; residual > 7.5 || residual < -8.5; residual /= 2.0)
{
++num; ++num;
}
return num; return num;
} }
private int Clamp(int input, int min, int max) private int Clamp(int input, int min, int max)
{ {
if (input < min) if (input < min)
{
return min; return min;
}
return input > max ? max : input; return input > max ? max : input;
} }
private void ChangeProgress(int progressPercentage) private void ChangeProgress(int progressPercentage)
{ {
EventHandler<ProgressChangedEventArgs> progress = this.Progress; EventHandler<ProgressChangedEventArgs> progress = Progress;
if (progress == null) if (progress == null)
{
return; return;
}
progress(new object(), new ProgressChangedEventArgs(progressPercentage, new object())); progress(new object(), new ProgressChangedEventArgs(progressPercentage, new object()));
} }
@ -492,33 +566,48 @@ namespace libWiiSharp
{ {
BNS bns = new BNS(); BNS bns = new BNS();
byte[] samples = bns.Read(inputFile); byte[] samples = bns.Read(inputFile);
Wave wave = new Wave((int) bns.bnsInfo.ChannelCount, 16, (int) bns.bnsInfo.SampleRate, samples); Wave wave = new Wave(bns.bnsInfo.ChannelCount, 16, bns.bnsInfo.SampleRate, samples);
if (bns.bnsInfo.HasLoop == (byte) 1) if (bns.bnsInfo.HasLoop == 1)
wave.AddLoop((int) bns.bnsInfo.LoopStart); {
wave.AddLoop((int)bns.bnsInfo.LoopStart);
}
return wave; return wave;
} }
public static Wave BnsToWave(string pathToFile) public static Wave BnsToWave(string pathToFile)
{ {
BNS bns = new BNS(); BNS bns = new BNS();
byte[] samples = (byte[]) null; byte[] samples = null;
using (FileStream fileStream = new FileStream(pathToFile, FileMode.Open)) using (FileStream fileStream = new FileStream(pathToFile, FileMode.Open))
samples = bns.Read((Stream) fileStream); {
Wave wave = new Wave((int) bns.bnsInfo.ChannelCount, 16, (int) bns.bnsInfo.SampleRate, samples); samples = bns.Read(fileStream);
if (bns.bnsInfo.HasLoop == (byte) 1) }
wave.AddLoop((int) bns.bnsInfo.LoopStart);
Wave wave = new Wave(bns.bnsInfo.ChannelCount, 16, bns.bnsInfo.SampleRate, samples);
if (bns.bnsInfo.HasLoop == 1)
{
wave.AddLoop((int)bns.bnsInfo.LoopStart);
}
return wave; return wave;
} }
public static Wave BnsToWave(byte[] bnsFile) public static Wave BnsToWave(byte[] bnsFile)
{ {
BNS bns = new BNS(); BNS bns = new BNS();
byte[] samples = (byte[]) null; byte[] samples = null;
using (MemoryStream memoryStream = new MemoryStream(bnsFile)) using (MemoryStream memoryStream = new MemoryStream(bnsFile))
samples = bns.Read((Stream) memoryStream); {
Wave wave = new Wave((int) bns.bnsInfo.ChannelCount, 16, (int) bns.bnsInfo.SampleRate, samples); samples = bns.Read(memoryStream);
if (bns.bnsInfo.HasLoop == (byte) 1) }
wave.AddLoop((int) bns.bnsInfo.LoopStart);
Wave wave = new Wave(bns.bnsInfo.ChannelCount, 16, bns.bnsInfo.SampleRate, samples);
if (bns.bnsInfo.HasLoop == 1)
{
wave.AddLoop((int)bns.bnsInfo.LoopStart);
}
return wave; return wave;
} }
@ -529,38 +618,43 @@ namespace libWiiSharp
private byte[] Read(Stream input) private byte[] Read(Stream input)
{ {
input.Seek(0L, SeekOrigin.Begin); input.Seek(0L, SeekOrigin.Begin);
this.bnsHeader.Read(input); bnsHeader.Read(input);
this.bnsInfo.Read(input); bnsInfo.Read(input);
this.bnsData.Read(input); bnsData.Read(input);
return this.Decode(); return Decode();
} }
private byte[] Decode() private byte[] Decode()
{ {
List<byte> byteList = new List<byte>(); List<byte> byteList = new List<byte>();
int num = this.bnsData.Data.Length / (this.bnsInfo.ChannelCount == (byte) 2 ? 16 : 8); int num = bnsData.Data.Length / (bnsInfo.ChannelCount == 2 ? 16 : 8);
int dataOffset1 = 0; int dataOffset1 = 0;
int dataOffset2 = num * 8; int dataOffset2 = num * 8;
byte[] numArray1 = new byte[0]; //byte[] numArray1 = new byte[0];
byte[] numArray2 = new byte[0]; byte[] numArray2 = new byte[0];
for (int index1 = 0; index1 < num; ++index1) for (int index1 = 0; index1 < num; ++index1)
{ {
byte[] numArray3 = this.DecodeAdpcm(0, dataOffset1); byte[] numArray3 = DecodeAdpcm(0, dataOffset1);
if (this.bnsInfo.ChannelCount == (byte) 2) if (bnsInfo.ChannelCount == 2)
numArray2 = this.DecodeAdpcm(1, dataOffset2); {
numArray2 = DecodeAdpcm(1, dataOffset2);
}
for (int index2 = 0; index2 < 14; ++index2) for (int index2 = 0; index2 < 14; ++index2)
{ {
byteList.Add(numArray3[index2 * 2]); byteList.Add(numArray3[index2 * 2]);
byteList.Add(numArray3[index2 * 2 + 1]); byteList.Add(numArray3[index2 * 2 + 1]);
if (this.bnsInfo.ChannelCount == (byte) 2) if (bnsInfo.ChannelCount == 2)
{ {
byteList.Add(numArray2[index2 * 2]); byteList.Add(numArray2[index2 * 2]);
byteList.Add(numArray2[index2 * 2 + 1]); byteList.Add(numArray2[index2 * 2 + 1]);
} }
} }
dataOffset1 += 8; dataOffset1 += 8;
if (this.bnsInfo.ChannelCount == (byte) 2) if (bnsInfo.ChannelCount == 2)
{
dataOffset2 += 8; dataOffset2 += 8;
}
} }
return byteList.ToArray(); return byteList.ToArray();
} }
@ -568,26 +662,29 @@ namespace libWiiSharp
private byte[] DecodeAdpcm(int channel, int dataOffset) private byte[] DecodeAdpcm(int channel, int dataOffset)
{ {
byte[] numArray = new byte[28]; byte[] numArray = new byte[28];
int num1 = (int) this.bnsData.Data[dataOffset] >> 4 & 15; int num1 = bnsData.Data[dataOffset] >> 4 & 15;
int num2 = 1 << ((int) this.bnsData.Data[dataOffset] & 15); int num2 = 1 << (bnsData.Data[dataOffset] & 15);
int num3 = this.pHist1[channel]; int num3 = pHist1[channel];
int num4 = this.pHist2[channel]; int num4 = pHist2[channel];
int num5 = channel == 0 ? this.bnsInfo.Coefficients1[num1 * 2] : this.bnsInfo.Coefficients2[num1 * 2]; int num5 = channel == 0 ? bnsInfo.Coefficients1[num1 * 2] : bnsInfo.Coefficients2[num1 * 2];
int num6 = channel == 0 ? this.bnsInfo.Coefficients1[num1 * 2 + 1] : this.bnsInfo.Coefficients2[num1 * 2 + 1]; int num6 = channel == 0 ? bnsInfo.Coefficients1[num1 * 2 + 1] : bnsInfo.Coefficients2[num1 * 2 + 1];
for (int index = 0; index < 14; ++index) for (int index = 0; index < 14; ++index)
{ {
short num7 = (short) this.bnsData.Data[dataOffset + (index / 2 + 1)]; short num7 = bnsData.Data[dataOffset + (index / 2 + 1)];
int num8 = (index & 1) != 0 ? (int) num7 & 15 : (int) num7 >> 4; int num8 = (index & 1) != 0 ? num7 & 15 : num7 >> 4;
if (num8 >= 8) if (num8 >= 8)
{
num8 -= 16; num8 -= 16;
int num9 = this.Clamp((num2 * num8 << 11) + (num5 * num3 + num6 * num4) + 1024 >> 11, (int) short.MinValue, (int) short.MaxValue); }
numArray[index * 2] = (byte) ((uint) (short) num9 & (uint) byte.MaxValue);
numArray[index * 2 + 1] = (byte) ((uint) (short) num9 >> 8); int num9 = Clamp((num2 * num8 << 11) + (num5 * num3 + num6 * num4) + 1024 >> 11, short.MinValue, short.MaxValue);
numArray[index * 2] = (byte)((uint)(short)num9 & byte.MaxValue);
numArray[index * 2 + 1] = (byte)((uint)(short)num9 >> 8);
num4 = num3; num4 = num3;
num3 = num9; num3 = num9;
} }
this.pHist1[channel] = num3; pHist1[channel] = num3;
this.pHist2[channel] = num4; pHist2[channel] = num4;
return numArray; return numArray;
} }
#endregion #endregion

View file

@ -23,41 +23,41 @@ namespace libWiiSharp
{ {
internal class BNS_Data internal class BNS_Data
{ {
private byte[] magic = new byte[4] private readonly byte[] magic = new byte[4]
{ {
(byte) 68, 68,
(byte) 65, 65,
(byte) 84, 84,
(byte) 65 65
}; };
private uint size = 315392; private uint size = 315392;
private byte[] data; private byte[] data;
public uint Size public uint Size
{ {
get => this.size; get => size;
set => this.size = value; set => size = value;
} }
public byte[] Data public byte[] Data
{ {
get => this.data; get => data;
set => this.data = value; set => data = value;
} }
public void Write(Stream outStream) public void Write(Stream outStream)
{ {
byte[] bytes = BitConverter.GetBytes(Shared.Swap(this.size)); byte[] bytes = BitConverter.GetBytes(Shared.Swap(size));
outStream.Write(this.magic, 0, this.magic.Length); outStream.Write(magic, 0, magic.Length);
outStream.Write(bytes, 0, bytes.Length); outStream.Write(bytes, 0, bytes.Length);
outStream.Write(this.data, 0, this.data.Length); outStream.Write(data, 0, data.Length);
} }
public void Read(Stream input) public void Read(Stream input)
{ {
BinaryReader binaryReader = new BinaryReader(input); BinaryReader binaryReader = new BinaryReader(input);
this.size = Shared.CompareByteArrays(this.magic, binaryReader.ReadBytes(4)) ? Shared.Swap(binaryReader.ReadUInt32()) : throw new Exception("This is not a valid BNS audfo file!"); size = Shared.CompareByteArrays(magic, binaryReader.ReadBytes(4)) ? Shared.Swap(binaryReader.ReadUInt32()) : throw new Exception("This is not a valid BNS audfo file!");
this.data = binaryReader.ReadBytes((int) this.size - 8); data = binaryReader.ReadBytes((int)size - 8);
} }
} }
} }

View file

@ -23,12 +23,12 @@ namespace libWiiSharp
{ {
internal class BNS_Header internal class BNS_Header
{ {
private byte[] magic = new byte[4] private readonly byte[] magic = new byte[4]
{ {
(byte) 66, 66,
(byte) 78, 78,
(byte) 83, 83,
(byte) 32 32
}; };
private uint flags = 4278124800; private uint flags = 4278124800;
private uint fileSize = 315584; private uint fileSize = 315584;
@ -41,80 +41,82 @@ namespace libWiiSharp
public uint DataOffset public uint DataOffset
{ {
get => this.dataOffset; get => dataOffset;
set => this.dataOffset = value; set => dataOffset = value;
} }
public uint InfoLength public uint InfoLength
{ {
get => this.infoLength; get => infoLength;
set => this.infoLength = value; set => infoLength = value;
} }
public ushort Size public ushort Size
{ {
get => this.size; get => size;
set => this.size = value; set => size = value;
} }
public uint DataLength public uint DataLength
{ {
get => this.dataLength; get => dataLength;
set => this.dataLength = value; set => dataLength = value;
} }
public uint FileSize public uint FileSize
{ {
get => this.fileSize; get => fileSize;
set => this.fileSize = value; set => fileSize = value;
} }
public void Write(Stream outStream) public void Write(Stream outStream)
{ {
outStream.Write(this.magic, 0, this.magic.Length); outStream.Write(magic, 0, magic.Length);
byte[] bytes1 = BitConverter.GetBytes(this.flags); byte[] bytes1 = BitConverter.GetBytes(flags);
Array.Reverse((Array) bytes1); Array.Reverse(bytes1);
outStream.Write(bytes1, 0, bytes1.Length); outStream.Write(bytes1, 0, bytes1.Length);
byte[] bytes2 = BitConverter.GetBytes(this.fileSize); byte[] bytes2 = BitConverter.GetBytes(fileSize);
Array.Reverse((Array) bytes2); Array.Reverse(bytes2);
outStream.Write(bytes2, 0, bytes2.Length); outStream.Write(bytes2, 0, bytes2.Length);
byte[] bytes3 = BitConverter.GetBytes(this.size); byte[] bytes3 = BitConverter.GetBytes(size);
Array.Reverse((Array) bytes3); Array.Reverse(bytes3);
outStream.Write(bytes3, 0, bytes3.Length); outStream.Write(bytes3, 0, bytes3.Length);
byte[] bytes4 = BitConverter.GetBytes(this.chunkCount); byte[] bytes4 = BitConverter.GetBytes(chunkCount);
Array.Reverse((Array) bytes4); Array.Reverse(bytes4);
outStream.Write(bytes4, 0, bytes4.Length); outStream.Write(bytes4, 0, bytes4.Length);
byte[] bytes5 = BitConverter.GetBytes(this.infoOffset); byte[] bytes5 = BitConverter.GetBytes(infoOffset);
Array.Reverse((Array) bytes5); Array.Reverse(bytes5);
outStream.Write(bytes5, 0, bytes5.Length); outStream.Write(bytes5, 0, bytes5.Length);
byte[] bytes6 = BitConverter.GetBytes(this.infoLength); byte[] bytes6 = BitConverter.GetBytes(infoLength);
Array.Reverse((Array) bytes6); Array.Reverse(bytes6);
outStream.Write(bytes6, 0, bytes6.Length); outStream.Write(bytes6, 0, bytes6.Length);
byte[] bytes7 = BitConverter.GetBytes(this.dataOffset); byte[] bytes7 = BitConverter.GetBytes(dataOffset);
Array.Reverse((Array) bytes7); Array.Reverse(bytes7);
outStream.Write(bytes7, 0, bytes7.Length); outStream.Write(bytes7, 0, bytes7.Length);
byte[] bytes8 = BitConverter.GetBytes(this.dataLength); byte[] bytes8 = BitConverter.GetBytes(dataLength);
Array.Reverse((Array) bytes8); Array.Reverse(bytes8);
outStream.Write(bytes8, 0, bytes8.Length); outStream.Write(bytes8, 0, bytes8.Length);
} }
public void Read(Stream input) public void Read(Stream input)
{ {
BinaryReader binaryReader = new BinaryReader(input); BinaryReader binaryReader = new BinaryReader(input);
if (!Shared.CompareByteArrays(this.magic, binaryReader.ReadBytes(4))) if (!Shared.CompareByteArrays(magic, binaryReader.ReadBytes(4)))
{ {
binaryReader.BaseStream.Seek(28L, SeekOrigin.Current); binaryReader.BaseStream.Seek(28L, SeekOrigin.Current);
if (!Shared.CompareByteArrays(this.magic, binaryReader.ReadBytes(4))) if (!Shared.CompareByteArrays(magic, binaryReader.ReadBytes(4)))
{
throw new Exception("This is not a valid BNS audio file!"); throw new Exception("This is not a valid BNS audio file!");
}
} }
this.flags = Shared.Swap(binaryReader.ReadUInt32()); flags = Shared.Swap(binaryReader.ReadUInt32());
this.fileSize = Shared.Swap(binaryReader.ReadUInt32()); fileSize = Shared.Swap(binaryReader.ReadUInt32());
this.size = Shared.Swap(binaryReader.ReadUInt16()); size = Shared.Swap(binaryReader.ReadUInt16());
this.chunkCount = Shared.Swap(binaryReader.ReadUInt16()); chunkCount = Shared.Swap(binaryReader.ReadUInt16());
this.infoOffset = Shared.Swap(binaryReader.ReadUInt32()); infoOffset = Shared.Swap(binaryReader.ReadUInt32());
this.infoLength = Shared.Swap(binaryReader.ReadUInt32()); infoLength = Shared.Swap(binaryReader.ReadUInt32());
this.dataOffset = Shared.Swap(binaryReader.ReadUInt32()); dataOffset = Shared.Swap(binaryReader.ReadUInt32());
this.dataLength = Shared.Swap(binaryReader.ReadUInt32()); dataLength = Shared.Swap(binaryReader.ReadUInt32());
} }
} }
} }

View file

@ -24,12 +24,12 @@ namespace libWiiSharp
internal class BNS_Info internal class BNS_Info
{ {
//Private Variables //Private Variables
private byte[] magic = new byte[4] private readonly byte[] magic = new byte[4]
{ {
(byte) 73, 73,
(byte) 78, 78,
(byte) 70, 70,
(byte) 79 79
}; };
private uint size = 160; private uint size = 160;
private byte codec; private byte codec;
@ -72,230 +72,233 @@ namespace libWiiSharp
//Public Variables //Public Variables
public byte HasLoop public byte HasLoop
{ {
get => this.hasLoop; get => hasLoop;
set => this.hasLoop = value; set => hasLoop = value;
} }
public uint Coefficients1Offset public uint Coefficients1Offset
{ {
get => this.coefficients1Offset; get => coefficients1Offset;
set => this.coefficients1Offset = value; set => coefficients1Offset = value;
} }
public uint Channel1StartOffset public uint Channel1StartOffset
{ {
get => this.channel1StartOffset; get => channel1StartOffset;
set => this.channel1StartOffset = value; set => channel1StartOffset = value;
} }
public uint Channel2StartOffset public uint Channel2StartOffset
{ {
get => this.channel2StartOffset; get => channel2StartOffset;
set => this.channel2StartOffset = value; set => channel2StartOffset = value;
} }
public uint Size public uint Size
{ {
get => this.size; get => size;
set => this.size = value; set => size = value;
} }
public ushort SampleRate public ushort SampleRate
{ {
get => this.sampleRate; get => sampleRate;
set => this.sampleRate = value; set => sampleRate = value;
} }
public byte ChannelCount public byte ChannelCount
{ {
get => this.channelCount; get => channelCount;
set => this.channelCount = value; set => channelCount = value;
} }
public uint Channel1Start public uint Channel1Start
{ {
get => this.channel1Start; get => channel1Start;
set => this.channel1Start = value; set => channel1Start = value;
} }
public uint Channel2Start public uint Channel2Start
{ {
get => this.channel2Start; get => channel2Start;
set => this.channel2Start = value; set => channel2Start = value;
} }
public uint LoopStart public uint LoopStart
{ {
get => this.loopStart; get => loopStart;
set => this.loopStart = value; set => loopStart = value;
} }
public uint LoopEnd public uint LoopEnd
{ {
get => this.loopEnd; get => loopEnd;
set => this.loopEnd = value; set => loopEnd = value;
} }
public int[] Coefficients1 public int[] Coefficients1
{ {
get => this.coefficients1; get => coefficients1;
set => this.coefficients1 = value; set => coefficients1 = value;
} }
public int[] Coefficients2 public int[] Coefficients2
{ {
get => this.coefficients2; get => coefficients2;
set => this.coefficients2 = value; set => coefficients2 = value;
} }
public void Write(Stream outStream) public void Write(Stream outStream)
{ {
outStream.Write(this.magic, 0, this.magic.Length); outStream.Write(magic, 0, magic.Length);
byte[] bytes1 = BitConverter.GetBytes(this.size); byte[] bytes1 = BitConverter.GetBytes(size);
Array.Reverse((Array) bytes1); Array.Reverse(bytes1);
outStream.Write(bytes1, 0, bytes1.Length); outStream.Write(bytes1, 0, bytes1.Length);
outStream.WriteByte(this.codec); outStream.WriteByte(codec);
outStream.WriteByte(this.hasLoop); outStream.WriteByte(hasLoop);
outStream.WriteByte(this.channelCount); outStream.WriteByte(channelCount);
outStream.WriteByte(this.zero); outStream.WriteByte(zero);
byte[] bytes2 = BitConverter.GetBytes(this.sampleRate); byte[] bytes2 = BitConverter.GetBytes(sampleRate);
Array.Reverse((Array) bytes2); Array.Reverse(bytes2);
outStream.Write(bytes2, 0, bytes2.Length); outStream.Write(bytes2, 0, bytes2.Length);
byte[] bytes3 = BitConverter.GetBytes(this.pad0); byte[] bytes3 = BitConverter.GetBytes(pad0);
Array.Reverse((Array) bytes3); Array.Reverse(bytes3);
outStream.Write(bytes3, 0, bytes3.Length); outStream.Write(bytes3, 0, bytes3.Length);
byte[] bytes4 = BitConverter.GetBytes(this.loopStart); byte[] bytes4 = BitConverter.GetBytes(loopStart);
Array.Reverse((Array) bytes4); Array.Reverse(bytes4);
outStream.Write(bytes4, 0, bytes4.Length); outStream.Write(bytes4, 0, bytes4.Length);
byte[] bytes5 = BitConverter.GetBytes(this.loopEnd); byte[] bytes5 = BitConverter.GetBytes(loopEnd);
Array.Reverse((Array) bytes5); Array.Reverse(bytes5);
outStream.Write(bytes5, 0, bytes5.Length); outStream.Write(bytes5, 0, bytes5.Length);
byte[] bytes6 = BitConverter.GetBytes(this.offsetToChannelStart); byte[] bytes6 = BitConverter.GetBytes(offsetToChannelStart);
Array.Reverse((Array) bytes6); Array.Reverse(bytes6);
outStream.Write(bytes6, 0, bytes6.Length); outStream.Write(bytes6, 0, bytes6.Length);
byte[] bytes7 = BitConverter.GetBytes(this.pad1); byte[] bytes7 = BitConverter.GetBytes(pad1);
Array.Reverse((Array) bytes7); Array.Reverse(bytes7);
outStream.Write(bytes7, 0, bytes7.Length); outStream.Write(bytes7, 0, bytes7.Length);
byte[] bytes8 = BitConverter.GetBytes(this.channel1StartOffset); byte[] bytes8 = BitConverter.GetBytes(channel1StartOffset);
Array.Reverse((Array) bytes8); Array.Reverse(bytes8);
outStream.Write(bytes8, 0, bytes8.Length); outStream.Write(bytes8, 0, bytes8.Length);
byte[] bytes9 = BitConverter.GetBytes(this.channel2StartOffset); byte[] bytes9 = BitConverter.GetBytes(channel2StartOffset);
Array.Reverse((Array) bytes9); Array.Reverse(bytes9);
outStream.Write(bytes9, 0, bytes9.Length); outStream.Write(bytes9, 0, bytes9.Length);
byte[] bytes10 = BitConverter.GetBytes(this.channel1Start); byte[] bytes10 = BitConverter.GetBytes(channel1Start);
Array.Reverse((Array) bytes10); Array.Reverse(bytes10);
outStream.Write(bytes10, 0, bytes10.Length); outStream.Write(bytes10, 0, bytes10.Length);
byte[] bytes11 = BitConverter.GetBytes(this.coefficients1Offset); byte[] bytes11 = BitConverter.GetBytes(coefficients1Offset);
Array.Reverse((Array) bytes11); Array.Reverse(bytes11);
outStream.Write(bytes11, 0, bytes11.Length); outStream.Write(bytes11, 0, bytes11.Length);
if (this.channelCount == (byte) 2) if (channelCount == 2)
{ {
byte[] bytes12 = BitConverter.GetBytes(this.pad2); byte[] bytes12 = BitConverter.GetBytes(pad2);
Array.Reverse((Array) bytes12); Array.Reverse(bytes12);
outStream.Write(bytes12, 0, bytes12.Length); outStream.Write(bytes12, 0, bytes12.Length);
byte[] bytes13 = BitConverter.GetBytes(this.channel2Start); byte[] bytes13 = BitConverter.GetBytes(channel2Start);
Array.Reverse((Array) bytes13); Array.Reverse(bytes13);
outStream.Write(bytes13, 0, bytes13.Length); outStream.Write(bytes13, 0, bytes13.Length);
byte[] bytes14 = BitConverter.GetBytes(this.coefficients2Offset); byte[] bytes14 = BitConverter.GetBytes(coefficients2Offset);
Array.Reverse((Array) bytes14); Array.Reverse(bytes14);
outStream.Write(bytes14, 0, bytes14.Length); outStream.Write(bytes14, 0, bytes14.Length);
byte[] bytes15 = BitConverter.GetBytes(this.pad3); byte[] bytes15 = BitConverter.GetBytes(pad3);
Array.Reverse((Array) bytes15); Array.Reverse(bytes15);
outStream.Write(bytes15, 0, bytes15.Length); outStream.Write(bytes15, 0, bytes15.Length);
foreach (int num in this.coefficients1) foreach (int num in coefficients1)
{ {
byte[] bytes16 = BitConverter.GetBytes(num); byte[] bytes16 = BitConverter.GetBytes(num);
Array.Reverse((Array) bytes16); Array.Reverse(bytes16);
outStream.Write(bytes16, 2, bytes16.Length - 2); outStream.Write(bytes16, 2, bytes16.Length - 2);
} }
byte[] bytes17 = BitConverter.GetBytes(this.channel1Gain); byte[] bytes17 = BitConverter.GetBytes(channel1Gain);
Array.Reverse((Array) bytes17); Array.Reverse(bytes17);
outStream.Write(bytes17, 0, bytes17.Length); outStream.Write(bytes17, 0, bytes17.Length);
byte[] bytes18 = BitConverter.GetBytes(this.channel1PredictiveScale); byte[] bytes18 = BitConverter.GetBytes(channel1PredictiveScale);
Array.Reverse((Array) bytes18); Array.Reverse(bytes18);
outStream.Write(bytes18, 0, bytes18.Length); outStream.Write(bytes18, 0, bytes18.Length);
byte[] bytes19 = BitConverter.GetBytes(this.channel1PreviousValue); byte[] bytes19 = BitConverter.GetBytes(channel1PreviousValue);
Array.Reverse((Array) bytes19); Array.Reverse(bytes19);
outStream.Write(bytes19, 0, bytes19.Length); outStream.Write(bytes19, 0, bytes19.Length);
byte[] bytes20 = BitConverter.GetBytes(this.channel1NextPreviousValue); byte[] bytes20 = BitConverter.GetBytes(channel1NextPreviousValue);
Array.Reverse((Array) bytes20); Array.Reverse(bytes20);
outStream.Write(bytes20, 0, bytes20.Length); outStream.Write(bytes20, 0, bytes20.Length);
byte[] bytes21 = BitConverter.GetBytes(this.channel1LoopPredictiveScale); byte[] bytes21 = BitConverter.GetBytes(channel1LoopPredictiveScale);
Array.Reverse((Array) bytes21); Array.Reverse(bytes21);
outStream.Write(bytes21, 0, bytes21.Length); outStream.Write(bytes21, 0, bytes21.Length);
byte[] bytes22 = BitConverter.GetBytes(this.channel1LoopPreviousValue); byte[] bytes22 = BitConverter.GetBytes(channel1LoopPreviousValue);
Array.Reverse((Array) bytes22); Array.Reverse(bytes22);
outStream.Write(bytes22, 0, bytes22.Length); outStream.Write(bytes22, 0, bytes22.Length);
byte[] bytes23 = BitConverter.GetBytes(this.channel1LoopNextPreviousValue); byte[] bytes23 = BitConverter.GetBytes(channel1LoopNextPreviousValue);
Array.Reverse((Array) bytes23); Array.Reverse(bytes23);
outStream.Write(bytes23, 0, bytes23.Length); outStream.Write(bytes23, 0, bytes23.Length);
byte[] bytes24 = BitConverter.GetBytes(this.channel1LoopPadding); byte[] bytes24 = BitConverter.GetBytes(channel1LoopPadding);
Array.Reverse((Array) bytes24); Array.Reverse(bytes24);
outStream.Write(bytes24, 0, bytes24.Length); outStream.Write(bytes24, 0, bytes24.Length);
foreach (int num in this.coefficients2) foreach (int num in coefficients2)
{ {
byte[] bytes16 = BitConverter.GetBytes(num); byte[] bytes16 = BitConverter.GetBytes(num);
Array.Reverse((Array) bytes16); Array.Reverse(bytes16);
outStream.Write(bytes16, 2, bytes16.Length - 2); outStream.Write(bytes16, 2, bytes16.Length - 2);
} }
byte[] bytes25 = BitConverter.GetBytes(this.channel2Gain); byte[] bytes25 = BitConverter.GetBytes(channel2Gain);
Array.Reverse((Array) bytes25); Array.Reverse(bytes25);
outStream.Write(bytes25, 0, bytes25.Length); outStream.Write(bytes25, 0, bytes25.Length);
byte[] bytes26 = BitConverter.GetBytes(this.channel2PredictiveScale); byte[] bytes26 = BitConverter.GetBytes(channel2PredictiveScale);
Array.Reverse((Array) bytes26); Array.Reverse(bytes26);
outStream.Write(bytes26, 0, bytes26.Length); outStream.Write(bytes26, 0, bytes26.Length);
byte[] bytes27 = BitConverter.GetBytes(this.channel2PreviousValue); byte[] bytes27 = BitConverter.GetBytes(channel2PreviousValue);
Array.Reverse((Array) bytes27); Array.Reverse(bytes27);
outStream.Write(bytes27, 0, bytes27.Length); outStream.Write(bytes27, 0, bytes27.Length);
byte[] bytes28 = BitConverter.GetBytes(this.channel2NextPreviousValue); byte[] bytes28 = BitConverter.GetBytes(channel2NextPreviousValue);
Array.Reverse((Array) bytes28); Array.Reverse(bytes28);
outStream.Write(bytes28, 0, bytes28.Length); outStream.Write(bytes28, 0, bytes28.Length);
byte[] bytes29 = BitConverter.GetBytes(this.channel2LoopPredictiveScale); byte[] bytes29 = BitConverter.GetBytes(channel2LoopPredictiveScale);
Array.Reverse((Array) bytes29); Array.Reverse(bytes29);
outStream.Write(bytes29, 0, bytes29.Length); outStream.Write(bytes29, 0, bytes29.Length);
byte[] bytes30 = BitConverter.GetBytes(this.channel2LoopPreviousValue); byte[] bytes30 = BitConverter.GetBytes(channel2LoopPreviousValue);
Array.Reverse((Array) bytes30); Array.Reverse(bytes30);
outStream.Write(bytes30, 0, bytes30.Length); outStream.Write(bytes30, 0, bytes30.Length);
byte[] bytes31 = BitConverter.GetBytes(this.channel2LoopNextPreviousValue); byte[] bytes31 = BitConverter.GetBytes(channel2LoopNextPreviousValue);
Array.Reverse((Array) bytes31); Array.Reverse(bytes31);
outStream.Write(bytes31, 0, bytes31.Length); outStream.Write(bytes31, 0, bytes31.Length);
byte[] bytes32 = BitConverter.GetBytes(this.channel2LoopPadding); byte[] bytes32 = BitConverter.GetBytes(channel2LoopPadding);
Array.Reverse((Array) bytes32); Array.Reverse(bytes32);
outStream.Write(bytes32, 0, bytes32.Length); outStream.Write(bytes32, 0, bytes32.Length);
} }
else else
{ {
if (this.channelCount != (byte) 1) if (channelCount != 1)
{
return; return;
foreach (int num in this.coefficients1) }
foreach (int num in coefficients1)
{ {
byte[] bytes12 = BitConverter.GetBytes(num); byte[] bytes12 = BitConverter.GetBytes(num);
Array.Reverse((Array) bytes12); Array.Reverse(bytes12);
outStream.Write(bytes12, 2, bytes12.Length - 2); outStream.Write(bytes12, 2, bytes12.Length - 2);
} }
byte[] bytes13 = BitConverter.GetBytes(this.channel1Gain); byte[] bytes13 = BitConverter.GetBytes(channel1Gain);
Array.Reverse((Array) bytes13); Array.Reverse(bytes13);
outStream.Write(bytes13, 0, bytes13.Length); outStream.Write(bytes13, 0, bytes13.Length);
byte[] bytes14 = BitConverter.GetBytes(this.channel1PredictiveScale); byte[] bytes14 = BitConverter.GetBytes(channel1PredictiveScale);
Array.Reverse((Array) bytes14); Array.Reverse(bytes14);
outStream.Write(bytes14, 0, bytes14.Length); outStream.Write(bytes14, 0, bytes14.Length);
byte[] bytes15 = BitConverter.GetBytes(this.channel1PreviousValue); byte[] bytes15 = BitConverter.GetBytes(channel1PreviousValue);
Array.Reverse((Array) bytes15); Array.Reverse(bytes15);
outStream.Write(bytes15, 0, bytes15.Length); outStream.Write(bytes15, 0, bytes15.Length);
byte[] bytes16 = BitConverter.GetBytes(this.channel1NextPreviousValue); byte[] bytes16 = BitConverter.GetBytes(channel1NextPreviousValue);
Array.Reverse((Array) bytes16); Array.Reverse(bytes16);
outStream.Write(bytes16, 0, bytes16.Length); outStream.Write(bytes16, 0, bytes16.Length);
byte[] bytes17 = BitConverter.GetBytes(this.channel1LoopPredictiveScale); byte[] bytes17 = BitConverter.GetBytes(channel1LoopPredictiveScale);
Array.Reverse((Array) bytes17); Array.Reverse(bytes17);
outStream.Write(bytes17, 0, bytes17.Length); outStream.Write(bytes17, 0, bytes17.Length);
byte[] bytes18 = BitConverter.GetBytes(this.channel1LoopPreviousValue); byte[] bytes18 = BitConverter.GetBytes(channel1LoopPreviousValue);
Array.Reverse((Array) bytes18); Array.Reverse(bytes18);
outStream.Write(bytes18, 0, bytes18.Length); outStream.Write(bytes18, 0, bytes18.Length);
byte[] bytes19 = BitConverter.GetBytes(this.channel1LoopNextPreviousValue); byte[] bytes19 = BitConverter.GetBytes(channel1LoopNextPreviousValue);
Array.Reverse((Array) bytes19); Array.Reverse(bytes19);
outStream.Write(bytes19, 0, bytes19.Length); outStream.Write(bytes19, 0, bytes19.Length);
byte[] bytes20 = BitConverter.GetBytes(this.channel1LoopPadding); byte[] bytes20 = BitConverter.GetBytes(channel1LoopPadding);
Array.Reverse((Array) bytes20); Array.Reverse(bytes20);
outStream.Write(bytes20, 0, bytes20.Length); outStream.Write(bytes20, 0, bytes20.Length);
} }
} }
@ -303,62 +306,74 @@ namespace libWiiSharp
public void Read(Stream input) public void Read(Stream input)
{ {
BinaryReader binaryReader = new BinaryReader(input); BinaryReader binaryReader = new BinaryReader(input);
this.size = Shared.CompareByteArrays(this.magic, binaryReader.ReadBytes(4)) ? Shared.Swap(binaryReader.ReadUInt32()) : throw new Exception("This is not a valid BNS audfo file!"); size = Shared.CompareByteArrays(magic, binaryReader.ReadBytes(4)) ? Shared.Swap(binaryReader.ReadUInt32()) : throw new Exception("This is not a valid BNS audfo file!");
this.codec = binaryReader.ReadByte(); codec = binaryReader.ReadByte();
this.hasLoop = binaryReader.ReadByte(); hasLoop = binaryReader.ReadByte();
this.channelCount = binaryReader.ReadByte(); channelCount = binaryReader.ReadByte();
this.zero = binaryReader.ReadByte(); zero = binaryReader.ReadByte();
this.sampleRate = Shared.Swap(binaryReader.ReadUInt16()); sampleRate = Shared.Swap(binaryReader.ReadUInt16());
this.pad0 = Shared.Swap(binaryReader.ReadUInt16()); pad0 = Shared.Swap(binaryReader.ReadUInt16());
this.loopStart = Shared.Swap(binaryReader.ReadUInt32()); loopStart = Shared.Swap(binaryReader.ReadUInt32());
this.loopEnd = Shared.Swap(binaryReader.ReadUInt32()); loopEnd = Shared.Swap(binaryReader.ReadUInt32());
this.offsetToChannelStart = Shared.Swap(binaryReader.ReadUInt32()); offsetToChannelStart = Shared.Swap(binaryReader.ReadUInt32());
this.pad1 = Shared.Swap(binaryReader.ReadUInt32()); pad1 = Shared.Swap(binaryReader.ReadUInt32());
this.channel1StartOffset = Shared.Swap(binaryReader.ReadUInt32()); channel1StartOffset = Shared.Swap(binaryReader.ReadUInt32());
this.channel2StartOffset = Shared.Swap(binaryReader.ReadUInt32()); channel2StartOffset = Shared.Swap(binaryReader.ReadUInt32());
this.channel1Start = Shared.Swap(binaryReader.ReadUInt32()); channel1Start = Shared.Swap(binaryReader.ReadUInt32());
this.coefficients1Offset = Shared.Swap(binaryReader.ReadUInt32()); coefficients1Offset = Shared.Swap(binaryReader.ReadUInt32());
if (this.channelCount == (byte) 2) if (channelCount == 2)
{ {
this.pad2 = Shared.Swap(binaryReader.ReadUInt32()); pad2 = Shared.Swap(binaryReader.ReadUInt32());
this.channel2Start = Shared.Swap(binaryReader.ReadUInt32()); channel2Start = Shared.Swap(binaryReader.ReadUInt32());
this.coefficients2Offset = Shared.Swap(binaryReader.ReadUInt32()); coefficients2Offset = Shared.Swap(binaryReader.ReadUInt32());
this.pad3 = Shared.Swap(binaryReader.ReadUInt32()); pad3 = Shared.Swap(binaryReader.ReadUInt32());
for (int index = 0; index < 16; ++index) for (int index = 0; index < 16; ++index)
this.coefficients1[index] = (int) (short) Shared.Swap(binaryReader.ReadUInt16()); {
this.channel1Gain = Shared.Swap(binaryReader.ReadUInt16()); coefficients1[index] = (short)Shared.Swap(binaryReader.ReadUInt16());
this.channel1PredictiveScale = Shared.Swap(binaryReader.ReadUInt16()); }
this.channel1PreviousValue = Shared.Swap(binaryReader.ReadUInt16());
this.channel1NextPreviousValue = Shared.Swap(binaryReader.ReadUInt16()); channel1Gain = Shared.Swap(binaryReader.ReadUInt16());
this.channel1LoopPredictiveScale = Shared.Swap(binaryReader.ReadUInt16()); channel1PredictiveScale = Shared.Swap(binaryReader.ReadUInt16());
this.channel1LoopPreviousValue = Shared.Swap(binaryReader.ReadUInt16()); channel1PreviousValue = Shared.Swap(binaryReader.ReadUInt16());
this.channel1LoopNextPreviousValue = Shared.Swap(binaryReader.ReadUInt16()); channel1NextPreviousValue = Shared.Swap(binaryReader.ReadUInt16());
this.channel1LoopPadding = Shared.Swap(binaryReader.ReadUInt16()); channel1LoopPredictiveScale = Shared.Swap(binaryReader.ReadUInt16());
channel1LoopPreviousValue = Shared.Swap(binaryReader.ReadUInt16());
channel1LoopNextPreviousValue = Shared.Swap(binaryReader.ReadUInt16());
channel1LoopPadding = Shared.Swap(binaryReader.ReadUInt16());
for (int index = 0; index < 16; ++index) for (int index = 0; index < 16; ++index)
this.coefficients2[index] = (int) (short) Shared.Swap(binaryReader.ReadUInt16()); {
this.channel2Gain = Shared.Swap(binaryReader.ReadUInt16()); coefficients2[index] = (short)Shared.Swap(binaryReader.ReadUInt16());
this.channel2PredictiveScale = Shared.Swap(binaryReader.ReadUInt16()); }
this.channel2PreviousValue = Shared.Swap(binaryReader.ReadUInt16());
this.channel2NextPreviousValue = Shared.Swap(binaryReader.ReadUInt16()); channel2Gain = Shared.Swap(binaryReader.ReadUInt16());
this.channel2LoopPredictiveScale = Shared.Swap(binaryReader.ReadUInt16()); channel2PredictiveScale = Shared.Swap(binaryReader.ReadUInt16());
this.channel2LoopPreviousValue = Shared.Swap(binaryReader.ReadUInt16()); channel2PreviousValue = Shared.Swap(binaryReader.ReadUInt16());
this.channel2LoopNextPreviousValue = Shared.Swap(binaryReader.ReadUInt16()); channel2NextPreviousValue = Shared.Swap(binaryReader.ReadUInt16());
this.channel2LoopPadding = Shared.Swap(binaryReader.ReadUInt16()); channel2LoopPredictiveScale = Shared.Swap(binaryReader.ReadUInt16());
channel2LoopPreviousValue = Shared.Swap(binaryReader.ReadUInt16());
channel2LoopNextPreviousValue = Shared.Swap(binaryReader.ReadUInt16());
channel2LoopPadding = Shared.Swap(binaryReader.ReadUInt16());
} }
else else
{ {
if (this.channelCount != (byte) 1) if (channelCount != 1)
{
return; return;
}
for (int index = 0; index < 16; ++index) for (int index = 0; index < 16; ++index)
this.coefficients1[index] = (int) (short) Shared.Swap(binaryReader.ReadUInt16()); {
this.channel1Gain = Shared.Swap(binaryReader.ReadUInt16()); coefficients1[index] = (short)Shared.Swap(binaryReader.ReadUInt16());
this.channel1PredictiveScale = Shared.Swap(binaryReader.ReadUInt16()); }
this.channel1PreviousValue = Shared.Swap(binaryReader.ReadUInt16());
this.channel1NextPreviousValue = Shared.Swap(binaryReader.ReadUInt16()); channel1Gain = Shared.Swap(binaryReader.ReadUInt16());
this.channel1LoopPredictiveScale = Shared.Swap(binaryReader.ReadUInt16()); channel1PredictiveScale = Shared.Swap(binaryReader.ReadUInt16());
this.channel1LoopPreviousValue = Shared.Swap(binaryReader.ReadUInt16()); channel1PreviousValue = Shared.Swap(binaryReader.ReadUInt16());
this.channel1LoopNextPreviousValue = Shared.Swap(binaryReader.ReadUInt16()); channel1NextPreviousValue = Shared.Swap(binaryReader.ReadUInt16());
this.channel1LoopPadding = Shared.Swap(binaryReader.ReadUInt16()); channel1LoopPredictiveScale = Shared.Swap(binaryReader.ReadUInt16());
channel1LoopPreviousValue = Shared.Swap(binaryReader.ReadUInt16());
channel1LoopNextPreviousValue = Shared.Swap(binaryReader.ReadUInt16());
channel1LoopPadding = Shared.Swap(binaryReader.ReadUInt16());
} }
} }
} }

View file

@ -24,55 +24,77 @@ namespace libWiiSharp
{ {
public class Brlan public class Brlan
{ {
public static string[] GetBrlanTpls(string pathTobrlan) => Brlan.getBrlanTpls(File.ReadAllBytes(pathTobrlan)); public static string[] GetBrlanTpls(string pathTobrlan)
{
return Brlan.PrivGetBrlanTpls(File.ReadAllBytes(pathTobrlan));
}
public static string[] GetBrlanTpls(byte[] brlanFile) => Brlan.getBrlanTpls(brlanFile); public static string[] GetBrlanTpls(byte[] brlanFile)
{
return Brlan.PrivGetBrlanTpls(brlanFile);
}
public static string[] GetBrlanTpls(WAD wad, bool banner) public static string[] GetBrlanTpls(WAD wad, bool banner)
{ {
if (!wad.HasBanner) if (!wad.HasBanner)
{
return new string[0]; return new string[0];
string str = nameof (banner); }
string str = nameof(banner);
if (!banner) if (!banner)
{
str = "icon"; str = "icon";
}
for (int index1 = 0; index1 < wad.BannerApp.Nodes.Count; ++index1) for (int index1 = 0; index1 < wad.BannerApp.Nodes.Count; ++index1)
{ {
if (wad.BannerApp.StringTable[index1].ToLower() == str + ".bin") if (wad.BannerApp.StringTable[index1].ToLower() == str + ".bin")
{ {
U8 u8 = U8.Load(wad.BannerApp.Data[index1]); U8 u8 = U8.Load(wad.BannerApp.Data[index1]);
string[] a = new string[0]; string[] a = new string[0];
for (int index2 = 0; index2 < u8.Nodes.Count; ++index2) for (int index2 = 0; index2 < u8.Nodes.Count; ++index2)
{ {
if (u8.StringTable[index2].ToLower() == str + "_start.brlan" || u8.StringTable[index2].ToLower() == str + "_loop.brlan" || u8.StringTable[index2].ToLower() == str + ".brlan") if (u8.StringTable[index2].ToLower() == str + "_start.brlan" || u8.StringTable[index2].ToLower() == str + "_loop.brlan" || u8.StringTable[index2].ToLower() == str + ".brlan")
a = Shared.MergeStringArrays(a, Brlan.getBrlanTpls(u8.Data[index2])); {
} a = Shared.MergeStringArrays(a, Brlan.GetBrlanTpls(u8.Data[index2]));
return a; }
}
return a;
} }
} }
return new string[0]; return new string[0];
} }
private static string[] getBrlanTpls(byte[] brlanFile) private static string[] PrivGetBrlanTpls(byte[] brlanFile)
{ {
List<string> stringList = new List<string>(); List<string> stringList = new List<string>();
int numOfTpls = Brlan.getNumOfTpls(brlanFile); int numOfTpls = Brlan.GetNumOfTpls(brlanFile);
int index1 = 36 + numOfTpls * 4; int index1 = 36 + numOfTpls * 4;
for (int index2 = 0; index2 < numOfTpls; ++index2) for (int index2 = 0; index2 < numOfTpls; ++index2)
{ {
string empty = string.Empty; string empty = string.Empty;
while (brlanFile[index1] != (byte) 0) while (brlanFile[index1] != 0)
{
empty += Convert.ToChar(brlanFile[index1++]).ToString(); empty += Convert.ToChar(brlanFile[index1++]).ToString();
}
stringList.Add(empty); stringList.Add(empty);
++index1; ++index1;
} }
for (int index2 = stringList.Count - 1; index2 >= 0; --index2) for (int index2 = stringList.Count - 1; index2 >= 0; --index2)
{ {
if (!stringList[index2].ToLower().EndsWith(".tpl")) if (!stringList[index2].ToLower().EndsWith(".tpl"))
{
stringList.RemoveAt(index2); stringList.RemoveAt(index2);
}
} }
return stringList.ToArray(); return stringList.ToArray();
} }
private static int getNumOfTpls(byte[] brlanFile) => (int) Shared.Swap(BitConverter.ToUInt16(brlanFile, 28)); private static int GetNumOfTpls(byte[] brlanFile)
{
return Shared.Swap(BitConverter.ToUInt16(brlanFile, 28));
}
} }
} }

View file

@ -24,17 +24,29 @@ namespace libWiiSharp
{ {
public class Brlyt public class Brlyt
{ {
public static string[] GetBrlytTpls(string pathToBrlyt) => Brlyt.getBrlytTpls(File.ReadAllBytes(pathToBrlyt)); public static string[] GetBrlytTpls(string pathToBrlyt)
{
return PrivGetBrlytTpls(File.ReadAllBytes(pathToBrlyt));
}
public static string[] GetBrlytTpls(byte[] brlytFile) => Brlyt.getBrlytTpls(brlytFile); public static string[] GetBrlytTpls(byte[] brlytFile)
{
return PrivGetBrlytTpls(brlytFile);
}
public static string[] GetBrlytTpls(WAD wad, bool banner) public static string[] GetBrlytTpls(WAD wad, bool banner)
{ {
if (!wad.HasBanner) if (!wad.HasBanner)
{
return new string[0]; return new string[0];
string str = nameof (banner); }
string str = nameof(banner);
if (!banner) if (!banner)
{
str = "icon"; str = "icon";
}
for (int index1 = 0; index1 < wad.BannerApp.Nodes.Count; ++index1) for (int index1 = 0; index1 < wad.BannerApp.Nodes.Count; ++index1)
{ {
if (wad.BannerApp.StringTable[index1].ToLower() == str + ".bin") if (wad.BannerApp.StringTable[index1].ToLower() == str + ".bin")
@ -44,7 +56,9 @@ namespace libWiiSharp
for (int index2 = 0; index2 < u8.Nodes.Count; ++index2) for (int index2 = 0; index2 < u8.Nodes.Count; ++index2)
{ {
if (u8.StringTable[index2].ToLower() == str + ".brlyt") if (u8.StringTable[index2].ToLower() == str + ".brlyt")
a = Shared.MergeStringArrays(a, Brlyt.getBrlytTpls(u8.Data[index2])); {
a = Shared.MergeStringArrays(a, Brlyt.GetBrlytTpls(u8.Data[index2]));
}
} }
return a; return a;
} }
@ -52,27 +66,35 @@ namespace libWiiSharp
return new string[0]; return new string[0];
} }
private static string[] getBrlytTpls(byte[] brlytFile) private static string[] PrivGetBrlytTpls(byte[] brlytFile)
{ {
List<string> stringList = new List<string>(); List<string> stringList = new List<string>();
int numOfTpls = Brlyt.getNumOfTpls(brlytFile); int numOfTpls = Brlyt.GetNumOfTpls(brlytFile);
int index1 = 48 + numOfTpls * 8; int index1 = 48 + numOfTpls * 8;
for (int index2 = 0; index2 < numOfTpls; ++index2) for (int index2 = 0; index2 < numOfTpls; ++index2)
{ {
string empty = string.Empty; string empty = string.Empty;
while (brlytFile[index1] != (byte) 0) while (brlytFile[index1] != 0)
{
empty += Convert.ToChar(brlytFile[index1++]).ToString(); empty += Convert.ToChar(brlytFile[index1++]).ToString();
}
stringList.Add(empty); stringList.Add(empty);
++index1; ++index1;
} }
for (int index2 = stringList.Count - 1; index2 >= 0; --index2) for (int index2 = stringList.Count - 1; index2 >= 0; --index2)
{ {
if (!stringList[index2].ToLower().EndsWith(".tpl")) if (!stringList[index2].ToLower().EndsWith(".tpl"))
{
stringList.RemoveAt(index2); stringList.RemoveAt(index2);
}
} }
return stringList.ToArray(); return stringList.ToArray();
} }
private static int getNumOfTpls(byte[] brlytFile) => (int) Shared.Swap(BitConverter.ToUInt16(brlytFile, 44)); private static int GetNumOfTpls(byte[] brlytFile)
{
return Shared.Swap(BitConverter.ToUInt16(brlytFile, 44));
}
} }
} }

View file

@ -24,9 +24,9 @@ namespace libWiiSharp
{ {
public class CertificateChain : IDisposable public class CertificateChain : IDisposable
{ {
private const string certCaHash = "5B7D3EE28706AD8DA2CBD5A6B75C15D0F9B6F318"; //private const string certCaHash = "5B7D3EE28706AD8DA2CBD5A6B75C15D0F9B6F318";
private const string certCpHash = "6824D6DA4C25184F0D6DAF6EDB9C0FC57522A41C"; //private const string certCpHash = "6824D6DA4C25184F0D6DAF6EDB9C0FC57522A41C";
private const string certXsHash = "09787045037121477824BC6A3E5E076156573F8A"; //private const string certXsHash = "09787045037121477824BC6A3E5E076156573F8A";
private SHA1 sha = SHA1.Create(); private SHA1 sha = SHA1.Create();
private bool[] certsComplete = new bool[3]; private bool[] certsComplete = new bool[3];
private byte[] certCa = new byte[1024]; private byte[] certCa = new byte[1024];
@ -34,33 +34,36 @@ namespace libWiiSharp
private byte[] certXs = new byte[768]; private byte[] certXs = new byte[768];
private bool isDisposed; private bool isDisposed;
public bool CertsComplete => this.certsComplete[0] && this.certsComplete[1] && this.certsComplete[2]; public bool CertsComplete => certsComplete[0] && certsComplete[1] && certsComplete[2];
public event EventHandler<MessageEventArgs> Debug; public event EventHandler<MessageEventArgs> Debug;
~CertificateChain() => this.Dispose(false); ~CertificateChain() => Dispose(false);
public void Dispose() public void Dispose()
{ {
this.Dispose(true); Dispose(true);
GC.SuppressFinalize((object) this); GC.SuppressFinalize(this);
} }
protected virtual void Dispose(bool disposing) protected virtual void Dispose(bool disposing)
{ {
if (disposing && !this.isDisposed) if (disposing && !isDisposed)
{ {
this.sha.Clear(); sha.Clear();
this.sha = (SHA1) null; sha = null;
this.certsComplete = (bool[]) null; certsComplete = null;
this.certCa = (byte[]) null; certCa = null;
this.certCp = (byte[]) null; certCp = null;
this.certXs = (byte[]) null; certXs = null;
} }
this.isDisposed = true; isDisposed = true;
} }
public static CertificateChain Load(string pathToCert) => CertificateChain.Load(File.ReadAllBytes(pathToCert)); public static CertificateChain Load(string pathToCert)
{
return CertificateChain.Load(File.ReadAllBytes(pathToCert));
}
public static CertificateChain Load(byte[] certFile) public static CertificateChain Load(byte[] certFile)
{ {
@ -68,7 +71,7 @@ namespace libWiiSharp
MemoryStream memoryStream = new MemoryStream(certFile); MemoryStream memoryStream = new MemoryStream(certFile);
try try
{ {
certificateChain.parseCert((Stream) memoryStream); certificateChain.ParseCert(memoryStream);
} }
catch catch
{ {
@ -82,11 +85,14 @@ namespace libWiiSharp
public static CertificateChain Load(Stream cert) public static CertificateChain Load(Stream cert)
{ {
CertificateChain certificateChain = new CertificateChain(); CertificateChain certificateChain = new CertificateChain();
certificateChain.parseCert(cert); certificateChain.ParseCert(cert);
return certificateChain; return certificateChain;
} }
public static CertificateChain FromTikTmd(string pathToTik, string pathToTmd) => CertificateChain.FromTikTmd(File.ReadAllBytes(pathToTik), File.ReadAllBytes(pathToTmd)); public static CertificateChain FromTikTmd(string pathToTik, string pathToTmd)
{
return CertificateChain.FromTikTmd(File.ReadAllBytes(pathToTik), File.ReadAllBytes(pathToTmd));
}
public static CertificateChain FromTikTmd(byte[] tikFile, byte[] tmdFile) public static CertificateChain FromTikTmd(byte[] tikFile, byte[] tmdFile)
{ {
@ -94,7 +100,7 @@ namespace libWiiSharp
MemoryStream memoryStream1 = new MemoryStream(tikFile); MemoryStream memoryStream1 = new MemoryStream(tikFile);
try try
{ {
certificateChain.grabFromTik((Stream) memoryStream1); certificateChain.GrabFromTik(memoryStream1);
} }
catch catch
{ {
@ -104,7 +110,7 @@ namespace libWiiSharp
MemoryStream memoryStream2 = new MemoryStream(tmdFile); MemoryStream memoryStream2 = new MemoryStream(tmdFile);
try try
{ {
certificateChain.grabFromTmd((Stream) memoryStream2); certificateChain.GrabFromTmd(memoryStream2);
} }
catch catch
{ {
@ -118,19 +124,22 @@ namespace libWiiSharp
public static CertificateChain FromTikTmd(Stream tik, Stream tmd) public static CertificateChain FromTikTmd(Stream tik, Stream tmd)
{ {
CertificateChain certificateChain = new CertificateChain(); CertificateChain certificateChain = new CertificateChain();
certificateChain.grabFromTik(tik); certificateChain.GrabFromTik(tik);
certificateChain.grabFromTmd(tmd); certificateChain.GrabFromTmd(tmd);
return certificateChain; return certificateChain;
} }
public void LoadFile(string pathToCert) => this.LoadFile(File.ReadAllBytes(pathToCert)); public void LoadFile(string pathToCert)
{
LoadFile(File.ReadAllBytes(pathToCert));
}
public void LoadFile(byte[] certFile) public void LoadFile(byte[] certFile)
{ {
MemoryStream memoryStream = new MemoryStream(certFile); MemoryStream memoryStream = new MemoryStream(certFile);
try try
{ {
this.parseCert((Stream) memoryStream); ParseCert(memoryStream);
} }
catch catch
{ {
@ -140,16 +149,22 @@ namespace libWiiSharp
memoryStream.Dispose(); memoryStream.Dispose();
} }
public void LoadFile(Stream cert) => this.parseCert(cert); public void LoadFile(Stream cert)
{
ParseCert(cert);
}
public void LoadFromTikTmd(string pathToTik, string pathToTmd) => this.LoadFromTikTmd(File.ReadAllBytes(pathToTik), File.ReadAllBytes(pathToTmd)); public void LoadFromTikTmd(string pathToTik, string pathToTmd)
{
LoadFromTikTmd(File.ReadAllBytes(pathToTik), File.ReadAllBytes(pathToTmd));
}
public void LoadFromTikTmd(byte[] tikFile, byte[] tmdFile) public void LoadFromTikTmd(byte[] tikFile, byte[] tmdFile)
{ {
MemoryStream memoryStream1 = new MemoryStream(tikFile); MemoryStream memoryStream1 = new MemoryStream(tikFile);
try try
{ {
this.grabFromTik((Stream) memoryStream1); GrabFromTik(memoryStream1);
} }
catch catch
{ {
@ -159,7 +174,7 @@ namespace libWiiSharp
MemoryStream memoryStream2 = new MemoryStream(tmdFile); MemoryStream memoryStream2 = new MemoryStream(tmdFile);
try try
{ {
this.grabFromTmd((Stream) memoryStream2); GrabFromTmd(memoryStream2);
} }
catch catch
{ {
@ -167,22 +182,27 @@ namespace libWiiSharp
throw; throw;
} }
memoryStream2.Dispose(); memoryStream2.Dispose();
if (!this.CertsComplete) if (!CertsComplete)
{
throw new Exception("Couldn't locate all certs!"); throw new Exception("Couldn't locate all certs!");
}
} }
public void LoadFromTikTmd(Stream tik, Stream tmd) public void LoadFromTikTmd(Stream tik, Stream tmd)
{ {
this.grabFromTik(tik); GrabFromTik(tik);
this.grabFromTmd(tmd); GrabFromTmd(tmd);
} }
public void Save(string savePath) public void Save(string savePath)
{ {
if (File.Exists(savePath)) if (File.Exists(savePath))
{
File.Delete(savePath); File.Delete(savePath);
using (FileStream fileStream = new FileStream(savePath, FileMode.Create)) }
this.writeToStream((Stream) fileStream);
using FileStream fileStream = new FileStream(savePath, FileMode.Create);
WriteToStream(fileStream);
} }
public MemoryStream ToMemoryStream() public MemoryStream ToMemoryStream()
@ -190,7 +210,7 @@ namespace libWiiSharp
MemoryStream memoryStream = new MemoryStream(); MemoryStream memoryStream = new MemoryStream();
try try
{ {
this.writeToStream((Stream) memoryStream); WriteToStream(memoryStream);
return memoryStream; return memoryStream;
} }
catch catch
@ -205,7 +225,7 @@ namespace libWiiSharp
MemoryStream memoryStream = new MemoryStream(); MemoryStream memoryStream = new MemoryStream();
try try
{ {
this.writeToStream((Stream) memoryStream); WriteToStream(memoryStream);
} }
catch catch
{ {
@ -217,73 +237,73 @@ namespace libWiiSharp
return array; return array;
} }
private void writeToStream(Stream writeStream) private void WriteToStream(Stream writeStream)
{ {
this.fireDebug("Writing Certificate Chain..."); FireDebug("Writing Certificate Chain...");
if (!this.CertsComplete) if (!CertsComplete)
{ {
this.fireDebug(" Certificate Chain incomplete..."); FireDebug(" Certificate Chain incomplete...");
throw new Exception("At least one certificate is missing!"); throw new Exception("At least one certificate is missing!");
} }
writeStream.Seek(0L, SeekOrigin.Begin); writeStream.Seek(0L, SeekOrigin.Begin);
object[] objArray1 = new object[1]; object[] objArray1 = new object[1];
long position = writeStream.Position; long position = writeStream.Position;
objArray1[0] = (object) position.ToString("x8"); objArray1[0] = position.ToString("x8");
this.fireDebug(" Writing Certificate CA... (Offset: 0x{0})", objArray1); FireDebug(" Writing Certificate CA... (Offset: 0x{0})", objArray1);
writeStream.Write(this.certCa, 0, this.certCa.Length); writeStream.Write(certCa, 0, certCa.Length);
object[] objArray2 = new object[1]; object[] objArray2 = new object[1];
position = writeStream.Position; position = writeStream.Position;
objArray2[0] = (object) position.ToString("x8"); objArray2[0] = position.ToString("x8");
this.fireDebug(" Writing Certificate CP... (Offset: 0x{0})", objArray2); FireDebug(" Writing Certificate CP... (Offset: 0x{0})", objArray2);
writeStream.Write(this.certCp, 0, this.certCp.Length); writeStream.Write(certCp, 0, certCp.Length);
object[] objArray3 = new object[1]; object[] objArray3 = new object[1];
position = writeStream.Position; position = writeStream.Position;
objArray3[0] = (object) position.ToString("x8"); objArray3[0] = position.ToString("x8");
this.fireDebug(" Writing Certificate XS... (Offset: 0x{0})", objArray3); FireDebug(" Writing Certificate XS... (Offset: 0x{0})", objArray3);
writeStream.Write(this.certXs, 0, this.certXs.Length); writeStream.Write(certXs, 0, certXs.Length);
this.fireDebug("Writing Certificate Chain Finished..."); FireDebug("Writing Certificate Chain Finished...");
} }
private void parseCert(Stream certFile) private void ParseCert(Stream certFile)
{ {
this.fireDebug("Parsing Certificate Chain..."); FireDebug("Parsing Certificate Chain...");
int num = 0; int num = 0;
for (int index = 0; index < 3; ++index) for (int index = 0; index < 3; ++index)
{ {
this.fireDebug(" Scanning at Offset 0x{0}:", (object) num.ToString("x8")); FireDebug(" Scanning at Offset 0x{0}:", (object)num.ToString("x8"));
try try
{ {
certFile.Seek((long) num, SeekOrigin.Begin); certFile.Seek(num, SeekOrigin.Begin);
byte[] array = new byte[1024]; byte[] array = new byte[1024];
certFile.Read(array, 0, array.Length); certFile.Read(array, 0, array.Length);
this.fireDebug(" Checking for Certificate CA..."); FireDebug(" Checking for Certificate CA...");
if (this.isCertCa(array) && !this.certsComplete[1]) if (IsCertCa(array) && !certsComplete[1])
{ {
this.fireDebug(" Certificate CA detected..."); FireDebug(" Certificate CA detected...");
this.certCa = array; certCa = array;
this.certsComplete[1] = true; certsComplete[1] = true;
num += 1024; num += 1024;
continue; continue;
} }
this.fireDebug(" Checking for Certificate CP..."); FireDebug(" Checking for Certificate CP...");
if (this.isCertCp(array) && !this.certsComplete[2]) if (IsCertCp(array) && !certsComplete[2])
{ {
this.fireDebug(" Certificate CP detected..."); FireDebug(" Certificate CP detected...");
Array.Resize<byte>(ref array, 768); Array.Resize<byte>(ref array, 768);
this.certCp = array; certCp = array;
this.certsComplete[2] = true; certsComplete[2] = true;
num += 768; num += 768;
continue; continue;
} }
this.fireDebug(" Checking for Certificate XS..."); FireDebug(" Checking for Certificate XS...");
if (this.isCertXs(array)) if (IsCertXs(array))
{ {
if (!this.certsComplete[0]) if (!certsComplete[0])
{ {
this.fireDebug(" Certificate XS detected..."); FireDebug(" Certificate XS detected...");
Array.Resize<byte>(ref array, 768); Array.Resize<byte>(ref array, 768);
this.certXs = array; certXs = array;
this.certsComplete[0] = true; certsComplete[0] = true;
num += 768; num += 768;
continue; continue;
} }
@ -291,58 +311,58 @@ namespace libWiiSharp
} }
catch (Exception ex) catch (Exception ex)
{ {
this.fireDebug("Error: {0}", (object) ex.Message); FireDebug("Error: {0}", (object)ex.Message);
} }
num += 768; num += 768;
} }
if (!this.CertsComplete) if (!CertsComplete)
{ {
this.fireDebug(" Couldn't locate all Certificates..."); FireDebug(" Couldn't locate all Certificates...");
throw new Exception("Couldn't locate all certs!"); throw new Exception("Couldn't locate all certs!");
} }
this.fireDebug("Parsing Certificate Chain Finished..."); FireDebug("Parsing Certificate Chain Finished...");
} }
private void grabFromTik(Stream tik) private void GrabFromTik(Stream tik)
{ {
this.fireDebug("Scanning Ticket for Certificates..."); FireDebug("Scanning Ticket for Certificates...");
int num = 676; int num = 676;
for (int index = 0; index < 3; ++index) for (int index = 0; index < 3; ++index)
{ {
this.fireDebug(" Scanning at Offset 0x{0}:", (object) num.ToString("x8")); FireDebug(" Scanning at Offset 0x{0}:", (object)num.ToString("x8"));
try try
{ {
tik.Seek((long) num, SeekOrigin.Begin); tik.Seek(num, SeekOrigin.Begin);
byte[] array = new byte[1024]; byte[] array = new byte[1024];
tik.Read(array, 0, array.Length); tik.Read(array, 0, array.Length);
this.fireDebug(" Checking for Certificate CA..."); FireDebug(" Checking for Certificate CA...");
if (this.isCertCa(array) && !this.certsComplete[1]) if (IsCertCa(array) && !certsComplete[1])
{ {
this.fireDebug(" Certificate CA detected..."); FireDebug(" Certificate CA detected...");
this.certCa = array; certCa = array;
this.certsComplete[1] = true; certsComplete[1] = true;
num += 1024; num += 1024;
continue; continue;
} }
this.fireDebug(" Checking for Certificate CP..."); FireDebug(" Checking for Certificate CP...");
if (this.isCertCp(array) && !this.certsComplete[2]) if (IsCertCp(array) && !certsComplete[2])
{ {
this.fireDebug(" Certificate CP detected..."); FireDebug(" Certificate CP detected...");
Array.Resize<byte>(ref array, 768); Array.Resize<byte>(ref array, 768);
this.certCp = array; certCp = array;
this.certsComplete[2] = true; certsComplete[2] = true;
num += 768; num += 768;
continue; continue;
} }
this.fireDebug(" Checking for Certificate XS..."); FireDebug(" Checking for Certificate XS...");
if (this.isCertXs(array)) if (IsCertXs(array))
{ {
if (!this.certsComplete[0]) if (!certsComplete[0])
{ {
this.fireDebug(" Certificate XS detected..."); FireDebug(" Certificate XS detected...");
Array.Resize<byte>(ref array, 768); Array.Resize<byte>(ref array, 768);
this.certXs = array; certXs = array;
this.certsComplete[0] = true; certsComplete[0] = true;
num += 768; num += 768;
continue; continue;
} }
@ -353,52 +373,52 @@ namespace libWiiSharp
} }
num += 768; num += 768;
} }
this.fireDebug("Scanning Ticket for Certificates Finished..."); FireDebug("Scanning Ticket for Certificates Finished...");
} }
private void grabFromTmd(Stream tmd) private void GrabFromTmd(Stream tmd)
{ {
this.fireDebug("Scanning TMD for Certificates..."); FireDebug("Scanning TMD for Certificates...");
byte[] buffer = new byte[2]; byte[] buffer = new byte[2];
tmd.Seek(478L, SeekOrigin.Begin); tmd.Seek(478L, SeekOrigin.Begin);
tmd.Read(buffer, 0, 2); tmd.Read(buffer, 0, 2);
int num = 484 + (int) Shared.Swap(BitConverter.ToUInt16(buffer, 0)) * 36; int num = 484 + Shared.Swap(BitConverter.ToUInt16(buffer, 0)) * 36;
for (int index = 0; index < 3; ++index) for (int index = 0; index < 3; ++index)
{ {
this.fireDebug(" Scanning at Offset 0x{0}:", (object) num.ToString("x8")); FireDebug(" Scanning at Offset 0x{0}:", (object)num.ToString("x8"));
try try
{ {
tmd.Seek((long) num, SeekOrigin.Begin); tmd.Seek(num, SeekOrigin.Begin);
byte[] array = new byte[1024]; byte[] array = new byte[1024];
tmd.Read(array, 0, array.Length); tmd.Read(array, 0, array.Length);
this.fireDebug(" Checking for Certificate CA..."); FireDebug(" Checking for Certificate CA...");
if (this.isCertCa(array) && !this.certsComplete[1]) if (IsCertCa(array) && !certsComplete[1])
{ {
this.fireDebug(" Certificate CA detected..."); FireDebug(" Certificate CA detected...");
this.certCa = array; certCa = array;
this.certsComplete[1] = true; certsComplete[1] = true;
num += 1024; num += 1024;
continue; continue;
} }
this.fireDebug(" Checking for Certificate CP..."); FireDebug(" Checking for Certificate CP...");
if (this.isCertCp(array) && !this.certsComplete[2]) if (IsCertCp(array) && !certsComplete[2])
{ {
this.fireDebug(" Certificate CP detected..."); FireDebug(" Certificate CP detected...");
Array.Resize<byte>(ref array, 768); Array.Resize<byte>(ref array, 768);
this.certCp = array; certCp = array;
this.certsComplete[2] = true; certsComplete[2] = true;
num += 768; num += 768;
continue; continue;
} }
this.fireDebug(" Checking for Certificate XS..."); FireDebug(" Checking for Certificate XS...");
if (this.isCertXs(array)) if (IsCertXs(array))
{ {
if (!this.certsComplete[0]) if (!certsComplete[0])
{ {
this.fireDebug(" Certificate XS detected..."); FireDebug(" Certificate XS detected...");
Array.Resize<byte>(ref array, 768); Array.Resize<byte>(ref array, 768);
this.certXs = array; certXs = array;
this.certsComplete[0] = true; certsComplete[0] = true;
num += 768; num += 768;
continue; continue;
} }
@ -409,41 +429,62 @@ namespace libWiiSharp
} }
num += 768; num += 768;
} }
this.fireDebug("Scanning TMD for Certificates Finished..."); FireDebug("Scanning TMD for Certificates Finished...");
} }
private bool isCertXs(byte[] part) private bool IsCertXs(byte[] part)
{ {
if (part.Length < 768) if (part.Length < 768)
{
return false; return false;
}
if (part.Length > 768) if (part.Length > 768)
{
Array.Resize<byte>(ref part, 768); Array.Resize<byte>(ref part, 768);
return part[388] == (byte) 88 && part[389] == (byte) 83 && Shared.CompareByteArrays(this.sha.ComputeHash(part), Shared.HexStringToByteArray("09787045037121477824BC6A3E5E076156573F8A")); }
return part[388] == 88 && part[389] == 83 && Shared.CompareByteArrays(sha.ComputeHash(part), Shared.HexStringToByteArray("09787045037121477824BC6A3E5E076156573F8A"));
} }
private bool isCertCa(byte[] part) private bool IsCertCa(byte[] part)
{ {
if (part.Length < 1024) if (part.Length < 1024)
{
return false; return false;
}
if (part.Length > 1024) if (part.Length > 1024)
{
Array.Resize<byte>(ref part, 1024); Array.Resize<byte>(ref part, 1024);
return part[644] == (byte) 67 && part[645] == (byte) 65 && Shared.CompareByteArrays(this.sha.ComputeHash(part), Shared.HexStringToByteArray("5B7D3EE28706AD8DA2CBD5A6B75C15D0F9B6F318")); }
return part[644] == 67 && part[645] == 65 && Shared.CompareByteArrays(sha.ComputeHash(part), Shared.HexStringToByteArray("5B7D3EE28706AD8DA2CBD5A6B75C15D0F9B6F318"));
} }
private bool isCertCp(byte[] part) private bool IsCertCp(byte[] part)
{ {
if (part.Length < 768) if (part.Length < 768)
{
return false; return false;
}
if (part.Length > 768) if (part.Length > 768)
{
Array.Resize<byte>(ref part, 768); Array.Resize<byte>(ref part, 768);
return part[388] == (byte) 67 && part[389] == (byte) 80 && Shared.CompareByteArrays(this.sha.ComputeHash(part), Shared.HexStringToByteArray("6824D6DA4C25184F0D6DAF6EDB9C0FC57522A41C")); }
return part[388] == 67 && part[389] == 80 && Shared.CompareByteArrays(sha.ComputeHash(part), Shared.HexStringToByteArray("6824D6DA4C25184F0D6DAF6EDB9C0FC57522A41C"));
} }
private void fireDebug(string debugMessage, params object[] args) private void FireDebug(string debugMessage, params object[] args)
{ {
EventHandler<MessageEventArgs> debug = this.Debug; EventHandler<MessageEventArgs> debug = Debug;
if (debug == null) if (debug == null)
{
return; return;
}
debug(new object(), new MessageEventArgs(string.Format(debugMessage, args))); debug(new object(), new MessageEventArgs(string.Format(debugMessage, args)));
} }
} }

View file

@ -25,16 +25,16 @@ namespace libWiiSharp
{ {
private uint[] rgbaPalette; private uint[] rgbaPalette;
private byte[] tplPalette; private byte[] tplPalette;
private uint[] rgbaData; private readonly uint[] rgbaData;
private byte[] tplData; private byte[] tplData;
private TPL_TextureFormat tplFormat; private readonly TPL_TextureFormat tplFormat;
private TPL_PaletteFormat paletteFormat; private readonly TPL_PaletteFormat paletteFormat;
private int width; private readonly int width;
private int height; private readonly int height;
public byte[] Palette => this.tplPalette; public byte[] Palette => tplPalette;
public byte[] Data => this.tplData; public byte[] Data => tplData;
public ColorIndexConverter( public ColorIndexConverter(
uint[] rgbaData, uint[] rgbaData,
@ -44,118 +44,135 @@ namespace libWiiSharp
TPL_PaletteFormat paletteFormat) TPL_PaletteFormat paletteFormat)
{ {
if (tplFormat != TPL_TextureFormat.CI4 && tplFormat != TPL_TextureFormat.CI8) if (tplFormat != TPL_TextureFormat.CI4 && tplFormat != TPL_TextureFormat.CI8)
{
throw new Exception("Texture format must be either CI4 or CI8"); throw new Exception("Texture format must be either CI4 or CI8");
}
if (paletteFormat != TPL_PaletteFormat.IA8 && paletteFormat != TPL_PaletteFormat.RGB565 && paletteFormat != TPL_PaletteFormat.RGB5A3) if (paletteFormat != TPL_PaletteFormat.IA8 && paletteFormat != TPL_PaletteFormat.RGB565 && paletteFormat != TPL_PaletteFormat.RGB5A3)
{
throw new Exception("Palette format must be either IA8, RGB565 or RGB5A3!"); throw new Exception("Palette format must be either IA8, RGB565 or RGB5A3!");
}
this.rgbaData = rgbaData; this.rgbaData = rgbaData;
this.width = width; this.width = width;
this.height = height; this.height = height;
this.tplFormat = tplFormat; this.tplFormat = tplFormat;
this.paletteFormat = paletteFormat; this.paletteFormat = paletteFormat;
this.buildPalette(); BuildPalette();
if (tplFormat != TPL_TextureFormat.CI4) if (tplFormat != TPL_TextureFormat.CI4)
{ {
if (tplFormat == TPL_TextureFormat.CI8) if (tplFormat == TPL_TextureFormat.CI8)
this.toCI8(); {
ToCI8();
}
else else
this.toCI14X2(); {
ToCI14X2();
}
} }
else else
this.toCI4(); {
ToCI4();
}
} }
private void toCI4() private void ToCI4()
{ {
byte[] numArray = new byte[Shared.AddPadding(this.width, 8) * Shared.AddPadding(this.height, 8) / 2]; byte[] numArray = new byte[Shared.AddPadding(width, 8) * Shared.AddPadding(height, 8) / 2];
int num = 0; int num = 0;
for (int index1 = 0; index1 < this.height; index1 += 8) for (int index1 = 0; index1 < height; index1 += 8)
{ {
for (int index2 = 0; index2 < this.width; index2 += 8) for (int index2 = 0; index2 < width; index2 += 8)
{ {
for (int index3 = index1; index3 < index1 + 8; ++index3) for (int index3 = index1; index3 < index1 + 8; ++index3)
{ {
for (int index4 = index2; index4 < index2 + 8; index4 += 2) for (int index4 = index2; index4 < index2 + 8; index4 += 2)
{ {
uint colorIndex1 = this.getColorIndex(index3 >= this.height || index4 >= this.width ? 0U : this.rgbaData[index3 * this.width + index4]); uint colorIndex1 = GetColorIndex(index3 >= height || index4 >= width ? 0U : rgbaData[index3 * width + index4]);
uint colorIndex2 = this.getColorIndex(index3 >= this.height || index4 >= this.width ? 0U : (index3 * this.width + index4 + 1 < this.rgbaData.Length ? this.rgbaData[index3 * this.width + index4 + 1] : 0U)); uint colorIndex2 = GetColorIndex(index3 >= height || index4 >= width ? 0U : (index3 * width + index4 + 1 < rgbaData.Length ? rgbaData[index3 * width + index4 + 1] : 0U));
numArray[num++] = (byte) ((uint) (byte) colorIndex1 << 4 | (uint) (byte) colorIndex2); numArray[num++] = (byte)((uint)(byte)colorIndex1 << 4 | (byte)colorIndex2);
} }
} }
} }
} }
this.tplData = numArray; tplData = numArray;
} }
private void toCI8() private void ToCI8()
{ {
byte[] numArray = new byte[Shared.AddPadding(this.width, 8) * Shared.AddPadding(this.height, 4)]; byte[] numArray = new byte[Shared.AddPadding(width, 8) * Shared.AddPadding(height, 4)];
int num1 = 0; int num1 = 0;
for (int index1 = 0; index1 < this.height; index1 += 4) for (int index1 = 0; index1 < height; index1 += 4)
{ {
for (int index2 = 0; index2 < this.width; index2 += 8) for (int index2 = 0; index2 < width; index2 += 8)
{ {
for (int index3 = index1; index3 < index1 + 4; ++index3) for (int index3 = index1; index3 < index1 + 4; ++index3)
{ {
for (int index4 = index2; index4 < index2 + 8; ++index4) for (int index4 = index2; index4 < index2 + 8; ++index4)
{ {
uint num2 = index3 >= this.height || index4 >= this.width ? 0U : this.rgbaData[index3 * this.width + index4]; uint num2 = index3 >= height || index4 >= width ? 0U : rgbaData[index3 * width + index4];
numArray[num1++] = (byte) this.getColorIndex(num2); numArray[num1++] = (byte)GetColorIndex(num2);
} }
} }
} }
} }
this.tplData = numArray; tplData = numArray;
} }
private void toCI14X2() private void ToCI14X2()
{ {
byte[] numArray1 = new byte[Shared.AddPadding(this.width, 4) * Shared.AddPadding(this.height, 4) * 2]; byte[] numArray1 = new byte[Shared.AddPadding(width, 4) * Shared.AddPadding(height, 4) * 2];
int num1 = 0; int num1 = 0;
for (int index1 = 0; index1 < this.height; index1 += 4) for (int index1 = 0; index1 < height; index1 += 4)
{ {
for (int index2 = 0; index2 < this.width; index2 += 4) for (int index2 = 0; index2 < width; index2 += 4)
{ {
for (int index3 = index1; index3 < index1 + 4; ++index3) for (int index3 = index1; index3 < index1 + 4; ++index3)
{ {
for (int index4 = index2; index4 < index2 + 4; ++index4) for (int index4 = index2; index4 < index2 + 4; ++index4)
{ {
byte[] bytes = BitConverter.GetBytes((ushort) this.getColorIndex(index3 >= this.height || index4 >= this.width ? 0U : this.rgbaData[index3 * this.width + index4])); byte[] bytes = BitConverter.GetBytes((ushort)GetColorIndex(index3 >= height || index4 >= width ? 0U : rgbaData[index3 * width + index4]));
byte[] numArray2 = numArray1; byte[] numArray2 = numArray1;
int index5 = num1; int index5 = num1;
int num2 = index5 + 1; int num2 = index5 + 1;
int num3 = (int) bytes[1]; int num3 = bytes[1];
numArray2[index5] = (byte) num3; numArray2[index5] = (byte)num3;
byte[] numArray3 = numArray1; byte[] numArray3 = numArray1;
int index6 = num2; int index6 = num2;
num1 = index6 + 1; num1 = index6 + 1;
int num4 = (int) bytes[0]; int num4 = bytes[0];
numArray3[index6] = (byte) num4; numArray3[index6] = (byte)num4;
} }
} }
} }
} }
this.tplData = numArray1; tplData = numArray1;
} }
private void buildPalette() private void BuildPalette()
{ {
int num1 = 256; int num1 = 256;
if (this.tplFormat == TPL_TextureFormat.CI4) if (tplFormat == TPL_TextureFormat.CI4)
{
num1 = 16; num1 = 16;
else if (this.tplFormat == TPL_TextureFormat.CI14X2) }
else if (tplFormat == TPL_TextureFormat.CI14X2)
{
num1 = 16384; num1 = 16384;
}
List<uint> uintList = new List<uint>(); List<uint> uintList = new List<uint>();
List<ushort> ushortList = new List<ushort>(); List<ushort> ushortList = new List<ushort>();
uintList.Add(0U); uintList.Add(0U);
ushortList.Add((ushort) 0); ushortList.Add(0);
for (int index = 1; index < this.rgbaData.Length && uintList.Count != num1; ++index) for (int index = 1; index < rgbaData.Length && uintList.Count != num1; ++index)
{ {
if ((long) (this.rgbaData[index] >> 24 & (uint) byte.MaxValue) >= (this.tplFormat == TPL_TextureFormat.CI14X2 ? 1L : 25L)) if ((rgbaData[index] >> 24 & byte.MaxValue) >= (tplFormat == TPL_TextureFormat.CI14X2 ? 1L : 25L))
{ {
ushort num2 = Shared.Swap(this.convertToPaletteValue((int) this.rgbaData[index])); ushort num2 = Shared.Swap(ConvertToPaletteValue((int)rgbaData[index]));
if (!uintList.Contains(this.rgbaData[index]) && !ushortList.Contains(num2)) if (!uintList.Contains(rgbaData[index]) && !ushortList.Contains(num2))
{ {
uintList.Add(this.rgbaData[index]); uintList.Add(rgbaData[index]);
ushortList.Add(num2); ushortList.Add(num2);
} }
} }
@ -165,127 +182,133 @@ namespace libWiiSharp
uintList.Add(uint.MaxValue); uintList.Add(uint.MaxValue);
ushortList.Add(ushort.MaxValue); ushortList.Add(ushort.MaxValue);
} }
this.tplPalette = Shared.UShortArrayToByteArray(ushortList.ToArray()); tplPalette = Shared.UShortArrayToByteArray(ushortList.ToArray());
this.rgbaPalette = uintList.ToArray(); rgbaPalette = uintList.ToArray();
} }
private ushort convertToPaletteValue(int rgba) private ushort ConvertToPaletteValue(int rgba)
{ {
int num1 = 0; int num1 = 0;
int num2; int num2;
if (this.paletteFormat == TPL_PaletteFormat.IA8) if (paletteFormat == TPL_PaletteFormat.IA8)
{ {
int num3 = ((rgba & (int) byte.MaxValue) + (rgba >> 8 & (int) byte.MaxValue) + (rgba >> 16 & (int) byte.MaxValue)) / 3 & (int) byte.MaxValue; int num3 = ((rgba & byte.MaxValue) + (rgba >> 8 & byte.MaxValue) + (rgba >> 16 & byte.MaxValue)) / 3 & byte.MaxValue;
num2 = (int) (ushort) ((rgba >> 24 & (int) byte.MaxValue) << 8 | num3); num2 = (ushort)((rgba >> 24 & byte.MaxValue) << 8 | num3);
} }
else if (this.paletteFormat == TPL_PaletteFormat.RGB565) else if (paletteFormat == TPL_PaletteFormat.RGB565)
{ {
num2 = (int) (ushort) ((rgba >> 16 & (int) byte.MaxValue) >> 3 << 11 | (rgba >> 8 & (int) byte.MaxValue) >> 2 << 5 | (rgba & (int) byte.MaxValue) >> 3); num2 = (ushort)((rgba >> 16 & byte.MaxValue) >> 3 << 11 | (rgba >> 8 & byte.MaxValue) >> 2 << 5 | (rgba & byte.MaxValue) >> 3);
} }
else else
{ {
int num3 = rgba >> 16 & (int) byte.MaxValue; int num3 = rgba >> 16 & byte.MaxValue;
int num4 = rgba >> 8 & (int) byte.MaxValue; int num4 = rgba >> 8 & byte.MaxValue;
int num5 = rgba & (int) byte.MaxValue; int num5 = rgba & byte.MaxValue;
int num6 = rgba >> 24 & (int) byte.MaxValue; int num6 = rgba >> 24 & byte.MaxValue;
if (num6 <= 218) if (num6 <= 218)
{ {
int num7 = num1 & -32769; int num7 = num1 & -32769;
int num8 = num3 * 15 / (int) byte.MaxValue & 15; int num8 = num3 * 15 / byte.MaxValue & 15;
int num9 = num4 * 15 / (int) byte.MaxValue & 15; int num9 = num4 * 15 / byte.MaxValue & 15;
int num10 = num5 * 15 / (int) byte.MaxValue & 15; int num10 = num5 * 15 / byte.MaxValue & 15;
int num11 = num6 * 7 / (int) byte.MaxValue & 7; int num11 = num6 * 7 / byte.MaxValue & 7;
num2 = num7 | num11 << 12 | num10 | num9 << 4 | num8 << 8; num2 = num7 | num11 << 12 | num10 | num9 << 4 | num8 << 8;
} }
else else
{ {
int num7 = num1 | 32768; int num7 = num1 | 32768;
int num8 = num3 * 31 / (int) byte.MaxValue & 31; int num8 = num3 * 31 / byte.MaxValue & 31;
int num9 = num4 * 31 / (int) byte.MaxValue & 31; int num9 = num4 * 31 / byte.MaxValue & 31;
int num10 = num5 * 31 / (int) byte.MaxValue & 31; int num10 = num5 * 31 / byte.MaxValue & 31;
num2 = num7 | num10 | num9 << 5 | num8 << 10; num2 = num7 | num10 | num9 << 5 | num8 << 10;
} }
} }
return (ushort) num2; return (ushort)num2;
} }
private uint getColorIndex(uint value) private uint GetColorIndex(uint value)
{ {
uint num1 = (uint) int.MaxValue; uint num1 = int.MaxValue;
uint num2 = 0; uint num2 = 0;
if ((long) (value >> 24 & (uint) byte.MaxValue) < (this.tplFormat == TPL_TextureFormat.CI14X2 ? 1L : 25L)) if ((value >> 24 & byte.MaxValue) < (tplFormat == TPL_TextureFormat.CI14X2 ? 1L : 25L))
return 0;
ushort paletteValue1 = this.convertToPaletteValue((int) value);
for (int index = 0; index < this.rgbaPalette.Length; ++index)
{ {
ushort paletteValue2 = this.convertToPaletteValue((int) this.rgbaPalette[index]); return 0;
if ((int) paletteValue1 == (int) paletteValue2) }
return (uint) index;
uint distance = this.getDistance(paletteValue1, paletteValue2); ushort paletteValue1 = ConvertToPaletteValue((int)value);
for (int index = 0; index < rgbaPalette.Length; ++index)
{
ushort paletteValue2 = ConvertToPaletteValue((int)rgbaPalette[index]);
if (paletteValue1 == paletteValue2)
{
return (uint)index;
}
uint distance = GetDistance(paletteValue1, paletteValue2);
if (distance < num1) if (distance < num1)
{ {
num1 = distance; num1 = distance;
num2 = (uint) index; num2 = (uint)index;
} }
} }
return num2; return num2;
} }
private uint getDistance(ushort color, ushort paletteColor) private uint GetDistance(ushort color, ushort paletteColor)
{ {
int rgbaValue1 = (int) this.convertToRgbaValue(color); int rgbaValue1 = (int)ConvertToRgbaValue(color);
uint rgbaValue2 = this.convertToRgbaValue(paletteColor); uint rgbaValue2 = ConvertToRgbaValue(paletteColor);
uint val1_1 = (uint) rgbaValue1 >> 24 & (uint) byte.MaxValue; uint val1_1 = (uint)rgbaValue1 >> 24 & byte.MaxValue;
uint val1_2 = (uint) rgbaValue1 >> 16 & (uint) byte.MaxValue; uint val1_2 = (uint)rgbaValue1 >> 16 & byte.MaxValue;
uint val1_3 = (uint) rgbaValue1 >> 8 & (uint) byte.MaxValue; uint val1_3 = (uint)rgbaValue1 >> 8 & byte.MaxValue;
uint val1_4 = (uint) (rgbaValue1 & (int) byte.MaxValue); uint val1_4 = (uint)(rgbaValue1 & byte.MaxValue);
uint val2_1 = rgbaValue2 >> 24 & (uint) byte.MaxValue; uint val2_1 = rgbaValue2 >> 24 & byte.MaxValue;
uint val2_2 = rgbaValue2 >> 16 & (uint) byte.MaxValue; uint val2_2 = rgbaValue2 >> 16 & byte.MaxValue;
uint val2_3 = rgbaValue2 >> 8 & (uint) byte.MaxValue; uint val2_3 = rgbaValue2 >> 8 & byte.MaxValue;
uint val2_4 = rgbaValue2 & (uint) byte.MaxValue; uint val2_4 = rgbaValue2 & byte.MaxValue;
int num1 = (int) Math.Max(val1_1, val2_1) - (int) Math.Min(val1_1, val2_1); int num1 = (int)Math.Max(val1_1, val2_1) - (int)Math.Min(val1_1, val2_1);
uint num2 = Math.Max(val1_2, val2_2) - Math.Min(val1_2, val2_2); uint num2 = Math.Max(val1_2, val2_2) - Math.Min(val1_2, val2_2);
uint num3 = Math.Max(val1_3, val2_3) - Math.Min(val1_3, val2_3); uint num3 = Math.Max(val1_3, val2_3) - Math.Min(val1_3, val2_3);
uint num4 = Math.Max(val1_4, val2_4) - Math.Min(val1_4, val2_4); uint num4 = Math.Max(val1_4, val2_4) - Math.Min(val1_4, val2_4);
int num5 = (int) num2; int num5 = (int)num2;
return (uint) (num1 + num5) + num3 + num4; return (uint)(num1 + num5) + num3 + num4;
} }
private uint convertToRgbaValue(ushort pixel) private uint ConvertToRgbaValue(ushort pixel)
{ {
if (this.paletteFormat == TPL_PaletteFormat.IA8) if (paletteFormat == TPL_PaletteFormat.IA8)
{ {
int num1 = (int) pixel >> 8; int num1 = pixel >> 8;
int num2 = (int) pixel & (int) byte.MaxValue; int num2 = pixel & byte.MaxValue;
return (uint) (num1 | num1 << 8 | num1 << 16 | num2 << 24); return (uint)(num1 | num1 << 8 | num1 << 16 | num2 << 24);
} }
if (this.paletteFormat == TPL_PaletteFormat.RGB565) if (paletteFormat == TPL_PaletteFormat.RGB565)
{ {
int num1 = ((int) pixel >> 11 & 31) << 3 & (int) byte.MaxValue; int num1 = (pixel >> 11 & 31) << 3 & byte.MaxValue;
int num2 = ((int) pixel >> 5 & 63) << 2 & (int) byte.MaxValue; int num2 = (pixel >> 5 & 63) << 2 & byte.MaxValue;
int num3 = ((int) pixel & 31) << 3 & (int) byte.MaxValue; int num3 = (pixel & 31) << 3 & byte.MaxValue;
int maxValue = (int) byte.MaxValue; int maxValue = byte.MaxValue;
return (uint) (num3 | num2 << 8 | num1 << 16 | maxValue << 24); return (uint)(num3 | num2 << 8 | num1 << 16 | maxValue << 24);
} }
int num4; int num4;
int num5; int num5;
int num6; int num6;
int num7; int num7;
if (((int) pixel & 32768) != 0) if ((pixel & 32768) != 0)
{ {
num4 = ((int) pixel >> 10 & 31) * (int) byte.MaxValue / 31; num4 = (pixel >> 10 & 31) * byte.MaxValue / 31;
num5 = ((int) pixel >> 5 & 31) * (int) byte.MaxValue / 31; num5 = (pixel >> 5 & 31) * byte.MaxValue / 31;
num6 = ((int) pixel & 31) * (int) byte.MaxValue / 31; num6 = (pixel & 31) * byte.MaxValue / 31;
num7 = (int) byte.MaxValue; num7 = byte.MaxValue;
} }
else else
{ {
num7 = ((int) pixel >> 12 & 7) * (int) byte.MaxValue / 7; num7 = (pixel >> 12 & 7) * byte.MaxValue / 7;
num4 = ((int) pixel >> 8 & 15) * (int) byte.MaxValue / 15; num4 = (pixel >> 8 & 15) * byte.MaxValue / 15;
num5 = ((int) pixel >> 4 & 15) * (int) byte.MaxValue / 15; num5 = (pixel >> 4 & 15) * byte.MaxValue / 15;
num6 = ((int) pixel & 15) * (int) byte.MaxValue / 15; num6 = (pixel & 15) * byte.MaxValue / 15;
} }
return (uint) (num6 | num5 << 8 | num4 << 16 | num7 << 24); return (uint)(num6 | num5 << 8 | num4 << 16 | num7 << 24);
} }
} }
} }

View file

@ -20,11 +20,17 @@ namespace libWiiSharp
{ {
public class CommonKey public class CommonKey
{ {
private static string standardKey = "ebe42a225e8593e448d9c5457381aaf7"; private static readonly string standardKey = "ebe42a225e8593e448d9c5457381aaf7";
private static string koreanKey = "63b82bb4f4614e2e13f2fefbba4c9b7e"; private static readonly string koreanKey = "63b82bb4f4614e2e13f2fefbba4c9b7e";
public static byte[] GetStandardKey() => Shared.HexStringToByteArray(CommonKey.standardKey); public static byte[] GetStandardKey()
{
return Shared.HexStringToByteArray(CommonKey.standardKey);
}
public static byte[] GetKoreanKey() => Shared.HexStringToByteArray(CommonKey.koreanKey); public static byte[] GetKoreanKey()
{
return Shared.HexStringToByteArray(CommonKey.koreanKey);
}
} }
} }

View file

@ -20,26 +20,29 @@ using System;
namespace libWiiSharp namespace libWiiSharp
{ {
public struct ContentIndices : IComparable public struct ContentIndices : IComparable
{
private int index;
private int contentIndex;
public int Index => this.index;
public int ContentIndex => this.contentIndex;
public ContentIndices(int index, int contentIndex)
{ {
this.index = index; private readonly int index;
this.contentIndex = contentIndex; private readonly int contentIndex;
}
public int CompareTo(object obj) public int Index => index;
{
if (obj is ContentIndices contentIndices) public int ContentIndex => contentIndex;
return this.contentIndex.CompareTo(contentIndices.contentIndex);
throw new ArgumentException(); public ContentIndices(int index, int contentIndex)
{
this.index = index;
this.contentIndex = contentIndex;
}
public int CompareTo(object obj)
{
if (obj is ContentIndices contentIndices)
{
return contentIndex.CompareTo(contentIndices.contentIndex);
}
throw new ArgumentException();
}
} }
}
} }

View file

@ -52,8 +52,8 @@ namespace libWiiSharp
private bool compress; private bool compress;
private string ipAddress; private string ipAddress;
private int port = 4299; private int port = 4299;
private string lastErrorMessage = string.Empty; //private string lastErrorMessage = string.Empty;
private Protocol protocol; private readonly Protocol protocol;
private TcpClient tcpClient; private TcpClient tcpClient;
private NetworkStream nwStream; private NetworkStream nwStream;
private string lastError = string.Empty; private string lastError = string.Empty;
@ -67,8 +67,8 @@ namespace libWiiSharp
/// </summary> /// </summary>
public int Blocksize public int Blocksize
{ {
get => this.blocksize; get => blocksize;
set => this.blocksize = value; set => blocksize = value;
} }
/// <summary> /// <summary>
@ -76,8 +76,8 @@ namespace libWiiSharp
/// </summary> /// </summary>
public int WiiloadVersionMayor public int WiiloadVersionMayor
{ {
get => this.wiiloadMayor; get => wiiloadMayor;
set => this.wiiloadMayor = value; set => wiiloadMayor = value;
} }
/// <summary> /// <summary>
@ -85,8 +85,8 @@ namespace libWiiSharp
/// </summary> /// </summary>
public int WiiloadVersionMinor public int WiiloadVersionMinor
{ {
get => this.wiiloadMinor; get => wiiloadMinor;
set => this.wiiloadMinor = value; set => wiiloadMinor = value;
} }
/// <summary> /// <summary>
@ -95,12 +95,15 @@ namespace libWiiSharp
/// </summary> /// </summary>
public bool Compress public bool Compress
{ {
get => this.compress; get => compress;
set set
{ {
if (this.protocol == Protocol.HAXX) if (protocol == Protocol.HAXX)
{
return; return;
this.compress = value; }
compress = value;
} }
} }
@ -109,8 +112,8 @@ namespace libWiiSharp
/// </summary> /// </summary>
public string IpAddress public string IpAddress
{ {
get => this.ipAddress; get => ipAddress;
set => this.ipAddress = value; set => ipAddress = value;
} }
/// The port used for the transmission. /// The port used for the transmission.
@ -118,141 +121,153 @@ namespace libWiiSharp
/// </summary> /// </summary>
public int Port public int Port
{ {
get => this.port; get => port;
set => this.port = value; set => port = value;
} }
/// <summary> /// <summary>
/// After a successfully completed transmission, this value holds the number of transmitted bytes. /// After a successfully completed transmission, this value holds the number of transmitted bytes.
/// </summary> /// </summary>
public int TransmittedLength => this.transmittedLength; public int TransmittedLength => transmittedLength;
/// <summary> /// <summary>
/// After a successfully completed transmission, this value holds the compression ratio. /// After a successfully completed transmission, this value holds the compression ratio.
/// Will be 0 if the data wasn't compressed. /// Will be 0 if the data wasn't compressed.
/// </summary> /// </summary>
public int CompressionRatio => this.compressionRatio; public int CompressionRatio => compressionRatio;
/// <summary> /// <summary>
/// Holds the last occured error message. /// Holds the last occured error message.
/// </summary> /// </summary>
public string LastError => this.lastError; public string LastError => lastError;
public HbcTransmitter(Protocol protocol, string ipAddress) public HbcTransmitter(Protocol protocol, string ipAddress)
{ {
this.protocol = protocol; this.protocol = protocol;
this.ipAddress = ipAddress; this.ipAddress = ipAddress;
this.wiiloadMinor = protocol == Protocol.HAXX ? 4 : 5; wiiloadMinor = protocol == Protocol.HAXX ? 4 : 5;
this.compress = protocol == Protocol.JODI; compress = protocol == Protocol.JODI;
} }
#region IDisposable Members #region IDisposable Members
~HbcTransmitter() => this.Dispose(false); ~HbcTransmitter() => Dispose(false);
public void Dispose() public void Dispose()
{ {
this.Dispose(true); Dispose(true);
GC.SuppressFinalize((object) this); GC.SuppressFinalize(this);
} }
protected virtual void Dispose(bool disposing) protected virtual void Dispose(bool disposing)
{ {
if (disposing && !this.isDisposed) if (disposing && !isDisposed)
{ {
this.ipAddress = (string) null; ipAddress = null;
this.lastErrorMessage = (string) null; //this.lastErrorMessage = (string)null;
this.lastError = (string) null; lastError = null;
if (this.nwStream != null) if (nwStream != null)
{ {
this.nwStream.Close(); nwStream.Close();
this.nwStream = (NetworkStream) null; nwStream = null;
} }
if (this.tcpClient != null) if (tcpClient != null)
{ {
this.tcpClient.Close(); tcpClient.Close();
this.tcpClient = (TcpClient) null; tcpClient = null;
} }
} }
this.isDisposed = true; isDisposed = true;
} }
#endregion #endregion
#region Public Functions #region Public Functions
public bool TransmitFile(string pathToFile) => this.transmit(Path.GetFileName(pathToFile), File.ReadAllBytes(pathToFile)); public bool TransmitFile(string pathToFile)
{
return Transmit(Path.GetFileName(pathToFile), File.ReadAllBytes(pathToFile));
}
public bool TransmitFile(string fileName, byte[] fileData) => this.transmit(fileName, fileData); public bool TransmitFile(string fileName, byte[] fileData)
{
return Transmit(fileName, fileData);
}
#endregion #endregion
#region Private Functions #region Private Functions
private bool transmit(string fileName, byte[] fileData) private bool Transmit(string fileName, byte[] fileData)
{ {
this.fireDebug("Transmitting {0} to {1}:{2}...", (object) fileName, (object) this.ipAddress, (object) this.port); FireDebug("Transmitting {0} to {1}:{2}...", fileName, ipAddress, port);
if (!Environment.OSVersion.ToString().ToLower().Contains("windows")) if (!Environment.OSVersion.ToString().ToLower().Contains("windows"))
this.compress = false; {
compress = false;
}
if (fileName.ToLower().EndsWith(".zip")) if (fileName.ToLower().EndsWith(".zip"))
this.compress = false; {
this.tcpClient = new TcpClient(); compress = false;
}
tcpClient = new TcpClient();
byte[] buffer1 = new byte[4]; byte[] buffer1 = new byte[4];
this.fireDebug(" Connecting..."); FireDebug(" Connecting...");
try try
{ {
this.tcpClient.Connect(this.ipAddress, 4299); tcpClient.Connect(ipAddress, 4299);
} }
catch (Exception ex) catch (Exception ex)
{ {
this.fireDebug(" -> Connection Failed:\n" + ex.Message); FireDebug(" -> Connection Failed:\n" + ex.Message);
this.lastError = "Connection Failed:\n" + ex.Message; lastError = "Connection Failed:\n" + ex.Message;
this.tcpClient.Close(); tcpClient.Close();
return false; return false;
} }
this.nwStream = this.tcpClient.GetStream(); nwStream = tcpClient.GetStream();
this.fireDebug(" Sending Magic..."); FireDebug(" Sending Magic...");
buffer1[0] = (byte) 72; buffer1[0] = 72;
buffer1[1] = (byte) 65; buffer1[1] = 65;
buffer1[2] = (byte) 88; buffer1[2] = 88;
buffer1[3] = (byte) 88; buffer1[3] = 88;
try try
{ {
this.nwStream.Write(buffer1, 0, 4); nwStream.Write(buffer1, 0, 4);
} }
catch (Exception ex) catch (Exception ex)
{ {
this.fireDebug(" -> Error sending Magic:\n" + ex.Message); FireDebug(" -> Error sending Magic:\n" + ex.Message);
this.lastError = "Error sending Magic:\n" + ex.Message; lastError = "Error sending Magic:\n" + ex.Message;
this.nwStream.Close(); nwStream.Close();
this.tcpClient.Close(); tcpClient.Close();
return false; return false;
} }
this.fireDebug(" Sending Version Info..."); FireDebug(" Sending Version Info...");
buffer1[0] = (byte) this.wiiloadMayor; buffer1[0] = (byte)wiiloadMayor;
buffer1[1] = (byte) this.wiiloadMinor; buffer1[1] = (byte)wiiloadMinor;
buffer1[2] = (byte) (fileName.Length + 2 >> 8 & (int) byte.MaxValue); buffer1[2] = (byte)(fileName.Length + 2 >> 8 & byte.MaxValue);
buffer1[3] = (byte) (fileName.Length + 2 & (int) byte.MaxValue); buffer1[3] = (byte)(fileName.Length + 2 & byte.MaxValue);
try try
{ {
this.nwStream.Write(buffer1, 0, 4); nwStream.Write(buffer1, 0, 4);
} }
catch (Exception ex) catch (Exception ex)
{ {
this.fireDebug(" -> Error sending Version Info:\n" + ex.Message); FireDebug(" -> Error sending Version Info:\n" + ex.Message);
this.lastError = "Error sending Version Info:\n" + ex.Message; lastError = "Error sending Version Info:\n" + ex.Message;
this.nwStream.Close(); nwStream.Close();
this.tcpClient.Close(); tcpClient.Close();
return false; return false;
} }
byte[] buffer2; byte[] buffer2;
if (this.compress) if (compress)
{ {
this.fireDebug(" Compressing File..."); FireDebug(" Compressing File...");
try try
{ {
buffer2 = zlibWrapper.Compress(fileData); buffer2 = ZlibWrapper.Compress(fileData);
} }
catch catch
{ {
this.fireDebug(" -> Compression failed, continuing without compression..."); FireDebug(" -> Compression failed, continuing without compression...");
this.compress = false; compress = false;
buffer2 = fileData; buffer2 = fileData;
fileData = new byte[0]; fileData = new byte[0];
} }
@ -262,88 +277,93 @@ namespace libWiiSharp
buffer2 = fileData; buffer2 = fileData;
fileData = new byte[0]; fileData = new byte[0];
} }
this.fireDebug(" Sending Filesize..."); FireDebug(" Sending Filesize...");
buffer1[0] = (byte) (buffer2.Length >> 24 & (int) byte.MaxValue); buffer1[0] = (byte)(buffer2.Length >> 24 & byte.MaxValue);
buffer1[1] = (byte) (buffer2.Length >> 16 & (int) byte.MaxValue); buffer1[1] = (byte)(buffer2.Length >> 16 & byte.MaxValue);
buffer1[2] = (byte) (buffer2.Length >> 8 & (int) byte.MaxValue); buffer1[2] = (byte)(buffer2.Length >> 8 & byte.MaxValue);
buffer1[3] = (byte) (buffer2.Length & (int) byte.MaxValue); buffer1[3] = (byte)(buffer2.Length & byte.MaxValue);
try try
{ {
this.nwStream.Write(buffer1, 0, 4); nwStream.Write(buffer1, 0, 4);
} }
catch (Exception ex) catch (Exception ex)
{ {
this.fireDebug(" -> Error sending Filesize:\n" + ex.Message); FireDebug(" -> Error sending Filesize:\n" + ex.Message);
this.lastError = "Error sending Filesize:\n" + ex.Message; lastError = "Error sending Filesize:\n" + ex.Message;
this.nwStream.Close(); nwStream.Close();
this.tcpClient.Close(); tcpClient.Close();
return false; return false;
} }
if (this.protocol != Protocol.HAXX) if (protocol != Protocol.HAXX)
{ {
buffer1[0] = (byte) (fileData.Length >> 24 & (int) byte.MaxValue); buffer1[0] = (byte)(fileData.Length >> 24 & byte.MaxValue);
buffer1[1] = (byte) (fileData.Length >> 16 & (int) byte.MaxValue); buffer1[1] = (byte)(fileData.Length >> 16 & byte.MaxValue);
buffer1[2] = (byte) (fileData.Length >> 8 & (int) byte.MaxValue); buffer1[2] = (byte)(fileData.Length >> 8 & byte.MaxValue);
buffer1[3] = (byte) (fileData.Length & (int) byte.MaxValue); buffer1[3] = (byte)(fileData.Length & byte.MaxValue);
try try
{ {
this.nwStream.Write(buffer1, 0, 4); nwStream.Write(buffer1, 0, 4);
} }
catch (Exception ex) catch (Exception ex)
{ {
this.fireDebug(" -> Error sending Filesize:\n" + ex.Message); FireDebug(" -> Error sending Filesize:\n" + ex.Message);
this.lastError = "Error sending Filesize:\n" + ex.Message; lastError = "Error sending Filesize:\n" + ex.Message;
this.nwStream.Close(); nwStream.Close();
this.tcpClient.Close(); tcpClient.Close();
return false; return false;
} }
} }
this.fireDebug(" Sending File..."); FireDebug(" Sending File...");
int offset = 0; int offset = 0;
int num1 = 0; int num1 = 0;
int num2 = buffer2.Length / this.Blocksize; int num2 = buffer2.Length / Blocksize;
int num3 = buffer2.Length % this.Blocksize; int num3 = buffer2.Length % Blocksize;
try try
{ {
do do
{ {
this.fireProgress(++num1 * 100 / num2); FireProgress(++num1 * 100 / num2);
this.nwStream.Write(buffer2, offset, this.Blocksize); nwStream.Write(buffer2, offset, Blocksize);
offset += this.Blocksize; offset += Blocksize;
} }
while (num1 < num2); while (num1 < num2);
if (num3 > 0) if (num3 > 0)
this.nwStream.Write(buffer2, offset, buffer2.Length - offset); {
nwStream.Write(buffer2, offset, buffer2.Length - offset);
}
} }
catch (Exception ex) catch (Exception ex)
{ {
this.fireDebug(" -> Error sending File:\n" + ex.Message); FireDebug(" -> Error sending File:\n" + ex.Message);
this.lastError = "Error sending File:\n" + ex.Message; lastError = "Error sending File:\n" + ex.Message;
this.nwStream.Close(); nwStream.Close();
this.tcpClient.Close(); tcpClient.Close();
return false; return false;
} }
this.fireDebug(" Sending Arguments..."); FireDebug(" Sending Arguments...");
byte[] buffer3 = new byte[fileName.Length + 2]; byte[] buffer3 = new byte[fileName.Length + 2];
for (int index = 0; index < fileName.Length; ++index) for (int index = 0; index < fileName.Length; ++index)
buffer3[index] = (byte) fileName.ToCharArray()[index]; {
buffer3[index] = (byte)fileName.ToCharArray()[index];
}
try try
{ {
this.nwStream.Write(buffer3, 0, buffer3.Length); nwStream.Write(buffer3, 0, buffer3.Length);
} }
catch (Exception ex) catch (Exception ex)
{ {
this.fireDebug(" -> Error sending Arguments:\n" + ex.Message); FireDebug(" -> Error sending Arguments:\n" + ex.Message);
this.lastError = "Error sending Arguments:\n" + ex.Message; lastError = "Error sending Arguments:\n" + ex.Message;
this.nwStream.Close(); nwStream.Close();
this.tcpClient.Close(); tcpClient.Close();
return false; return false;
} }
this.nwStream.Close(); nwStream.Close();
this.tcpClient.Close(); tcpClient.Close();
this.transmittedLength = buffer2.Length; transmittedLength = buffer2.Length;
this.compressionRatio = !this.compress || fileData.Length == 0 ? 0 : buffer2.Length * 100 / fileData.Length; compressionRatio = !compress || fileData.Length == 0 ? 0 : buffer2.Length * 100 / fileData.Length;
this.fireDebug("Transmitting {0} to {1}:{2} Finished...", (object) fileName, (object) this.ipAddress, (object) this.port); FireDebug("Transmitting {0} to {1}:{2} Finished...", fileName, ipAddress, port);
return true; return true;
} }
#endregion #endregion
@ -359,28 +379,34 @@ namespace libWiiSharp
/// </summary> /// </summary>
public event EventHandler<MessageEventArgs> Debug; public event EventHandler<MessageEventArgs> Debug;
private void fireDebug(string debugMessage, params object[] args) private void FireDebug(string debugMessage, params object[] args)
{ {
EventHandler<MessageEventArgs> debug = this.Debug; EventHandler<MessageEventArgs> debug = Debug;
if (debug == null) if (debug == null)
{
return; return;
}
debug(new object(), new MessageEventArgs(string.Format(debugMessage, args))); debug(new object(), new MessageEventArgs(string.Format(debugMessage, args)));
} }
private void fireProgress(int progressPercentage) private void FireProgress(int progressPercentage)
{ {
EventHandler<ProgressChangedEventArgs> progress = this.Progress; EventHandler<ProgressChangedEventArgs> progress = Progress;
if (progress == null) if (progress == null)
{
return; return;
progress(new object(), new ProgressChangedEventArgs(progressPercentage, (object) string.Empty)); }
progress(new object(), new ProgressChangedEventArgs(progressPercentage, string.Empty));
} }
#endregion #endregion
} }
internal class zlibWrapper internal class ZlibWrapper
{ {
[DllImport("zlib1.dll")] [DllImport("zlib1.dll")]
private static extern zlibWrapper.ZLibError compress2( private static extern ZlibWrapper.ZLibError Compress2(
byte[] dest, byte[] dest,
ref int destLength, ref int destLength,
byte[] source, byte[] source,
@ -391,9 +417,12 @@ namespace libWiiSharp
{ {
byte[] array = new byte[inFile.Length + 64]; byte[] array = new byte[inFile.Length + 64];
int destLength = -1; int destLength = -1;
zlibWrapper.ZLibError zlibError = zlibWrapper.compress2(array, ref destLength, inFile, inFile.Length, 6); ZlibWrapper.ZLibError zlibError = ZlibWrapper.Compress2(array, ref destLength, inFile, inFile.Length, 6);
if (zlibError != zlibWrapper.ZLibError.Z_OK || destLength <= -1 || destLength >= inFile.Length) if (zlibError != ZlibWrapper.ZLibError.Z_OK || destLength <= -1 || destLength >= inFile.Length)
{
throw new Exception("An error occured while compressing! Code: " + zlibError.ToString()); throw new Exception("An error occured while compressing! Code: " + zlibError.ToString());
}
Array.Resize<byte>(ref array, destLength); Array.Resize<byte>(ref array, destLength);
return array; return array;
} }

View file

@ -24,8 +24,8 @@ namespace libWiiSharp
{ {
public class Headers public class Headers
{ {
private static uint imd5Magic = 1229800501; private static readonly uint imd5Magic = 1229800501;
private static uint imetMagic = 1229800788; private static readonly uint imetMagic = 1229800788;
/// <summary> /// <summary>
/// Convert HeaderType to int to get it's Length. /// Convert HeaderType to int to get it's Length.
@ -53,7 +53,10 @@ namespace libWiiSharp
/// </summary> /// </summary>
/// <param name="pathToFile"></param> /// <param name="pathToFile"></param>
/// <returns></returns> /// <returns></returns>
public static Headers.HeaderType DetectHeader(string pathToFile) => Headers.DetectHeader(File.ReadAllBytes(pathToFile)); public static Headers.HeaderType DetectHeader(string pathToFile)
{
return Headers.DetectHeader(File.ReadAllBytes(pathToFile));
}
/// <summary> /// <summary>
/// Checks the byte array for Headers. /// Checks the byte array for Headers.
@ -62,11 +65,17 @@ namespace libWiiSharp
/// <returns></returns> /// <returns></returns>
public static Headers.HeaderType DetectHeader(byte[] file) public static Headers.HeaderType DetectHeader(byte[] file)
{ {
if (file.Length > 68 && (int) Shared.Swap(BitConverter.ToUInt32(file, 64)) == (int) Headers.imetMagic) if (file.Length > 68 && (int)Shared.Swap(BitConverter.ToUInt32(file, 64)) == (int)Headers.imetMagic)
{
return Headers.HeaderType.ShortIMET; return Headers.HeaderType.ShortIMET;
if (file.Length > 132 && (int) Shared.Swap(BitConverter.ToUInt32(file, 128)) == (int) Headers.imetMagic) }
if (file.Length > 132 && (int)Shared.Swap(BitConverter.ToUInt32(file, 128)) == (int)Headers.imetMagic)
{
return Headers.HeaderType.IMET; return Headers.HeaderType.IMET;
return file.Length > 4 && (int) Shared.Swap(BitConverter.ToUInt32(file, 0)) == (int) Headers.imd5Magic ? Headers.HeaderType.IMD5 : Headers.HeaderType.None; }
return file.Length > 4 && (int)Shared.Swap(BitConverter.ToUInt32(file, 0)) == (int)Headers.imd5Magic ? Headers.HeaderType.IMD5 : Headers.HeaderType.None;
} }
/// <summary> /// <summary>
@ -81,22 +90,28 @@ namespace libWiiSharp
{ {
file.Seek(64L, SeekOrigin.Begin); file.Seek(64L, SeekOrigin.Begin);
file.Read(buffer, 0, buffer.Length); file.Read(buffer, 0, buffer.Length);
if ((int) Shared.Swap(BitConverter.ToUInt32(buffer, 0)) == (int) Headers.imetMagic) if ((int)Shared.Swap(BitConverter.ToUInt32(buffer, 0)) == (int)Headers.imetMagic)
{
return Headers.HeaderType.ShortIMET; return Headers.HeaderType.ShortIMET;
}
} }
if (file.Length > 132L) if (file.Length > 132L)
{ {
file.Seek(128L, SeekOrigin.Begin); file.Seek(128L, SeekOrigin.Begin);
file.Read(buffer, 0, buffer.Length); file.Read(buffer, 0, buffer.Length);
if ((int) Shared.Swap(BitConverter.ToUInt32(buffer, 0)) == (int) Headers.imetMagic) if ((int)Shared.Swap(BitConverter.ToUInt32(buffer, 0)) == (int)Headers.imetMagic)
{
return Headers.HeaderType.IMET; return Headers.HeaderType.IMET;
}
} }
if (file.Length > 4L) if (file.Length > 4L)
{ {
file.Seek(0L, SeekOrigin.Begin); file.Seek(0L, SeekOrigin.Begin);
file.Read(buffer, 0, buffer.Length); file.Read(buffer, 0, buffer.Length);
if ((int) Shared.Swap(BitConverter.ToUInt32(buffer, 0)) == (int) Headers.imd5Magic) if ((int)Shared.Swap(BitConverter.ToUInt32(buffer, 0)) == (int)Headers.imd5Magic)
{
return Headers.HeaderType.IMD5; return Headers.HeaderType.IMD5;
}
} }
return Headers.HeaderType.None; return Headers.HeaderType.None;
} }
@ -106,10 +121,10 @@ namespace libWiiSharp
{ {
private bool hashesMatch = true; private bool hashesMatch = true;
private bool isShortImet; private bool isShortImet;
private byte[] additionalPadding = new byte[64]; private readonly byte[] additionalPadding = new byte[64];
private byte[] padding = new byte[64]; private readonly byte[] padding = new byte[64];
private uint imetMagic = 1229800788; private readonly uint imetMagic = 1229800788;
private uint sizeOfHeader = 1536; private readonly uint sizeOfHeader = 1536;
private uint unknown = 3; private uint unknown = 3;
private uint iconSize; private uint iconSize;
private uint bannerSize; private uint bannerSize;
@ -122,10 +137,10 @@ namespace libWiiSharp
private byte[] spanishTitle = new byte[84]; private byte[] spanishTitle = new byte[84];
private byte[] italianTitle = new byte[84]; private byte[] italianTitle = new byte[84];
private byte[] dutchTitle = new byte[84]; private byte[] dutchTitle = new byte[84];
private byte[] unknownTitle1 = new byte[84]; private readonly byte[] unknownTitle1 = new byte[84];
private byte[] unknownTitle2 = new byte[84]; private readonly byte[] unknownTitle2 = new byte[84];
private byte[] koreanTitle = new byte[84]; private byte[] koreanTitle = new byte[84];
private byte[] padding2 = new byte[588]; private readonly byte[] padding2 = new byte[588];
private byte[] hash = new byte[16]; private byte[] hash = new byte[16];
/// <summary> /// <summary>
@ -133,8 +148,8 @@ namespace libWiiSharp
/// </summary> /// </summary>
public bool IsShortIMET public bool IsShortIMET
{ {
get => this.isShortImet; get => isShortImet;
set => this.isShortImet = value; set => isShortImet = value;
} }
/// <summary> /// <summary>
@ -142,8 +157,8 @@ namespace libWiiSharp
/// </summary> /// </summary>
public uint IconSize public uint IconSize
{ {
get => this.iconSize; get => iconSize;
set => this.iconSize = value; set => iconSize = value;
} }
/// <summary> /// <summary>
@ -151,8 +166,8 @@ namespace libWiiSharp
/// </summary> /// </summary>
public uint BannerSize public uint BannerSize
{ {
get => this.bannerSize; get => bannerSize;
set => this.bannerSize = value; set => bannerSize = value;
} }
/// <summary> /// <summary>
@ -160,8 +175,8 @@ namespace libWiiSharp
/// </summary> /// </summary>
public uint SoundSize public uint SoundSize
{ {
get => this.soundSize; get => soundSize;
set => this.soundSize = value; set => soundSize = value;
} }
/// <summary> /// <summary>
@ -169,8 +184,8 @@ namespace libWiiSharp
/// </summary> /// </summary>
public string JapaneseTitle public string JapaneseTitle
{ {
get => this.returnTitleAsString(this.japaneseTitle); get => ReturnTitleAsString(japaneseTitle);
set => this.setTitleFromString(value, 0); set => SetTitleFromString(value, 0);
} }
/// <summary> /// <summary>
@ -178,8 +193,8 @@ namespace libWiiSharp
/// </summary> /// </summary>
public string EnglishTitle public string EnglishTitle
{ {
get => this.returnTitleAsString(this.englishTitle); get => ReturnTitleAsString(englishTitle);
set => this.setTitleFromString(value, 1); set => SetTitleFromString(value, 1);
} }
/// <summary> /// <summary>
@ -187,8 +202,8 @@ namespace libWiiSharp
/// </summary> /// </summary>
public string GermanTitle public string GermanTitle
{ {
get => this.returnTitleAsString(this.germanTitle); get => ReturnTitleAsString(germanTitle);
set => this.setTitleFromString(value, 2); set => SetTitleFromString(value, 2);
} }
/// <summary> /// <summary>
@ -196,8 +211,8 @@ namespace libWiiSharp
/// </summary> /// </summary>
public string FrenchTitle public string FrenchTitle
{ {
get => this.returnTitleAsString(this.frenchTitle); get => ReturnTitleAsString(frenchTitle);
set => this.setTitleFromString(value, 3); set => SetTitleFromString(value, 3);
} }
/// <summary> /// <summary>
@ -205,8 +220,8 @@ namespace libWiiSharp
/// </summary> /// </summary>
public string SpanishTitle public string SpanishTitle
{ {
get => this.returnTitleAsString(this.spanishTitle); get => ReturnTitleAsString(spanishTitle);
set => this.setTitleFromString(value, 4); set => SetTitleFromString(value, 4);
} }
/// <summary> /// <summary>
@ -214,8 +229,8 @@ namespace libWiiSharp
/// </summary> /// </summary>
public string ItalianTitle public string ItalianTitle
{ {
get => this.returnTitleAsString(this.italianTitle); get => ReturnTitleAsString(italianTitle);
set => this.setTitleFromString(value, 5); set => SetTitleFromString(value, 5);
} }
/// <summary> /// <summary>
@ -223,8 +238,8 @@ namespace libWiiSharp
/// </summary> /// </summary>
public string DutchTitle public string DutchTitle
{ {
get => this.returnTitleAsString(this.dutchTitle); get => ReturnTitleAsString(dutchTitle);
set => this.setTitleFromString(value, 6); set => SetTitleFromString(value, 6);
} }
/// <summary> /// <summary>
@ -232,8 +247,8 @@ namespace libWiiSharp
/// </summary> /// </summary>
public string KoreanTitle public string KoreanTitle
{ {
get => this.returnTitleAsString(this.koreanTitle); get => ReturnTitleAsString(koreanTitle);
set => this.setTitleFromString(value, 7); set => SetTitleFromString(value, 7);
} }
/// <summary> /// <summary>
@ -241,20 +256,20 @@ namespace libWiiSharp
/// </summary> /// </summary>
public string[] AllTitles => new string[8] public string[] AllTitles => new string[8]
{ {
this.JapaneseTitle, JapaneseTitle,
this.EnglishTitle, EnglishTitle,
this.GermanTitle, GermanTitle,
this.FrenchTitle, FrenchTitle,
this.SpanishTitle, SpanishTitle,
this.ItalianTitle, ItalianTitle,
this.DutchTitle, DutchTitle,
this.KoreanTitle KoreanTitle
}; };
/// <summary> /// <summary>
/// When parsing an IMET header, this value will turn false if the hash stored in the header doesn't match the headers hash. /// When parsing an IMET header, this value will turn false if the hash stored in the header doesn't match the headers hash.
/// </summary> /// </summary>
public bool HashesMatch => this.hashesMatch; public bool HashesMatch => hashesMatch;
#region Public Functions #region Public Functions
/// <summary> /// <summary>
@ -262,7 +277,10 @@ namespace libWiiSharp
/// </summary> /// </summary>
/// <param name="pathToFile"></param> /// <param name="pathToFile"></param>
/// <returns></returns> /// <returns></returns>
public static Headers.IMET Load(string pathToFile) => Headers.IMET.Load(File.ReadAllBytes(pathToFile)); public static Headers.IMET Load(string pathToFile)
{
return Headers.IMET.Load(File.ReadAllBytes(pathToFile));
}
/// <summary> /// <summary>
/// Loads the IMET Header of a byte array. /// Loads the IMET Header of a byte array.
@ -278,11 +296,14 @@ namespace libWiiSharp
case Headers.HeaderType.IMET: case Headers.HeaderType.IMET:
Headers.IMET imet = new Headers.IMET(); Headers.IMET imet = new Headers.IMET();
if (headerType == Headers.HeaderType.ShortIMET) if (headerType == Headers.HeaderType.ShortIMET)
{
imet.isShortImet = true; imet.isShortImet = true;
}
MemoryStream memoryStream = new MemoryStream(fileOrHeader); MemoryStream memoryStream = new MemoryStream(fileOrHeader);
try try
{ {
imet.parseHeader((Stream) memoryStream); imet.ParseHeader(memoryStream);
} }
catch catch
{ {
@ -310,8 +331,11 @@ namespace libWiiSharp
case Headers.HeaderType.IMET: case Headers.HeaderType.IMET:
Headers.IMET imet = new Headers.IMET(); Headers.IMET imet = new Headers.IMET();
if (headerType == Headers.HeaderType.ShortIMET) if (headerType == Headers.HeaderType.ShortIMET)
{
imet.isShortImet = true; imet.isShortImet = true;
imet.parseHeader(fileOrHeader); }
imet.ParseHeader(fileOrHeader);
return imet; return imet;
default: default:
throw new Exception("No IMET Header found!"); throw new Exception("No IMET Header found!");
@ -334,15 +358,23 @@ namespace libWiiSharp
int soundSize, int soundSize,
params string[] titles) params string[] titles)
{ {
Headers.IMET imet = new Headers.IMET(); Headers.IMET imet = new Headers.IMET
imet.isShortImet = isShortImet; {
isShortImet = isShortImet
};
for (int titleIndex = 0; titleIndex < titles.Length; ++titleIndex) for (int titleIndex = 0; titleIndex < titles.Length; ++titleIndex)
imet.setTitleFromString(titles[titleIndex], titleIndex); {
imet.SetTitleFromString(titles[titleIndex], titleIndex);
}
for (int length = titles.Length; length < 8; ++length) for (int length = titles.Length; length < 8; ++length)
imet.setTitleFromString(titles.Length > 1 ? titles[1] : titles[0], length); {
imet.iconSize = (uint) iconSize; imet.SetTitleFromString(titles.Length > 1 ? titles[1] : titles[0], length);
imet.bannerSize = (uint) bannerSize; }
imet.soundSize = (uint) soundSize;
imet.iconSize = (uint)iconSize;
imet.bannerSize = (uint)bannerSize;
imet.soundSize = (uint)soundSize;
return imet; return imet;
} }
@ -367,13 +399,13 @@ namespace libWiiSharp
Headers.HeaderType headerType = Headers.DetectHeader(file); Headers.HeaderType headerType = Headers.DetectHeader(file);
switch (headerType) switch (headerType)
{ {
case Headers.HeaderType.ShortIMET: case Headers.HeaderType.ShortIMET:
case Headers.HeaderType.IMET: case Headers.HeaderType.IMET:
byte[] numArray = new byte[(int) (file.Length - headerType)]; byte[] numArray = new byte[(int)(file.Length - headerType)];
Array.Copy((Array) file, (int) headerType, (Array) numArray, 0, numArray.Length); Array.Copy(file, (int)headerType, numArray, 0, numArray.Length);
return numArray; return numArray;
default: default:
throw new Exception("No IMET Header found!"); throw new Exception("No IMET Header found!");
} }
} }
@ -384,7 +416,9 @@ namespace libWiiSharp
public void SetAllTitles(string newTitle) public void SetAllTitles(string newTitle)
{ {
for (int titleIndex = 0; titleIndex < 10; ++titleIndex) for (int titleIndex = 0; titleIndex < 10; ++titleIndex)
this.setTitleFromString(newTitle, titleIndex); {
SetTitleFromString(newTitle, titleIndex);
}
} }
/// <summary> /// <summary>
@ -396,7 +430,7 @@ namespace libWiiSharp
MemoryStream memoryStream = new MemoryStream(); MemoryStream memoryStream = new MemoryStream();
try try
{ {
this.writeToStream((Stream) memoryStream); WriteToStream(memoryStream);
return memoryStream; return memoryStream;
} }
catch catch
@ -410,13 +444,19 @@ namespace libWiiSharp
/// Returns the Header as a byte array. /// Returns the Header as a byte array.
/// </summary> /// </summary>
/// <returns></returns> /// <returns></returns>
public byte[] ToByteArray() => this.ToMemoryStream().ToArray(); public byte[] ToByteArray()
{
return ToMemoryStream().ToArray();
}
/// <summary> /// <summary>
/// Writes the Header to the given stream. /// Writes the Header to the given stream.
/// </summary> /// </summary>
/// <param name="writeStream"></param> /// <param name="writeStream"></param>
public void Write(Stream writeStream) => this.writeToStream(writeStream); public void Write(Stream writeStream)
{
WriteToStream(writeStream);
}
/// <summary> /// <summary>
/// Changes the Titles. /// Changes the Titles.
@ -425,105 +465,125 @@ namespace libWiiSharp
public void ChangeTitles(params string[] newTitles) public void ChangeTitles(params string[] newTitles)
{ {
for (int titleIndex = 0; titleIndex < newTitles.Length; ++titleIndex) for (int titleIndex = 0; titleIndex < newTitles.Length; ++titleIndex)
this.setTitleFromString(newTitles[titleIndex], titleIndex); {
SetTitleFromString(newTitles[titleIndex], titleIndex);
}
for (int length = newTitles.Length; length < 8; ++length) for (int length = newTitles.Length; length < 8; ++length)
this.setTitleFromString(newTitles.Length > 1 ? newTitles[1] : newTitles[0], length); {
SetTitleFromString(newTitles.Length > 1 ? newTitles[1] : newTitles[0], length);
}
} }
/// <summary> /// <summary>
/// Returns a string array with the Titles. /// Returns a string array with the Titles.
/// </summary> /// </summary>
/// <returns></returns> /// <returns></returns>
public string[] GetTitles() => new string[8] public string[] GetTitles()
{ {
this.JapaneseTitle, return new string[8]
this.EnglishTitle, {
this.GermanTitle, JapaneseTitle,
this.FrenchTitle, EnglishTitle,
this.SpanishTitle, GermanTitle,
this.ItalianTitle, FrenchTitle,
this.DutchTitle, SpanishTitle,
this.KoreanTitle ItalianTitle,
}; DutchTitle,
KoreanTitle
};
}
#endregion #endregion
#region Private Functions #region Private Functions
private void writeToStream(Stream writeStream) private void WriteToStream(Stream writeStream)
{ {
writeStream.Seek(0L, SeekOrigin.Begin); writeStream.Seek(0L, SeekOrigin.Begin);
if (!this.isShortImet) if (!isShortImet)
writeStream.Write(this.additionalPadding, 0, this.additionalPadding.Length); {
writeStream.Write(this.padding, 0, this.padding.Length); writeStream.Write(additionalPadding, 0, additionalPadding.Length);
writeStream.Write(BitConverter.GetBytes(Shared.Swap(this.imetMagic)), 0, 4); }
writeStream.Write(BitConverter.GetBytes(Shared.Swap(this.sizeOfHeader)), 0, 4);
writeStream.Write(BitConverter.GetBytes(Shared.Swap(this.unknown)), 0, 4); writeStream.Write(padding, 0, padding.Length);
writeStream.Write(BitConverter.GetBytes(Shared.Swap(this.iconSize)), 0, 4); writeStream.Write(BitConverter.GetBytes(Shared.Swap(imetMagic)), 0, 4);
writeStream.Write(BitConverter.GetBytes(Shared.Swap(this.bannerSize)), 0, 4); writeStream.Write(BitConverter.GetBytes(Shared.Swap(sizeOfHeader)), 0, 4);
writeStream.Write(BitConverter.GetBytes(Shared.Swap(this.soundSize)), 0, 4); writeStream.Write(BitConverter.GetBytes(Shared.Swap(unknown)), 0, 4);
writeStream.Write(BitConverter.GetBytes(Shared.Swap(this.flags)), 0, 4); writeStream.Write(BitConverter.GetBytes(Shared.Swap(iconSize)), 0, 4);
writeStream.Write(this.japaneseTitle, 0, this.japaneseTitle.Length); writeStream.Write(BitConverter.GetBytes(Shared.Swap(bannerSize)), 0, 4);
writeStream.Write(this.englishTitle, 0, this.englishTitle.Length); writeStream.Write(BitConverter.GetBytes(Shared.Swap(soundSize)), 0, 4);
writeStream.Write(this.germanTitle, 0, this.germanTitle.Length); writeStream.Write(BitConverter.GetBytes(Shared.Swap(flags)), 0, 4);
writeStream.Write(this.frenchTitle, 0, this.frenchTitle.Length); writeStream.Write(japaneseTitle, 0, japaneseTitle.Length);
writeStream.Write(this.spanishTitle, 0, this.spanishTitle.Length); writeStream.Write(englishTitle, 0, englishTitle.Length);
writeStream.Write(this.italianTitle, 0, this.italianTitle.Length); writeStream.Write(germanTitle, 0, germanTitle.Length);
writeStream.Write(this.dutchTitle, 0, this.dutchTitle.Length); writeStream.Write(frenchTitle, 0, frenchTitle.Length);
writeStream.Write(this.unknownTitle1, 0, this.unknownTitle1.Length); writeStream.Write(spanishTitle, 0, spanishTitle.Length);
writeStream.Write(this.unknownTitle2, 0, this.unknownTitle2.Length); writeStream.Write(italianTitle, 0, italianTitle.Length);
writeStream.Write(this.koreanTitle, 0, this.koreanTitle.Length); writeStream.Write(dutchTitle, 0, dutchTitle.Length);
writeStream.Write(this.padding2, 0, this.padding2.Length); writeStream.Write(unknownTitle1, 0, unknownTitle1.Length);
int position = (int) writeStream.Position; writeStream.Write(unknownTitle2, 0, unknownTitle2.Length);
this.hash = new byte[16]; writeStream.Write(koreanTitle, 0, koreanTitle.Length);
writeStream.Write(this.hash, 0, this.hash.Length); writeStream.Write(padding2, 0, padding2.Length);
int position = (int)writeStream.Position;
hash = new byte[16];
writeStream.Write(hash, 0, hash.Length);
byte[] numArray = new byte[writeStream.Position]; byte[] numArray = new byte[writeStream.Position];
writeStream.Seek(0L, SeekOrigin.Begin); writeStream.Seek(0L, SeekOrigin.Begin);
writeStream.Read(numArray, 0, numArray.Length); writeStream.Read(numArray, 0, numArray.Length);
this.computeHash(numArray, !this.isShortImet ? 64 : 0); ComputeHash(numArray, !isShortImet ? 64 : 0);
writeStream.Seek((long) position, SeekOrigin.Begin); writeStream.Seek(position, SeekOrigin.Begin);
writeStream.Write(this.hash, 0, this.hash.Length); writeStream.Write(hash, 0, hash.Length);
} }
private void computeHash(byte[] headerBytes, int hashPos) private void ComputeHash(byte[] headerBytes, int hashPos)
{ {
MD5 md5 = MD5.Create(); MD5 md5 = MD5.Create();
this.hash = md5.ComputeHash(headerBytes, hashPos, 1536); hash = md5.ComputeHash(headerBytes, hashPos, 1536);
md5.Clear(); md5.Clear();
} }
private void parseHeader(Stream headerStream) private void ParseHeader(Stream headerStream)
{ {
headerStream.Seek(0L, SeekOrigin.Begin); headerStream.Seek(0L, SeekOrigin.Begin);
byte[] buffer1 = new byte[4]; byte[] buffer1 = new byte[4];
if (!this.isShortImet) if (!isShortImet)
headerStream.Read(this.additionalPadding, 0, this.additionalPadding.Length); {
headerStream.Read(this.padding, 0, this.padding.Length); headerStream.Read(additionalPadding, 0, additionalPadding.Length);
}
headerStream.Read(padding, 0, padding.Length);
headerStream.Read(buffer1, 0, 4); headerStream.Read(buffer1, 0, 4);
if ((int) Shared.Swap(BitConverter.ToUInt32(buffer1, 0)) != (int) this.imetMagic) if ((int)Shared.Swap(BitConverter.ToUInt32(buffer1, 0)) != (int)imetMagic)
{
throw new Exception("Invalid Magic!"); throw new Exception("Invalid Magic!");
}
headerStream.Read(buffer1, 0, 4); headerStream.Read(buffer1, 0, 4);
if ((int) Shared.Swap(BitConverter.ToUInt32(buffer1, 0)) != (int) this.sizeOfHeader) if ((int)Shared.Swap(BitConverter.ToUInt32(buffer1, 0)) != (int)sizeOfHeader)
{
throw new Exception("Invalid Header Size!"); throw new Exception("Invalid Header Size!");
}
headerStream.Read(buffer1, 0, 4); headerStream.Read(buffer1, 0, 4);
this.unknown = Shared.Swap(BitConverter.ToUInt32(buffer1, 0)); unknown = Shared.Swap(BitConverter.ToUInt32(buffer1, 0));
headerStream.Read(buffer1, 0, 4); headerStream.Read(buffer1, 0, 4);
this.iconSize = Shared.Swap(BitConverter.ToUInt32(buffer1, 0)); iconSize = Shared.Swap(BitConverter.ToUInt32(buffer1, 0));
headerStream.Read(buffer1, 0, 4); headerStream.Read(buffer1, 0, 4);
this.bannerSize = Shared.Swap(BitConverter.ToUInt32(buffer1, 0)); bannerSize = Shared.Swap(BitConverter.ToUInt32(buffer1, 0));
headerStream.Read(buffer1, 0, 4); headerStream.Read(buffer1, 0, 4);
this.soundSize = Shared.Swap(BitConverter.ToUInt32(buffer1, 0)); soundSize = Shared.Swap(BitConverter.ToUInt32(buffer1, 0));
headerStream.Read(buffer1, 0, 4); headerStream.Read(buffer1, 0, 4);
this.flags = Shared.Swap(BitConverter.ToUInt32(buffer1, 0)); flags = Shared.Swap(BitConverter.ToUInt32(buffer1, 0));
headerStream.Read(this.japaneseTitle, 0, this.japaneseTitle.Length); headerStream.Read(japaneseTitle, 0, japaneseTitle.Length);
headerStream.Read(this.englishTitle, 0, this.englishTitle.Length); headerStream.Read(englishTitle, 0, englishTitle.Length);
headerStream.Read(this.germanTitle, 0, this.germanTitle.Length); headerStream.Read(germanTitle, 0, germanTitle.Length);
headerStream.Read(this.frenchTitle, 0, this.frenchTitle.Length); headerStream.Read(frenchTitle, 0, frenchTitle.Length);
headerStream.Read(this.spanishTitle, 0, this.spanishTitle.Length); headerStream.Read(spanishTitle, 0, spanishTitle.Length);
headerStream.Read(this.italianTitle, 0, this.italianTitle.Length); headerStream.Read(italianTitle, 0, italianTitle.Length);
headerStream.Read(this.dutchTitle, 0, this.dutchTitle.Length); headerStream.Read(dutchTitle, 0, dutchTitle.Length);
headerStream.Read(this.unknownTitle1, 0, this.unknownTitle1.Length); headerStream.Read(unknownTitle1, 0, unknownTitle1.Length);
headerStream.Read(this.unknownTitle2, 0, this.unknownTitle2.Length); headerStream.Read(unknownTitle2, 0, unknownTitle2.Length);
headerStream.Read(this.koreanTitle, 0, this.koreanTitle.Length); headerStream.Read(koreanTitle, 0, koreanTitle.Length);
headerStream.Read(this.padding2, 0, this.padding2.Length); headerStream.Read(padding2, 0, padding2.Length);
headerStream.Read(this.hash, 0, this.hash.Length); headerStream.Read(this.hash, 0, this.hash.Length);
headerStream.Seek(-16L, SeekOrigin.Current); headerStream.Seek(-16L, SeekOrigin.Current);
headerStream.Write(new byte[16], 0, 16); headerStream.Write(new byte[16], 0, 16);
@ -531,12 +591,12 @@ namespace libWiiSharp
headerStream.Seek(0L, SeekOrigin.Begin); headerStream.Seek(0L, SeekOrigin.Begin);
headerStream.Read(buffer2, 0, buffer2.Length); headerStream.Read(buffer2, 0, buffer2.Length);
MD5 md5 = MD5.Create(); MD5 md5 = MD5.Create();
byte[] hash = md5.ComputeHash(buffer2, !this.isShortImet ? 64 : 0, 1536); byte[] hash = md5.ComputeHash(buffer2, !isShortImet ? 64 : 0, 1536);
md5.Clear(); md5.Clear();
this.hashesMatch = Shared.CompareByteArrays(hash, this.hash); hashesMatch = Shared.CompareByteArrays(hash, this.hash);
} }
private string returnTitleAsString(byte[] title) private string ReturnTitleAsString(byte[] title)
{ {
string empty = string.Empty; string empty = string.Empty;
for (int index = 0; index < 84; index += 2) for (int index = 0; index < 84; index += 2)
@ -547,12 +607,14 @@ namespace libWiiSharp
title[index] title[index]
}, 0); }, 0);
if (ch != char.MinValue) if (ch != char.MinValue)
empty += ch.ToString(); {
empty += ch.ToString();
}
} }
return empty; return empty;
} }
private void setTitleFromString(string title, int titleIndex) private void SetTitleFromString(string title, int titleIndex)
{ {
byte[] numArray = new byte[84]; byte[] numArray = new byte[84];
for (int index = 0; index < title.Length; ++index) for (int index = 0; index < title.Length; ++index)
@ -564,28 +626,28 @@ namespace libWiiSharp
switch (titleIndex) switch (titleIndex)
{ {
case 0: case 0:
this.japaneseTitle = numArray; japaneseTitle = numArray;
break; break;
case 1: case 1:
this.englishTitle = numArray; englishTitle = numArray;
break; break;
case 2: case 2:
this.germanTitle = numArray; germanTitle = numArray;
break; break;
case 3: case 3:
this.frenchTitle = numArray; frenchTitle = numArray;
break; break;
case 4: case 4:
this.spanishTitle = numArray; spanishTitle = numArray;
break; break;
case 5: case 5:
this.italianTitle = numArray; italianTitle = numArray;
break; break;
case 6: case 6:
this.dutchTitle = numArray; dutchTitle = numArray;
break; break;
case 7: case 7:
this.koreanTitle = numArray; koreanTitle = numArray;
break; break;
} }
} }
@ -594,24 +656,24 @@ namespace libWiiSharp
public class IMD5 public class IMD5
{ {
private uint imd5Magic = 1229800501; private readonly uint imd5Magic = 1229800501;
private uint fileSize; private uint fileSize;
private byte[] padding = new byte[8]; private readonly byte[] padding = new byte[8];
private byte[] hash = new byte[16]; private byte[] hash = new byte[16];
/// <summary> /// <summary>
/// The size of the file without the IMD5 Header. /// The size of the file without the IMD5 Header.
/// </summary> /// </summary>
public uint FileSize => this.fileSize; public uint FileSize => fileSize;
/// <summary> /// <summary>
/// The hash of the file without the IMD5 Header. /// The hash of the file without the IMD5 Header.
/// </summary> /// </summary>
public byte[] Hash => this.hash; public byte[] Hash => hash;
private IMD5() private IMD5()
{ {
} }
#region Public Functions #region Public Functions
/// <summary> /// <summary>
@ -619,7 +681,10 @@ namespace libWiiSharp
/// </summary> /// </summary>
/// <param name="pathToFile"></param> /// <param name="pathToFile"></param>
/// <returns></returns> /// <returns></returns>
public static Headers.IMD5 Load(string pathToFile) => Headers.IMD5.Load(File.ReadAllBytes(pathToFile)); public static Headers.IMD5 Load(string pathToFile)
{
return Headers.IMD5.Load(File.ReadAllBytes(pathToFile));
}
/// <summary> /// <summary>
/// Loads the IMD5 Header of a byte array. /// Loads the IMD5 Header of a byte array.
@ -629,12 +694,15 @@ namespace libWiiSharp
public static Headers.IMD5 Load(byte[] fileOrHeader) public static Headers.IMD5 Load(byte[] fileOrHeader)
{ {
if (Headers.DetectHeader(fileOrHeader) != Headers.HeaderType.IMD5) if (Headers.DetectHeader(fileOrHeader) != Headers.HeaderType.IMD5)
{
throw new Exception("No IMD5 Header found!"); throw new Exception("No IMD5 Header found!");
}
Headers.IMD5 imD5 = new Headers.IMD5(); Headers.IMD5 imD5 = new Headers.IMD5();
MemoryStream memoryStream = new MemoryStream(fileOrHeader); MemoryStream memoryStream = new MemoryStream(fileOrHeader);
try try
{ {
imD5.parseHeader((Stream) memoryStream); imD5.ParseHeader(memoryStream);
} }
catch catch
{ {
@ -653,9 +721,12 @@ namespace libWiiSharp
public static Headers.IMD5 Load(Stream fileOrHeader) public static Headers.IMD5 Load(Stream fileOrHeader)
{ {
if (Headers.DetectHeader(fileOrHeader) != Headers.HeaderType.IMD5) if (Headers.DetectHeader(fileOrHeader) != Headers.HeaderType.IMD5)
{
throw new Exception("No IMD5 Header found!"); throw new Exception("No IMD5 Header found!");
}
Headers.IMD5 imD5 = new Headers.IMD5(); Headers.IMD5 imD5 = new Headers.IMD5();
imD5.parseHeader(fileOrHeader); imD5.ParseHeader(fileOrHeader);
return imD5; return imD5;
} }
@ -666,9 +737,11 @@ namespace libWiiSharp
/// <returns></returns> /// <returns></returns>
public static Headers.IMD5 Create(byte[] file) public static Headers.IMD5 Create(byte[] file)
{ {
Headers.IMD5 imD5 = new Headers.IMD5(); IMD5 imD5 = new IMD5
imD5.fileSize = (uint) file.Length; {
imD5.computeHash(file); fileSize = (uint)file.Length
};
imD5.ComputeHash(file);
return imD5; return imD5;
} }
@ -680,8 +753,8 @@ namespace libWiiSharp
{ {
byte[] buffer = Headers.IMD5.AddHeader(File.ReadAllBytes(pathToFile)); byte[] buffer = Headers.IMD5.AddHeader(File.ReadAllBytes(pathToFile));
File.Delete(pathToFile); File.Delete(pathToFile);
using (FileStream fileStream = new FileStream(pathToFile, FileMode.Create)) using FileStream fileStream = new FileStream(pathToFile, FileMode.Create);
fileStream.Write(buffer, 0, buffer.Length); fileStream.Write(buffer, 0, buffer.Length);
} }
/// <summary> /// <summary>
@ -694,7 +767,7 @@ namespace libWiiSharp
Headers.IMD5 imD5 = Headers.IMD5.Create(file); Headers.IMD5 imD5 = Headers.IMD5.Create(file);
MemoryStream memoryStream1 = new MemoryStream(); MemoryStream memoryStream1 = new MemoryStream();
MemoryStream memoryStream2 = memoryStream1; MemoryStream memoryStream2 = memoryStream1;
imD5.writeToStream((Stream) memoryStream2); imD5.WriteToStream(memoryStream2);
memoryStream1.Write(file, 0, file.Length); memoryStream1.Write(file, 0, file.Length);
byte[] array = memoryStream1.ToArray(); byte[] array = memoryStream1.ToArray();
memoryStream1.Dispose(); memoryStream1.Dispose();
@ -709,8 +782,8 @@ namespace libWiiSharp
{ {
byte[] buffer = Headers.IMD5.RemoveHeader(File.ReadAllBytes(pathToFile)); byte[] buffer = Headers.IMD5.RemoveHeader(File.ReadAllBytes(pathToFile));
File.Delete(pathToFile); File.Delete(pathToFile);
using (FileStream fileStream = new FileStream(pathToFile, FileMode.Create)) using FileStream fileStream = new FileStream(pathToFile, FileMode.Create);
fileStream.Write(buffer, 0, buffer.Length); fileStream.Write(buffer, 0, buffer.Length);
} }
/// <summary> /// <summary>
@ -736,7 +809,7 @@ namespace libWiiSharp
MemoryStream memoryStream = new MemoryStream(); MemoryStream memoryStream = new MemoryStream();
try try
{ {
this.writeToStream((Stream) memoryStream); WriteToStream(memoryStream);
return memoryStream; return memoryStream;
} }
catch catch
@ -750,43 +823,52 @@ namespace libWiiSharp
/// Returns the IMD5 Header as a byte array. /// Returns the IMD5 Header as a byte array.
/// </summary> /// </summary>
/// <returns></returns> /// <returns></returns>
public byte[] ToByteArray() => this.ToMemoryStream().ToArray(); public byte[] ToByteArray()
{
return ToMemoryStream().ToArray();
}
/// <summary> /// <summary>
/// Writes the IMD5 Header to the given stream. /// Writes the IMD5 Header to the given stream.
/// </summary> /// </summary>
/// <param name="writeStream"></param> /// <param name="writeStream"></param>
public void Write(Stream writeStream) => this.writeToStream(writeStream); public void Write(Stream writeStream)
{
WriteToStream(writeStream);
}
#endregion #endregion
#region Private Functions #region Private Functions
private void writeToStream(Stream writeStream) private void WriteToStream(Stream writeStream)
{ {
writeStream.Seek(0L, SeekOrigin.Begin); writeStream.Seek(0L, SeekOrigin.Begin);
writeStream.Write(BitConverter.GetBytes(Shared.Swap(this.imd5Magic)), 0, 4); writeStream.Write(BitConverter.GetBytes(Shared.Swap(imd5Magic)), 0, 4);
writeStream.Write(BitConverter.GetBytes(Shared.Swap(this.fileSize)), 0, 4); writeStream.Write(BitConverter.GetBytes(Shared.Swap(fileSize)), 0, 4);
writeStream.Write(this.padding, 0, this.padding.Length); writeStream.Write(padding, 0, padding.Length);
writeStream.Write(this.hash, 0, this.hash.Length); writeStream.Write(hash, 0, hash.Length);
} }
private void computeHash(byte[] bytesToHash) private void ComputeHash(byte[] bytesToHash)
{ {
MD5 md5 = MD5.Create(); MD5 md5 = MD5.Create();
this.hash = md5.ComputeHash(bytesToHash); hash = md5.ComputeHash(bytesToHash);
md5.Clear(); md5.Clear();
} }
private void parseHeader(Stream headerStream) private void ParseHeader(Stream headerStream)
{ {
headerStream.Seek(0L, SeekOrigin.Begin); headerStream.Seek(0L, SeekOrigin.Begin);
byte[] buffer = new byte[4]; byte[] buffer = new byte[4];
headerStream.Read(buffer, 0, 4); headerStream.Read(buffer, 0, 4);
if ((int) Shared.Swap(BitConverter.ToUInt32(buffer, 0)) != (int) this.imd5Magic) if ((int)Shared.Swap(BitConverter.ToUInt32(buffer, 0)) != (int)imd5Magic)
throw new Exception("Invalid Magic!"); {
throw new Exception("Invalid Magic!");
}
headerStream.Read(buffer, 0, 4); headerStream.Read(buffer, 0, 4);
this.fileSize = Shared.Swap(BitConverter.ToUInt32(buffer, 0)); fileSize = Shared.Swap(BitConverter.ToUInt32(buffer, 0));
headerStream.Read(this.padding, 0, this.padding.Length); headerStream.Read(padding, 0, padding.Length);
headerStream.Read(this.hash, 0, this.hash.Length); headerStream.Read(hash, 0, hash.Length);
} }
#endregion #endregion
} }

View file

@ -34,33 +34,6 @@ namespace libWiiSharp
private static string savedValue; private static string savedValue;
#region Public Functions #region Public Functions
/// <summary>
/// Displays the byte array like a hex editor in a ListView.
/// Columns will be created, estimated width is ~685 px.
/// Big files (25kB ++) will take quite a long time, so don't use this for big files.
/// </summary>
/// <param name="data"></param>
/// <param name="listView"></param>
public static void DumpToListView(byte[] data, ListView listView) => HexView.dumpToListView(data, listView);
/// <summary>
/// Displays the byte array like a hex editor in a DataGridView.
/// Columns will be created, estimated width is ~685 px.
/// Big files (25kB ++) will take quite a long time, so don't use this for big files.
/// </summary>
/// <param name="data"></param>
/// <param name="dataGridView"></param>
public static void DumpToDataGridView(byte[] data, DataGridView dataGridView) => HexView.dumpToDataGridView(data, dataGridView);
/// <summary>
/// Dumps a DataGridView back to a byte array.
/// The DataGridView must have the right format.
/// Big files (25kB ++) will take quite a long time, so don't use this for big files.
/// </summary>
/// <param name="dataGridView"></param>
/// <returns></returns>
public static byte[] DumpFromDataGridView(DataGridView dataGridView) => HexView.dumpFromDataGridView(dataGridView);
/// <summary> /// <summary>
/// Displays the byte array like a hex editor in a RichTextBox. /// Displays the byte array like a hex editor in a RichTextBox.
/// Big files (25kB ++) will take quite a long time, so don't use this for big files. /// Big files (25kB ++) will take quite a long time, so don't use this for big files.
@ -89,15 +62,6 @@ namespace libWiiSharp
textBox.Text = HexView.DumpAsString(data).Replace("\n", "\r\n"); textBox.Text = HexView.DumpAsString(data).Replace("\n", "\r\n");
} }
/// <summary>
/// Displays the byte array like a hex editor as a string array.
/// Be sure to use "Courier New" as a font, so every char has the same width.
/// Big files (25kB ++) will take quite a long time, so don't use this for big files.
/// </summary>
/// <param name="data"></param>
/// <returns></returns>
public static string[] DumpAsStringArray(byte[] data) => HexView.dumpAsStringArray(data);
/// <summary> /// <summary>
/// Displays the byte array like a hex editor as a string. /// Displays the byte array like a hex editor as a string.
/// Be sure to use "Courier New" as a font, so every char has the same width. /// Be sure to use "Courier New" as a font, so every char has the same width.
@ -105,7 +69,10 @@ namespace libWiiSharp
/// </summary> /// </summary>
/// <param name="data"></param> /// <param name="data"></param>
/// <returns></returns> /// <returns></returns>
public static string DumpAsString(byte[] data) => string.Join("\n", HexView.dumpAsStringArray(data)); public static string DumpAsString(byte[] data)
{
return string.Join("\n", HexView.DumpAsStringArray(data));
}
/// <summary> /// <summary>
/// Link your DataGridView's CellEndEdit event with this function. /// Link your DataGridView's CellEndEdit event with this function.
@ -121,32 +88,46 @@ namespace libWiiSharp
DataGridView dataGridView = sender as DataGridView; DataGridView dataGridView = sender as DataGridView;
if (dataGridView.Columns[e.ColumnIndex].HeaderText.ToLower() == "dump") if (dataGridView.Columns[e.ColumnIndex].HeaderText.ToLower() == "dump")
{ {
string str = (string) dataGridView.Rows[e.RowIndex].Cells[17].Value; string str = (string)dataGridView.Rows[e.RowIndex].Cells[17].Value;
if (!(str != HexView.savedValue)) if (!(str != HexView.savedValue))
{
return; return;
}
if (str.Length != 16) if (str.Length != 16)
{
throw new Exception(); throw new Exception();
}
for (int index = 0; index < 16; ++index) for (int index = 0; index < 16; ++index)
{ {
if ((int) HexView.toAscii(byte.Parse((string) dataGridView.Rows[e.RowIndex].Cells[index + 1].Value, NumberStyles.HexNumber)) != (int) str[index]) if (HexView.ToAscii(byte.Parse((string)dataGridView.Rows[e.RowIndex].Cells[index + 1].Value, NumberStyles.HexNumber)) != str[index])
dataGridView.Rows[e.RowIndex].Cells[index + 1].Value = (object) HexView.fromAscii(str[index]).ToString("x2"); {
dataGridView.Rows[e.RowIndex].Cells[index + 1].Value = HexView.FromAscii(str[index]).ToString("x2");
}
} }
} }
else else
{ {
if (((string) dataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Value).Length == 1) if (((string)dataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Value).Length == 1)
dataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = (object) ("0" + dataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Value?.ToString()); {
dataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = "0" + dataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Value?.ToString();
}
int startIndex = int.Parse(dataGridView.Columns[e.ColumnIndex].HeaderText, NumberStyles.HexNumber); int startIndex = int.Parse(dataGridView.Columns[e.ColumnIndex].HeaderText, NumberStyles.HexNumber);
string str = ((string) dataGridView.Rows[e.RowIndex].Cells[17].Value).Remove(startIndex, 1).Insert(startIndex, HexView.toAscii(byte.Parse((string) dataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Value, NumberStyles.HexNumber)).ToString()); string str = ((string)dataGridView.Rows[e.RowIndex].Cells[17].Value).Remove(startIndex, 1).Insert(startIndex, HexView.ToAscii(byte.Parse((string)dataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Value, NumberStyles.HexNumber)).ToString());
dataGridView.Rows[e.RowIndex].Cells[17].Value = (object) str; dataGridView.Rows[e.RowIndex].Cells[17].Value = str;
if (((string) dataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Value).Length <= 2) if (((string)dataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Value).Length <= 2)
{
return; return;
dataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = (object) ((string) dataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Value).Remove(0, ((string) dataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Value).Length - 2); }
dataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = ((string)dataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Value).Remove(0, ((string)dataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Value).Length - 2);
} }
} }
catch catch
{ {
((DataGridView) sender).Rows[e.RowIndex].Cells[e.ColumnIndex].Value = (object) HexView.savedValue; ((DataGridView)sender).Rows[e.RowIndex].Cells[e.ColumnIndex].Value = savedValue;
} }
} }
@ -157,17 +138,26 @@ namespace libWiiSharp
/// </summary> /// </summary>
/// <param name="sender"></param> /// <param name="sender"></param>
/// <param name="e"></param> /// <param name="e"></param>
public static void DataGridView_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e) => HexView.savedValue = (string) ((DataGridView) sender).Rows[e.RowIndex].Cells[e.ColumnIndex].Value; public static void DataGridView_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
{
HexView.savedValue = (string)((DataGridView)sender).Rows[e.RowIndex].Cells[e.ColumnIndex].Value;
}
#endregion #endregion
#region Private Functions #region Private Functions
private static string[] dumpAsStringArray(byte[] data) /// <summary>
/// Displays the byte array like a hex editor as a string array.
/// Be sure to use "Courier New" as a font, so every char has the same width.
/// Big files (25kB ++) will take quite a long time, so don't use this for big files.
/// </summary>
/// <param name="data"></param>
/// <returns></returns>
private static string[] DumpAsStringArray(byte[] data)
{ {
List<string> stringList = new List<string>(); List<string> stringList = new List<string>();
string empty = string.Empty;
int num; int num;
char ascii; char ascii;
for (num = 0; (double) (data.Length - num) / 16.0 >= 1.0; num += 16) for (num = 0; (data.Length - num) / 16.0 >= 1.0; num += 16)
{ {
string str1 = string.Empty + num.ToString("x8") + " "; string str1 = string.Empty + num.ToString("x8") + " ";
string str2 = string.Empty; string str2 = string.Empty;
@ -175,7 +165,7 @@ namespace libWiiSharp
{ {
str1 = str1 + data[num + index].ToString("x2") + " "; str1 = str1 + data[num + index].ToString("x2") + " ";
string str3 = str2; string str3 = str2;
ascii = HexView.toAscii(data[num + index]); ascii = HexView.ToAscii(data[num + index]);
string str4 = ascii.ToString(); string str4 = ascii.ToString();
str2 = str3 + str4; str2 = str3 + str4;
} }
@ -192,33 +182,43 @@ namespace libWiiSharp
{ {
str1 = str1 + data[num + index].ToString("x2") + " "; str1 = str1 + data[num + index].ToString("x2") + " ";
string str3 = str2; string str3 = str2;
ascii = HexView.toAscii(data[num + index]); ascii = HexView.ToAscii(data[num + index]);
string str4 = ascii.ToString(); string str4 = ascii.ToString();
str2 = str3 + str4; str2 = str3 + str4;
} }
else else
{
str1 += " "; str1 += " ";
}
} }
string str5 = str1 + " " + str2; string str5 = str1 + " " + str2;
stringList.Add(str5); stringList.Add(str5);
} }
return stringList.ToArray(); return stringList.ToArray();
} }
// Unused
private static byte[] dumpFromDataGridView(DataGridView dataGridView) /*
/// <summary>
/// Dumps a DataGridView back to a byte array.
/// The DataGridView must have the right format.
/// Big files (25kB ++) will take quite a long time, so don't use this for big files.
/// </summary>
/// <param name="dataGridView"></param>
/// <returns></returns>
private static byte[] DumpFromDataGridView(DataGridView dataGridView)
{ {
try try
{ {
List<byte> byteList = new List<byte>(); List<byte> byteList = new List<byte>();
for (int index1 = 0; !string.IsNullOrEmpty((string) dataGridView.Rows[index1].Cells[1].Value); ++index1) for (int index1 = 0; !string.IsNullOrEmpty((string)dataGridView.Rows[index1].Cells[1].Value); ++index1)
{ {
for (int index2 = 0; index2 < 16; ++index2) for (int index2 = 0; index2 < 16; ++index2)
{ {
if (!string.IsNullOrEmpty((string) dataGridView.Rows[index1].Cells[index2 + 1].Value)) if (!string.IsNullOrEmpty((string)dataGridView.Rows[index1].Cells[index2 + 1].Value))
byteList.Add(byte.Parse((string) dataGridView.Rows[index1].Cells[index2 + 1].Value, NumberStyles.HexNumber)); byteList.Add(byte.Parse((string)dataGridView.Rows[index1].Cells[index2 + 1].Value, NumberStyles.HexNumber));
} }
if (index1 == dataGridView.Rows.Count - 1) if (index1 == dataGridView.Rows.Count - 1)
break; break;
} }
return byteList.ToArray(); return byteList.ToArray();
} }
@ -228,7 +228,14 @@ namespace libWiiSharp
} }
} }
private static void dumpToDataGridView(byte[] data, DataGridView dataGridView) /// <summary>
/// Displays the byte array like a hex editor in a DataGridView.
/// Columns will be created, estimated width is ~685 px.
/// Big files (25kB ++) will take quite a long time, so don't use this for big files.
/// </summary>
/// <param name="data"></param>
/// <param name="dataGridView"></param>
private static void DumpToDataGridView(byte[] data, DataGridView dataGridView)
{ {
dataGridView.Columns.Clear(); dataGridView.Columns.Clear();
dataGridView.Rows.Clear(); dataGridView.Rows.Clear();
@ -237,63 +244,70 @@ namespace libWiiSharp
{ {
HeaderText = "Offset", HeaderText = "Offset",
Width = 80, Width = 80,
CellTemplate = (DataGridViewCell) new DataGridViewTextBoxCell() CellTemplate = (DataGridViewCell)new DataGridViewTextBoxCell()
}); });
for (int index = 0; index < 16; ++index) for (int index = 0; index < 16; ++index)
dataGridView.Columns.Add(new DataGridViewColumn() dataGridView.Columns.Add(new DataGridViewColumn()
{ {
HeaderText = index.ToString("x1"), HeaderText = index.ToString("x1"),
Width = 30, Width = 30,
CellTemplate = (DataGridViewCell) new DataGridViewTextBoxCell() CellTemplate = (DataGridViewCell)new DataGridViewTextBoxCell()
});
dataGridView.Columns.Add(new DataGridViewColumn()
{
HeaderText = "Dump",
Width = 125,
CellTemplate = (DataGridViewCell) new DataGridViewTextBoxCell()
}); });
dataGridView.Columns.Add(new DataGridViewColumn()
{
HeaderText = "Dump",
Width = 125,
CellTemplate = (DataGridViewCell)new DataGridViewTextBoxCell()
});
int num; int num;
for (num = 0; (double) (data.Length - num) / 16.0 >= 1.0; num += 16) for (num = 0; (double)(data.Length - num) / 16.0 >= 1.0; num += 16)
{ {
DataGridViewRow dataGridViewRow = new DataGridViewRow(); DataGridViewRow dataGridViewRow = new DataGridViewRow();
int index1 = dataGridViewRow.Cells.Add((DataGridViewCell) new DataGridViewTextBoxCell()); int index1 = dataGridViewRow.Cells.Add((DataGridViewCell)new DataGridViewTextBoxCell());
dataGridViewRow.Cells[index1].Value = (object) num.ToString("x8"); dataGridViewRow.Cells[index1].Value = (object)num.ToString("x8");
dataGridViewRow.Cells[index1].ReadOnly = true; dataGridViewRow.Cells[index1].ReadOnly = true;
string empty = string.Empty; string empty = string.Empty;
for (int index2 = 0; index2 < 16; ++index2) for (int index2 = 0; index2 < 16; ++index2)
{ {
int index3 = dataGridViewRow.Cells.Add((DataGridViewCell) new DataGridViewTextBoxCell()); int index3 = dataGridViewRow.Cells.Add((DataGridViewCell)new DataGridViewTextBoxCell());
dataGridViewRow.Cells[index3].Value = (object) data[num + index2].ToString("x2"); dataGridViewRow.Cells[index3].Value = (object)data[num + index2].ToString("x2");
empty += HexView.toAscii(data[num + index2]).ToString(); empty += HexView.ToAscii(data[num + index2]).ToString();
} }
int index4 = dataGridViewRow.Cells.Add((DataGridViewCell) new DataGridViewTextBoxCell()); int index4 = dataGridViewRow.Cells.Add((DataGridViewCell)new DataGridViewTextBoxCell());
dataGridViewRow.Cells[index4].Value = (object) empty; dataGridViewRow.Cells[index4].Value = (object)empty;
dataGridView.Rows.Add(dataGridViewRow); dataGridView.Rows.Add(dataGridViewRow);
} }
if (data.Length <= num) if (data.Length <= num)
return; return;
DataGridViewRow dataGridViewRow1 = new DataGridViewRow(); DataGridViewRow dataGridViewRow1 = new DataGridViewRow();
int index5 = dataGridViewRow1.Cells.Add((DataGridViewCell) new DataGridViewTextBoxCell()); int index5 = dataGridViewRow1.Cells.Add((DataGridViewCell)new DataGridViewTextBoxCell());
dataGridViewRow1.Cells[index5].Value = (object) num.ToString("x8"); dataGridViewRow1.Cells[index5].Value = (object)num.ToString("x8");
dataGridViewRow1.Cells[index5].ReadOnly = true; dataGridViewRow1.Cells[index5].ReadOnly = true;
string empty1 = string.Empty; string empty1 = string.Empty;
for (int index1 = 0; index1 < 16; ++index1) for (int index1 = 0; index1 < 16; ++index1)
{ {
if (index1 < data.Length - num) if (index1 < data.Length - num)
{ {
int index2 = dataGridViewRow1.Cells.Add((DataGridViewCell) new DataGridViewTextBoxCell()); int index2 = dataGridViewRow1.Cells.Add((DataGridViewCell)new DataGridViewTextBoxCell());
dataGridViewRow1.Cells[index2].Value = (object) data[num + index1].ToString("x2"); dataGridViewRow1.Cells[index2].Value = (object)data[num + index1].ToString("x2");
empty1 += HexView.toAscii(data[num + index1]).ToString(); empty1 += HexView.ToAscii(data[num + index1]).ToString();
} }
else else
dataGridViewRow1.Cells.Add((DataGridViewCell) new DataGridViewTextBoxCell()); dataGridViewRow1.Cells.Add((DataGridViewCell)new DataGridViewTextBoxCell());
} }
int index6 = dataGridViewRow1.Cells.Add((DataGridViewCell) new DataGridViewTextBoxCell()); int index6 = dataGridViewRow1.Cells.Add((DataGridViewCell)new DataGridViewTextBoxCell());
dataGridViewRow1.Cells[index6].Value = (object) empty1; dataGridViewRow1.Cells[index6].Value = (object)empty1;
dataGridView.Rows.Add(dataGridViewRow1); dataGridView.Rows.Add(dataGridViewRow1);
} }
private static void dumpToListView(byte[] data, ListView listView) /// <summary>
/// Displays the byte array like a hex editor in a ListView.
/// Columns will be created, estimated width is ~685 px.
/// Big files (25kB ++) will take quite a long time, so don't use this for big files.
/// </summary>
/// <param name="data"></param>
/// <param name="listView"></param>
private static void DumpToListView(byte[] data, ListView listView)
{ {
listView.Columns.Clear(); listView.Columns.Clear();
listView.Items.Clear(); listView.Items.Clear();
@ -304,14 +318,14 @@ namespace libWiiSharp
listView.Columns.Add(index.ToString("x1"), index.ToString("x1"), 30, HorizontalAlignment.Left, string.Empty); listView.Columns.Add(index.ToString("x1"), index.ToString("x1"), 30, HorizontalAlignment.Left, string.Empty);
listView.Columns.Add("Dump", "Dump", 125, HorizontalAlignment.Left, string.Empty); listView.Columns.Add("Dump", "Dump", 125, HorizontalAlignment.Left, string.Empty);
int num; int num;
for (num = 0; (double) (data.Length - num) / 16.0 >= 1.0; num += 16) for (num = 0; (double)(data.Length - num) / 16.0 >= 1.0; num += 16)
{ {
ListViewItem listViewItem = new ListViewItem(num.ToString("x8")); ListViewItem listViewItem = new ListViewItem(num.ToString("x8"));
string empty = string.Empty; string empty = string.Empty;
for (int index = 0; index < 16; ++index) for (int index = 0; index < 16; ++index)
{ {
listViewItem.SubItems.Add(data[num + index].ToString("x2")); listViewItem.SubItems.Add(data[num + index].ToString("x2"));
empty += HexView.toAscii(data[num + index]).ToString(); empty += HexView.ToAscii(data[num + index]).ToString();
} }
listViewItem.SubItems.Add(empty); listViewItem.SubItems.Add(empty);
listView.Items.Add(listViewItem); listView.Items.Add(listViewItem);
@ -325,7 +339,7 @@ namespace libWiiSharp
if (index < data.Length - num) if (index < data.Length - num)
{ {
listViewItem1.SubItems.Add(data[num + index].ToString("x2")); listViewItem1.SubItems.Add(data[num + index].ToString("x2"));
empty1 += HexView.toAscii(data[num + index]).ToString(); empty1 += HexView.ToAscii(data[num + index]).ToString();
} }
else else
listViewItem1.SubItems.Add(string.Empty); listViewItem1.SubItems.Add(string.Empty);
@ -333,10 +347,18 @@ namespace libWiiSharp
listViewItem1.SubItems.Add(empty1); listViewItem1.SubItems.Add(empty1);
listView.Items.Add(listViewItem1); listView.Items.Add(listViewItem1);
} }
*/
private static char toAscii(byte value) => value >= (byte) 32 && value <= (byte) 126 ? (char) value : '.';
private static byte fromAscii(char value) => (byte) value; private static char ToAscii(byte value)
{
return value >= 32 && value <= 126 ? (char)value : '.';
}
private static byte FromAscii(char value)
{
return (byte)value;
}
#endregion #endregion
} }
} }

View file

@ -37,8 +37,8 @@ namespace libWiiSharp
/// <param name="iosWad"></param> /// <param name="iosWad"></param>
public void LoadIOS(ref WAD iosWad) public void LoadIOS(ref WAD iosWad)
{ {
this.wadFile = iosWad; wadFile = iosWad;
this.getEsIndex(); GetEsIndex();
} }
/// <summary> /// <summary>
@ -46,262 +46,295 @@ namespace libWiiSharp
/// Returns the number of applied patches. /// Returns the number of applied patches.
/// </summary> /// </summary>
/// <returns></returns> /// <returns></returns>
public int PatchFakeSigning() => this.esIndex < 0 ? -1 : this.patchFakeSigning(ref this.wadFile.Contents[this.esIndex]); public int PatchFakeSigning()
{
return esIndex < 0 ? -1 : PrivPatchFakeSigning(ref wadFile.Contents[esIndex]);
}
/// <summary> /// <summary>
/// Patches es_identify. /// Patches es_identify.
/// Returns the number of applied patches. /// Returns the number of applied patches.
/// </summary> /// </summary>
/// <returns></returns> /// <returns></returns>
public int PatchEsIdentify() => this.esIndex < 0 ? -1 : this.patchEsIdentify(ref this.wadFile.Contents[this.esIndex]); public int PatchEsIdentify()
{
return esIndex < 0 ? -1 : PrivPatchEsIdentify(ref wadFile.Contents[esIndex]);
}
/// <summary> /// <summary>
/// Patches nand permissions. /// Patches nand permissions.
/// Returns the number of applied patches. /// Returns the number of applied patches.
/// </summary> /// </summary>
/// <returns></returns> /// <returns></returns>
public int PatchNandPermissions() => this.esIndex < 0 ? -1 : this.patchNandPermissions(ref this.wadFile.Contents[this.esIndex]); public int PatchNandPermissions()
{
return esIndex < 0 ? -1 : PrivPatchNandPermissions(ref wadFile.Contents[esIndex]);
}
public int PatchVP() => this.esIndex < 0 ? -1 : this.patchVP(ref this.wadFile.Contents[this.esIndex]); public int PatchVP()
{
return esIndex < 0 ? -1 : PrivPatchVP(ref wadFile.Contents[esIndex]);
}
/// <summary> /// <summary>
/// Patches fakesigning, es_identify and nand permissions. /// Patches fakesigning, es_identify and nand permissions.
/// Returns the number of applied patches. /// Returns the number of applied patches.
/// </summary> /// </summary>
/// <returns></returns> /// <returns></returns>
public int PatchAll() => this.esIndex < 0 ? -1 : this.patchAll(ref this.wadFile.Contents[this.esIndex]); public int PatchAll()
{
return esIndex < 0 ? -1 : PrivPatchAll(ref wadFile.Contents[esIndex]);
}
public int PatchFakeSigning(ref byte[] esModule) => this.patchFakeSigning(ref esModule); public int PatchFakeSigning(ref byte[] esModule)
{
return PatchFakeSigning(ref esModule);
}
public int PatchEsIdentify(ref byte[] esModule) => this.patchEsIdentify(ref esModule); public int PatchEsIdentify(ref byte[] esModule)
{
return PatchEsIdentify(ref esModule);
}
public int PatchNandPermissions(ref byte[] esModule) => this.patchNandPermissions(ref esModule); public int PatchNandPermissions(ref byte[] esModule)
{
return PrivPatchNandPermissions(ref esModule);
}
public int PatchVP(ref byte[] esModule) => this.patchVP(ref esModule); public int PatchVP(ref byte[] esModule)
{
return PrivPatchVP(ref esModule);
}
public int PatchAll(ref byte[] esModule) => this.patchAll(ref esModule); public int PatchAll(ref byte[] esModule)
{
return PrivPatchAll(ref esModule);
}
#endregion #endregion
#region Private Functions #region Private Functions
private int patchFakeSigning(ref byte[] esModule) private int PrivPatchFakeSigning(ref byte[] esModule)
{ {
this.fireDebug("Patching Fakesigning..."); FireDebug("Patching Fakesigning...");
int num = 0; int num = 0;
byte[] second1 = new byte[4] byte[] second1 = new byte[4]
{ {
(byte) 32, 32,
(byte) 7, 7,
(byte) 35, 35,
(byte) 162 162
}; };
byte[] second2 = new byte[4] byte[] second2 = new byte[4]
{ {
(byte) 32, 32,
(byte) 7, 7,
(byte) 75, 75,
(byte) 11 11
}; };
for (int firstIndex = 0; firstIndex < esModule.Length - 4; ++firstIndex) for (int firstIndex = 0; firstIndex < esModule.Length - 4; ++firstIndex)
{ {
this.fireProgress((firstIndex + 1) * 100 / esModule.Length); FireProgress((firstIndex + 1) * 100 / esModule.Length);
if (Shared.CompareByteArrays(esModule, firstIndex, second1, 0, 4) || Shared.CompareByteArrays(esModule, firstIndex, second2, 0, 4)) if (Shared.CompareByteArrays(esModule, firstIndex, second1, 0, 4) || Shared.CompareByteArrays(esModule, firstIndex, second2, 0, 4))
{ {
this.fireDebug(" Patching at Offset: 0x{0}", (object) firstIndex.ToString("x8").ToUpper()); FireDebug(" Patching at Offset: 0x{0}", (object)firstIndex.ToString("x8").ToUpper());
esModule[firstIndex + 1] = (byte) 0; esModule[firstIndex + 1] = 0;
firstIndex += 4; firstIndex += 4;
++num; ++num;
} }
} }
this.fireDebug("Patching Fakesigning Finished... (Patches applied: {0})", (object) num); FireDebug("Patching Fakesigning Finished... (Patches applied: {0})", (object)num);
return num;
}
private int patchEsIdentify(ref byte[] esModule)
{
this.fireDebug("Patching ES_Identify...");
int num = 0;
byte[] second = new byte[4]
{
(byte) 40,
(byte) 3,
(byte) 209,
(byte) 35
};
for (int firstIndex = 0; firstIndex < esModule.Length - 4; ++firstIndex)
{
this.fireProgress((firstIndex + 1) * 100 / esModule.Length);
if (Shared.CompareByteArrays(esModule, firstIndex, second, 0, 4))
{
this.fireDebug(" Patching at Offset: 0x{0}", (object) firstIndex.ToString("x8").ToUpper());
esModule[firstIndex + 2] = (byte) 0;
esModule[firstIndex + 3] = (byte) 0;
firstIndex += 4;
++num;
}
}
this.fireDebug("Patching ES_Identify Finished... (Patches applied: {0})", (object) num);
return num; return num;
} }
private int patchNandPermissions(ref byte[] esModule) private int PrivPatchEsIdentify(ref byte[] esModule)
{ {
this.fireDebug("Patching NAND Permissions..."); FireDebug("Patching ES_Identify...");
int num = 0;
byte[] second = new byte[4]
{
40,
3,
209,
35
};
for (int firstIndex = 0; firstIndex < esModule.Length - 4; ++firstIndex)
{
FireProgress((firstIndex + 1) * 100 / esModule.Length);
if (Shared.CompareByteArrays(esModule, firstIndex, second, 0, 4))
{
FireDebug(" Patching at Offset: 0x{0}", (object)firstIndex.ToString("x8").ToUpper());
esModule[firstIndex + 2] = 0;
esModule[firstIndex + 3] = 0;
firstIndex += 4;
++num;
}
}
FireDebug("Patching ES_Identify Finished... (Patches applied: {0})", (object)num);
return num;
}
private int PrivPatchNandPermissions(ref byte[] esModule)
{
FireDebug("Patching NAND Permissions...");
int num = 0; int num = 0;
byte[] second = new byte[6] byte[] second = new byte[6]
{ {
(byte) 66, 66,
(byte) 139, 139,
(byte) 208, 208,
(byte) 1, 1,
(byte) 37, 37,
(byte) 102 102
}; };
for (int firstIndex = 0; firstIndex < esModule.Length - 6; ++firstIndex) for (int firstIndex = 0; firstIndex < esModule.Length - 6; ++firstIndex)
{ {
this.fireProgress((firstIndex + 1) * 100 / esModule.Length); FireProgress((firstIndex + 1) * 100 / esModule.Length);
if (Shared.CompareByteArrays(esModule, firstIndex, second, 0, 6)) if (Shared.CompareByteArrays(esModule, firstIndex, second, 0, 6))
{ {
this.fireDebug(" Patching at Offset: 0x{0}", (object) firstIndex.ToString("x8").ToUpper()); FireDebug(" Patching at Offset: 0x{0}", (object)firstIndex.ToString("x8").ToUpper());
esModule[firstIndex + 2] = (byte) 224; esModule[firstIndex + 2] = 224;
firstIndex += 6; firstIndex += 6;
++num; ++num;
} }
} }
this.fireDebug("Patching NAND Permissions Finished... (Patches applied: {0})", (object) num); FireDebug("Patching NAND Permissions Finished... (Patches applied: {0})", (object)num);
return num; return num;
} }
private int patchVP(ref byte[] esModule) private int PrivPatchVP(ref byte[] esModule)
{ {
this.fireDebug("Patching VP..."); FireDebug("Patching VP...");
int num = 0; int num = 0;
byte[] second = new byte[4] byte[] second = new byte[4]
{ {
(byte) 210, 210,
(byte) 1, 1,
(byte) 78, 78,
(byte) 86 86
}; };
for (int firstIndex = 0; firstIndex < esModule.Length - 4; ++firstIndex) for (int firstIndex = 0; firstIndex < esModule.Length - 4; ++firstIndex)
{ {
this.fireProgress((firstIndex + 1) * 100 / esModule.Length); FireProgress((firstIndex + 1) * 100 / esModule.Length);
if (Shared.CompareByteArrays(esModule, firstIndex, second, 0, 4)) if (Shared.CompareByteArrays(esModule, firstIndex, second, 0, 4))
{ {
this.fireDebug(" Patching for VP at Offset: 0x{0}", (object) firstIndex.ToString("x8").ToUpper()); FireDebug(" Patching for VP at Offset: 0x{0}", (object)firstIndex.ToString("x8").ToUpper());
esModule[firstIndex] = (byte) 224; esModule[firstIndex] = 224;
firstIndex += 4; firstIndex += 4;
++num; ++num;
} }
} }
this.fireDebug("Patching VP Finished... (Patches applied: {0})", (object) num); FireDebug("Patching VP Finished... (Patches applied: {0})", (object)num);
return num; return num;
} }
private int patchAll(ref byte[] esModule) private int PrivPatchAll(ref byte[] esModule)
{ {
this.fireDebug("Patching Fakesigning, ES_Identify, NAND Permissions and VP ..."); FireDebug("Patching Fakesigning, ES_Identify, NAND Permissions and VP ...");
int num = 0; int num = 0;
byte[] second1 = new byte[4] byte[] second1 = new byte[4]
{ {
(byte) 32, 32,
(byte) 7, 7,
(byte) 35, 35,
(byte) 162 162
}; };
byte[] second2 = new byte[4] byte[] second2 = new byte[4]
{ {
(byte) 32, 32,
(byte) 7, 7,
(byte) 75, 75,
(byte) 11 11
}; };
byte[] second3 = new byte[4] byte[] second3 = new byte[4]
{ {
(byte) 40, 40,
(byte) 3, 3,
(byte) 209, 209,
(byte) 35 35
}; };
byte[] second4 = new byte[6] byte[] second4 = new byte[6]
{ {
(byte) 66, 66,
(byte) 139, 139,
(byte) 208, 208,
(byte) 1, 1,
(byte) 37, 37,
(byte) 102 102
}; };
byte[] second5 = new byte[4] byte[] second5 = new byte[4]
{ {
(byte) 210, 210,
(byte) 1, 1,
(byte) 78, 78,
(byte) 86 86
}; };
for (int firstIndex = 0; firstIndex < esModule.Length - 6; ++firstIndex) for (int firstIndex = 0; firstIndex < esModule.Length - 6; ++firstIndex)
{ {
this.fireProgress((firstIndex + 1) * 100 / esModule.Length); FireProgress((firstIndex + 1) * 100 / esModule.Length);
if (Shared.CompareByteArrays(esModule, firstIndex, second1, 0, 4) || Shared.CompareByteArrays(esModule, firstIndex, second2, 0, 4)) if (Shared.CompareByteArrays(esModule, firstIndex, second1, 0, 4) || Shared.CompareByteArrays(esModule, firstIndex, second2, 0, 4))
{ {
this.fireDebug(" Patching Fakesigning at Offset: 0x{0}", (object) firstIndex.ToString("x8").ToUpper()); FireDebug(" Patching Fakesigning at Offset: 0x{0}", (object)firstIndex.ToString("x8").ToUpper());
esModule[firstIndex + 1] = (byte) 0; esModule[firstIndex + 1] = 0;
firstIndex += 4; firstIndex += 4;
++num; ++num;
} }
else if (Shared.CompareByteArrays(esModule, firstIndex, second3, 0, 4)) else if (Shared.CompareByteArrays(esModule, firstIndex, second3, 0, 4))
{ {
this.fireDebug(" Patching ES_Identify at Offset: 0x{0}", (object) firstIndex.ToString("x8").ToUpper()); FireDebug(" Patching ES_Identify at Offset: 0x{0}", (object)firstIndex.ToString("x8").ToUpper());
esModule[firstIndex + 2] = (byte) 0; esModule[firstIndex + 2] = 0;
esModule[firstIndex + 3] = (byte) 0; esModule[firstIndex + 3] = 0;
firstIndex += 4; firstIndex += 4;
++num; ++num;
} }
else if (Shared.CompareByteArrays(esModule, firstIndex, second4, 0, 6)) else if (Shared.CompareByteArrays(esModule, firstIndex, second4, 0, 6))
{ {
this.fireDebug(" Patching NAND Permissions at Offset: 0x{0}", (object) firstIndex.ToString("x8").ToUpper()); FireDebug(" Patching NAND Permissions at Offset: 0x{0}", (object)firstIndex.ToString("x8").ToUpper());
esModule[firstIndex + 2] = (byte) 224; esModule[firstIndex + 2] = 224;
firstIndex += 6; firstIndex += 6;
++num; ++num;
} }
else if (Shared.CompareByteArrays(esModule, firstIndex, second5, 0, 4)) else if (Shared.CompareByteArrays(esModule, firstIndex, second5, 0, 4))
{ {
this.fireDebug(" Patching VP at Offset: 0x{0}", (object) firstIndex.ToString("x8").ToUpper()); FireDebug(" Patching VP at Offset: 0x{0}", (object)firstIndex.ToString("x8").ToUpper());
esModule[firstIndex] = (byte) 224; esModule[firstIndex] = 224;
firstIndex += 4; firstIndex += 4;
++num; ++num;
} }
} }
this.fireDebug("Patching Fakesigning, ES_Identify, NAND Permissions and VP Finished... (Patches applied: {0})", (object) num); FireDebug("Patching Fakesigning, ES_Identify, NAND Permissions and VP Finished... (Patches applied: {0})", (object)num);
return num; return num;
} }
private void getEsIndex() private void GetEsIndex()
{ {
this.fireDebug("Scanning for ES Module..."); FireDebug("Scanning for ES Module...");
string str = "$IOSVersion:"; string str = "$IOSVersion:";
for (int index1 = this.wadFile.NumOfContents - 1; index1 >= 0; --index1) for (int index1 = wadFile.NumOfContents - 1; index1 >= 0; --index1)
{ {
this.fireDebug(" Scanning Content #{0} of {1}...", (object) (index1 + 1), (object) this.wadFile.NumOfContents); FireDebug(" Scanning Content #{0} of {1}...", index1 + 1, wadFile.NumOfContents);
this.fireProgress((index1 + 1) * 100 / this.wadFile.NumOfContents); FireProgress((index1 + 1) * 100 / wadFile.NumOfContents);
for (int index2 = 0; index2 < this.wadFile.Contents[index1].Length - 64; ++index2) for (int index2 = 0; index2 < wadFile.Contents[index1].Length - 64; ++index2)
{ {
if (Encoding.ASCII.GetString(this.wadFile.Contents[index1], index2, 12) == str) if (Encoding.ASCII.GetString(wadFile.Contents[index1], index2, 12) == str)
{ {
int index3 = index2 + 12; int index3 = index2 + 12;
while (this.wadFile.Contents[index1][index3] == (byte) 32) while (wadFile.Contents[index1][index3] == 32)
++index3;
if (Encoding.ASCII.GetString(this.wadFile.Contents[index1], index3, 3) == "ES:")
{ {
this.fireDebug(" -> ES Module found!"); ++index3;
this.fireDebug("Scanning for ES Module Finished..."); }
this.esIndex = index1;
this.fireProgress(100); if (Encoding.ASCII.GetString(wadFile.Contents[index1], index3, 3) == "ES:")
{
FireDebug(" -> ES Module found!");
FireDebug("Scanning for ES Module Finished...");
esIndex = index1;
FireProgress(100);
return; return;
} }
} }
} }
} }
this.fireDebug("/!\\/!\\/!\\ ES Module wasn't found! /!\\/!\\/!\\"); FireDebug("/!\\/!\\/!\\ ES Module wasn't found! /!\\/!\\/!\\");
throw new Exception("ES module wasn't found!"); throw new Exception("ES module wasn't found!");
} }
#endregion #endregion
@ -315,20 +348,26 @@ namespace libWiiSharp
/// Fires debugging messages. You may write them into a log file or log textbox. /// Fires debugging messages. You may write them into a log file or log textbox.
/// </summary> /// </summary>
public event EventHandler<MessageEventArgs> Debug; public event EventHandler<MessageEventArgs> Debug;
private void fireDebug(string debugMessage, params object[] args) private void FireDebug(string debugMessage, params object[] args)
{ {
EventHandler<MessageEventArgs> debug = this.Debug; EventHandler<MessageEventArgs> debug = Debug;
if (debug == null) if (debug == null)
{
return; return;
}
debug(new object(), new MessageEventArgs(string.Format(debugMessage, args))); debug(new object(), new MessageEventArgs(string.Format(debugMessage, args)));
} }
private void fireProgress(int progressPercentage) private void FireProgress(int progressPercentage)
{ {
EventHandler<ProgressChangedEventArgs> progress = this.Progress; EventHandler<ProgressChangedEventArgs> progress = Progress;
if (progress == null) if (progress == null)
{
return; return;
progress(new object(), new ProgressChangedEventArgs(progressPercentage, (object) string.Empty)); }
progress(new object(), new ProgressChangedEventArgs(progressPercentage, string.Empty));
} }
#endregion #endregion
} }

694
Lz77.cs
View file

@ -9,352 +9,400 @@ using System.IO;
namespace libWiiSharp namespace libWiiSharp
{ {
public class Lz77 public class Lz77
{
private const int N = 4096;
private const int F = 18;
private const int threshold = 2;
private static uint lz77Magic = 1280980791;
private int[] leftSon = new int[4097];
private int[] rightSon = new int[4353];
private int[] dad = new int[4097];
private ushort[] textBuffer = new ushort[4113];
private int matchPosition;
private int matchLength;
public static uint Lz77Magic => Lz77.lz77Magic;
public static bool IsLz77Compressed(string file) => Lz77.IsLz77Compressed(File.ReadAllBytes(file));
public static bool IsLz77Compressed(byte[] file)
{ {
Headers.HeaderType headerType = Headers.DetectHeader(file); //private const int N = 4096;
return (int) Shared.Swap(BitConverter.ToUInt32(file, (int) headerType)) == (int) Lz77.lz77Magic; //private const int F = 18;
} //private const int threshold = 2;
private static readonly uint lz77Magic = 1280980791;
//private readonly int[] leftSon = new int[4097];
//private readonly int[] rightSon = new int[4353];
//private readonly int[] dad = new int[4097];
private readonly ushort[] textBuffer = new ushort[4113];
//private int matchPosition;
//private int matchLength;
public static bool IsLz77Compressed(Stream file) public static uint Lz77Magic => Lz77.lz77Magic;
{
Headers.HeaderType headerType = Headers.DetectHeader(file);
byte[] buffer = new byte[4];
file.Seek((long) headerType, SeekOrigin.Begin);
file.Read(buffer, 0, buffer.Length);
return (int) Shared.Swap(BitConverter.ToUInt32(buffer, 0)) == (int) Lz77.lz77Magic;
}
public void Compress(string inFile, string outFile) public static bool IsLz77Compressed(string file)
{
Stream stream = (Stream) null;
using (FileStream fileStream = new FileStream(inFile, FileMode.Open))
stream = this.compress((Stream) fileStream);
byte[] buffer = new byte[stream.Length];
stream.Read(buffer, 0, buffer.Length);
if (File.Exists(outFile))
File.Delete(outFile);
using (FileStream fileStream = new FileStream(outFile, FileMode.Create))
fileStream.Write(buffer, 0, buffer.Length);
}
public byte[] Compress(byte[] file) => ((MemoryStream) this.compress((Stream) new MemoryStream(file))).ToArray();
public Stream Compress(Stream file) => this.compress(file);
public void Decompress(string inFile, string outFile)
{
Stream stream = (Stream) null;
using (FileStream fileStream = new FileStream(inFile, FileMode.Open))
stream = this.decompress((Stream) fileStream);
byte[] buffer = new byte[stream.Length];
stream.Read(buffer, 0, buffer.Length);
if (File.Exists(outFile))
File.Delete(outFile);
using (FileStream fileStream = new FileStream(outFile, FileMode.Create))
fileStream.Write(buffer, 0, buffer.Length);
}
public byte[] Decompress(byte[] file) => ((MemoryStream) this.decompress((Stream) new MemoryStream(file))).ToArray();
public Stream Decompress(Stream file) => this.decompress(file);
private Stream decompress(Stream inFile)
{
if (!Lz77.IsLz77Compressed(inFile))
return inFile;
inFile.Seek(0L, SeekOrigin.Begin);
uint num1 = 0;
Headers.HeaderType headerType = Headers.DetectHeader(inFile);
byte[] buffer = new byte[8];
inFile.Seek((long) headerType, SeekOrigin.Begin);
inFile.Read(buffer, 0, 8);
if ((int) Shared.Swap(BitConverter.ToUInt32(buffer, 0)) != (int) Lz77.lz77Magic)
{
inFile.Dispose();
throw new Exception("Invaild Magic!");
}
if (buffer[4] != (byte) 16)
{
inFile.Dispose();
throw new Exception("Unsupported Compression Type!");
}
uint num2 = BitConverter.ToUInt32(buffer, 4) >> 8;
for (int index = 0; index < 4078; ++index)
this.textBuffer[index] = (ushort) 223;
int num3 = 4078;
uint num4 = 7;
int num5 = 7;
MemoryStream memoryStream = new MemoryStream();
label_10:
while (true)
{
num4 <<= 1;
++num5;
if (num5 == 8)
{ {
int num6; return Lz77.IsLz77Compressed(File.ReadAllBytes(file));
if ((num6 = inFile.ReadByte()) != -1)
{
num4 = (uint) num6;
num5 = 0;
}
else
goto label_24;
} }
if (((int) num4 & 128) == 0)
{
int num6;
if ((long) (num6 = inFile.ReadByte()) != inFile.Length - 1L)
{
if (num1 < num2)
memoryStream.WriteByte((byte) num6);
ushort[] textBuffer = this.textBuffer;
int index = num3;
int num7 = index + 1;
int num8 = (int) (byte) num6;
textBuffer[index] = (ushort) num8;
num3 = num7 & 4095;
++num1;
}
else
goto label_24;
}
else
break;
}
int num9;
int num10;
if ((num9 = inFile.ReadByte()) != -1 && (num10 = inFile.ReadByte()) != -1)
{
int num6 = num10 | num9 << 8 & 3840;
int num7 = (num9 >> 4 & 15) + 2;
for (int index1 = 0; index1 <= num7; ++index1)
{
int num8 = (int) this.textBuffer[num3 - num6 - 1 & 4095];
if (num1 < num2)
memoryStream.WriteByte((byte) num8);
ushort[] textBuffer = this.textBuffer;
int index2 = num3;
int num11 = index2 + 1;
int num12 = (int) (byte) num8;
textBuffer[index2] = (ushort) num12;
num3 = num11 & 4095;
++num1;
}
goto label_10;
}
label_24:
return (Stream) memoryStream;
}
private Stream compress(Stream inFile) public static bool IsLz77Compressed(byte[] file)
{
if (Lz77.IsLz77Compressed(inFile))
return inFile;
inFile.Seek(0L, SeekOrigin.Begin);
int num1 = 0;
int[] numArray1 = new int[17];
uint num2 = (uint) (((int) Convert.ToUInt32(inFile.Length) << 8) + 16);
MemoryStream memoryStream = new MemoryStream();
memoryStream.Write(BitConverter.GetBytes(Shared.Swap(Lz77.lz77Magic)), 0, 4);
memoryStream.Write(BitConverter.GetBytes(num2), 0, 4);
this.InitTree();
numArray1[0] = 0;
int num3 = 1;
int num4 = 128;
int p = 0;
int r = 4078;
for (int index = p; index < r; ++index)
this.textBuffer[index] = ushort.MaxValue;
int num5;
int num6;
for (num5 = 0; num5 < 18 && (num6 = inFile.ReadByte()) != -1; ++num5)
this.textBuffer[r + num5] = (ushort) num6;
if (num5 == 0)
return inFile;
for (int index = 1; index <= 18; ++index)
this.InsertNode(r - index);
this.InsertNode(r);
do
{
if (this.matchLength > num5)
this.matchLength = num5;
if (this.matchLength <= 2)
{ {
this.matchLength = 1; Headers.HeaderType headerType = Headers.DetectHeader(file);
numArray1[num3++] = (int) this.textBuffer[r]; return (int)Shared.Swap(BitConverter.ToUInt32(file, (int)headerType)) == (int)Lz77.lz77Magic;
} }
else
public static bool IsLz77Compressed(Stream file)
{ {
numArray1[0] |= num4; Headers.HeaderType headerType = Headers.DetectHeader(file);
int[] numArray2 = numArray1; byte[] buffer = new byte[4];
int index1 = num3; file.Seek((long)headerType, SeekOrigin.Begin);
int num7 = index1 + 1; file.Read(buffer, 0, buffer.Length);
int num8 = (int) (ushort) (r - this.matchPosition - 1 >> 8 & 15) | this.matchLength - 3 << 4; return (int)Shared.Swap(BitConverter.ToUInt32(buffer, 0)) == (int)Lz77.lz77Magic;
numArray2[index1] = num8;
int[] numArray3 = numArray1;
int index2 = num7;
num3 = index2 + 1;
int num9 = (int) (ushort) (r - this.matchPosition - 1 & (int) byte.MaxValue);
numArray3[index2] = num9;
} }
if ((num4 >>= 1) == 0)
public void Compress(string inFile, string outFile)
{ {
for (int index = 0; index < num3; ++index) Stream stream = null;
memoryStream.WriteByte((byte) numArray1[index]); using (FileStream fileStream = new FileStream(inFile, FileMode.Open))
num1 += num3; {
numArray1[0] = 0; stream = Compress(fileStream);
num3 = 1; }
num4 = 128;
byte[] buffer = new byte[stream.Length];
stream.Read(buffer, 0, buffer.Length);
if (File.Exists(outFile))
{
File.Delete(outFile);
}
using (FileStream fileStream = new FileStream(outFile, FileMode.Create))
{
fileStream.Write(buffer, 0, buffer.Length);
}
} }
int matchLength = this.matchLength;
int num10; public byte[] Compress(byte[] file)
int num11;
for (num10 = 0; num10 < matchLength && (num11 = inFile.ReadByte()) != -1; ++num10)
{ {
this.DeleteNode(p); return ((MemoryStream)Compress(new MemoryStream(file))).ToArray();
this.textBuffer[p] = (ushort) num11;
if (p < 17)
this.textBuffer[p + 4096] = (ushort) num11;
p = p + 1 & 4095;
r = r + 1 & 4095;
this.InsertNode(r);
} }
while (num10++ < matchLength)
public Stream Compress(Stream file)
{ {
this.DeleteNode(p); return Compress(file);
p = p + 1 & 4095; }
r = r + 1 & 4095;
if (--num5 != 0) public void Decompress(string inFile, string outFile)
{
Stream stream = null;
using (FileStream fileStream = new FileStream(inFile, FileMode.Open))
{
stream = Decompress(fileStream);
}
byte[] buffer = new byte[stream.Length];
stream.Read(buffer, 0, buffer.Length);
if (File.Exists(outFile))
{
File.Delete(outFile);
}
using (FileStream fileStream = new FileStream(outFile, FileMode.Create))
{
fileStream.Write(buffer, 0, buffer.Length);
}
}
public byte[] Decompress(byte[] file)
{
return ((MemoryStream)PrivDecompress(new MemoryStream(file))).ToArray();
}
public Stream Decompress(Stream file)
{
return PrivDecompress(file);
}
private Stream PrivDecompress(Stream inFile)
{
if (!Lz77.IsLz77Compressed(inFile))
{
return inFile;
}
inFile.Seek(0L, SeekOrigin.Begin);
uint num1 = 0;
Headers.HeaderType headerType = Headers.DetectHeader(inFile);
byte[] buffer = new byte[8];
inFile.Seek((long)headerType, SeekOrigin.Begin);
inFile.Read(buffer, 0, 8);
if ((int)Shared.Swap(BitConverter.ToUInt32(buffer, 0)) != (int)Lz77.lz77Magic)
{
inFile.Dispose();
throw new Exception("Invaild Magic!");
}
if (buffer[4] != 16)
{
inFile.Dispose();
throw new Exception("Unsupported Compression Type!");
}
uint num2 = BitConverter.ToUInt32(buffer, 4) >> 8;
for (int index = 0; index < 4078; ++index)
{
textBuffer[index] = 223;
}
int num3 = 4078;
uint num4 = 7;
int num5 = 7;
MemoryStream memoryStream = new MemoryStream();
label_10:
while (true)
{
num4 <<= 1;
++num5;
if (num5 == 8)
{
int num6;
if ((num6 = inFile.ReadByte()) != -1)
{
num4 = (uint)num6;
num5 = 0;
}
else
{
goto label_24;
}
}
if (((int)num4 & 128) == 0)
{
int num6;
if ((num6 = inFile.ReadByte()) != inFile.Length - 1L)
{
if (num1 < num2)
{
memoryStream.WriteByte((byte)num6);
}
ushort[] textBuffer = this.textBuffer;
int index = num3;
int num7 = index + 1;
int num8 = (byte)num6;
textBuffer[index] = (ushort)num8;
num3 = num7 & 4095;
++num1;
}
else
{
goto label_24;
}
}
else
{
break;
}
}
int num9;
int num10;
if ((num9 = inFile.ReadByte()) != -1 && (num10 = inFile.ReadByte()) != -1)
{
int num6 = num10 | num9 << 8 & 3840;
int num7 = (num9 >> 4 & 15) + 2;
for (int index1 = 0; index1 <= num7; ++index1)
{
int num8 = this.textBuffer[num3 - num6 - 1 & 4095];
if (num1 < num2)
{
memoryStream.WriteByte((byte)num8);
}
ushort[] textBuffer = this.textBuffer;
int index2 = num3;
int num11 = index2 + 1;
int num12 = (byte)num8;
textBuffer[index2] = (ushort)num12;
num3 = num11 & 4095;
++num1;
}
goto label_10;
}
label_24:
return memoryStream;
}
/*
private Stream PrivCompress(Stream inFile)
{
if (Lz77.IsLz77Compressed(inFile))
return inFile;
inFile.Seek(0L, SeekOrigin.Begin);
int num1 = 0;
int[] numArray1 = new int[17];
uint num2 = (uint)(((int)Convert.ToUInt32(inFile.Length) << 8) + 16);
MemoryStream memoryStream = new MemoryStream();
memoryStream.Write(BitConverter.GetBytes(Shared.Swap(Lz77.lz77Magic)), 0, 4);
memoryStream.Write(BitConverter.GetBytes(num2), 0, 4);
this.InitTree();
numArray1[0] = 0;
int num3 = 1;
int num4 = 128;
int p = 0;
int r = 4078;
for (int index = p; index < r; ++index)
this.textBuffer[index] = ushort.MaxValue;
int num5;
int num6;
for (num5 = 0; num5 < 18 && (num6 = inFile.ReadByte()) != -1; ++num5)
this.textBuffer[r + num5] = (ushort)num6;
if (num5 == 0)
return inFile;
for (int index = 1; index <= 18; ++index)
this.InsertNode(r - index);
this.InsertNode(r); this.InsertNode(r);
} do
}
while (num5 > 0);
if (num3 > 1)
{
for (int index = 0; index < num3; ++index)
memoryStream.WriteByte((byte) numArray1[index]);
num1 += num3;
}
if (num1 % 4 != 0)
{
for (int index = 0; index < 4 - num1 % 4; ++index)
memoryStream.WriteByte((byte) 0);
}
return (Stream) memoryStream;
}
private void InitTree()
{
for (int index = 4097; index <= 4352; ++index)
this.rightSon[index] = 4096;
for (int index = 0; index < 4096; ++index)
this.dad[index] = 4096;
}
private void InsertNode(int r)
{
int num1 = 1;
int index = 4097 + (this.textBuffer[r] != ushort.MaxValue ? (int) this.textBuffer[r] : 0);
this.rightSon[r] = this.leftSon[r] = 4096;
this.matchLength = 0;
int num2;
do
{
do
{
if (num1 >= 0)
{
if (this.rightSon[index] == 4096)
{ {
this.rightSon[index] = r; if (this.matchLength > num5)
this.dad[r] = index; this.matchLength = num5;
return; if (this.matchLength <= 2)
{
this.matchLength = 1;
numArray1[num3++] = (int)this.textBuffer[r];
}
else
{
numArray1[0] |= num4;
int[] numArray2 = numArray1;
int index1 = num3;
int num7 = index1 + 1;
int num8 = (int)(ushort)(r - this.matchPosition - 1 >> 8 & 15) | this.matchLength - 3 << 4;
numArray2[index1] = num8;
int[] numArray3 = numArray1;
int index2 = num7;
num3 = index2 + 1;
int num9 = (int)(ushort)(r - this.matchPosition - 1 & (int)byte.MaxValue);
numArray3[index2] = num9;
}
if ((num4 >>= 1) == 0)
{
for (int index = 0; index < num3; ++index)
memoryStream.WriteByte((byte)numArray1[index]);
num1 += num3;
numArray1[0] = 0;
num3 = 1;
num4 = 128;
}
int matchLength = this.matchLength;
int num10;
int num11;
for (num10 = 0; num10 < matchLength && (num11 = inFile.ReadByte()) != -1; ++num10)
{
this.DeleteNode(p);
this.textBuffer[p] = (ushort)num11;
if (p < 17)
this.textBuffer[p + 4096] = (ushort)num11;
p = p + 1 & 4095;
r = r + 1 & 4095;
this.InsertNode(r);
}
while (num10++ < matchLength)
{
this.DeleteNode(p);
p = p + 1 & 4095;
r = r + 1 & 4095;
if (--num5 != 0)
this.InsertNode(r);
}
} }
index = this.rightSon[index]; while (num5 > 0);
} if (num3 > 1)
else
{
if (this.leftSon[index] == 4096)
{ {
this.leftSon[index] = r; for (int index = 0; index < num3; ++index)
this.dad[r] = index; memoryStream.WriteByte((byte)numArray1[index]);
return; num1 += num3;
} }
index = this.leftSon[index]; if (num1 % 4 != 0)
} {
num2 = 1; for (int index = 0; index < 4 - num1 % 4; ++index)
while (num2 < 18 && (num1 = (int) this.textBuffer[r + num2] - (int) this.textBuffer[index + num2]) == 0) memoryStream.WriteByte((byte)0);
++num2; }
return (Stream)memoryStream;
} }
while (num2 <= this.matchLength);
this.matchPosition = index;
}
while ((this.matchLength = num2) < 18);
this.dad[r] = this.dad[index];
this.leftSon[r] = this.leftSon[index];
this.rightSon[r] = this.rightSon[index];
this.dad[this.leftSon[index]] = r;
this.dad[this.rightSon[index]] = r;
if (this.rightSon[this.dad[index]] == index)
this.rightSon[this.dad[index]] = r;
else
this.leftSon[this.dad[index]] = r;
this.dad[index] = 4096;
}
private void DeleteNode(int p) private void InitTree()
{
if (this.dad[p] == 4096)
return;
int index;
if (this.rightSon[p] == 4096)
index = this.leftSon[p];
else if (this.leftSon[p] == 4096)
{
index = this.rightSon[p];
}
else
{
index = this.leftSon[p];
if (this.rightSon[index] != 4096)
{ {
do for (int index = 4097; index <= 4352; ++index)
{ this.rightSon[index] = 4096;
index = this.rightSon[index]; for (int index = 0; index < 4096; ++index)
} this.dad[index] = 4096;
while (this.rightSon[index] != 4096);
this.rightSon[this.dad[index]] = this.leftSon[index];
this.dad[this.leftSon[index]] = this.dad[index];
this.leftSon[index] = this.leftSon[p];
this.dad[this.leftSon[p]] = index;
} }
this.rightSon[index] = this.rightSon[p]; private void InsertNode(int r)
this.dad[this.rightSon[p]] = index; {
} int num1 = 1;
this.dad[index] = this.dad[p]; int index = 4097 + (this.textBuffer[r] != ushort.MaxValue ? (int)this.textBuffer[r] : 0);
if (this.rightSon[this.dad[p]] == p) this.rightSon[r] = this.leftSon[r] = 4096;
this.rightSon[this.dad[p]] = index; this.matchLength = 0;
else int num2;
this.leftSon[this.dad[p]] = index; do
this.dad[p] = 4096; {
do
{
if (num1 >= 0)
{
if (this.rightSon[index] == 4096)
{
this.rightSon[index] = r;
this.dad[r] = index;
return;
}
index = this.rightSon[index];
}
else
{
if (this.leftSon[index] == 4096)
{
this.leftSon[index] = r;
this.dad[r] = index;
return;
}
index = this.leftSon[index];
}
num2 = 1;
while (num2 < 18 && (num1 = (int)this.textBuffer[r + num2] - (int)this.textBuffer[index + num2]) == 0)
++num2;
}
while (num2 <= this.matchLength);
this.matchPosition = index;
}
while ((this.matchLength = num2) < 18);
this.dad[r] = this.dad[index];
this.leftSon[r] = this.leftSon[index];
this.rightSon[r] = this.rightSon[index];
this.dad[this.leftSon[index]] = r;
this.dad[this.rightSon[index]] = r;
if (this.rightSon[this.dad[index]] == index)
this.rightSon[this.dad[index]] = r;
else
this.leftSon[this.dad[index]] = r;
this.dad[index] = 4096;
}
private void DeleteNode(int p)
{
if (this.dad[p] == 4096)
return;
int index;
if (this.rightSon[p] == 4096)
index = this.leftSon[p];
else if (this.leftSon[p] == 4096)
{
index = this.rightSon[p];
}
else
{
index = this.leftSon[p];
if (this.rightSon[index] != 4096)
{
do
{
index = this.rightSon[index];
}
while (this.rightSon[index] != 4096);
this.rightSon[this.dad[index]] = this.leftSon[index];
this.dad[this.leftSon[index]] = this.dad[index];
this.leftSon[index] = this.leftSon[p];
this.dad[this.leftSon[p]] = index;
}
this.rightSon[index] = this.rightSon[p];
this.dad[this.rightSon[p]] = index;
}
this.dad[index] = this.dad[p];
if (this.rightSon[this.dad[p]] == p)
this.rightSon[this.dad[p]] = index;
else
this.leftSon[this.dad[p]] = index;
this.dad[p] = 4096;
}
*/
} }
}
} }

View file

@ -8,12 +8,15 @@ using System;
namespace libWiiSharp namespace libWiiSharp
{ {
public class MessageEventArgs : EventArgs public class MessageEventArgs : EventArgs
{ {
private string message; private readonly string message;
public string Message => this.message; public string Message => message;
public MessageEventArgs(string message) => this.message = message; public MessageEventArgs(string message)
} {
this.message = message;
}
}
} }

View file

@ -13,424 +13,474 @@ using System.Security.Cryptography;
namespace libWiiSharp namespace libWiiSharp
{ {
public class NusClient : IDisposable public class NusClient : IDisposable
{
private const string nusUrl = "http://nus.cdn.shop.wii.com/ccs/download/";
private WebClient wcNus = new WebClient();
private bool useLocalFiles;
private bool continueWithoutTicket;
private bool isDisposed;
public bool UseLocalFiles
{ {
get => this.useLocalFiles; private const string nusUrl = "http://nus.cdn.shop.wii.com/ccs/download/";
set => this.useLocalFiles = value; private readonly WebClient wcNus = new WebClient();
} private bool useLocalFiles;
private bool continueWithoutTicket;
private bool isDisposed;
public bool ContinueWithoutTicket public bool UseLocalFiles
{
get => this.continueWithoutTicket;
set => this.continueWithoutTicket = value;
}
public event EventHandler<ProgressChangedEventArgs> Progress;
public event EventHandler<MessageEventArgs> Debug;
~NusClient() => this.Dispose(false);
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize((object) this);
}
protected virtual void Dispose(bool disposing)
{
if (disposing && !this.isDisposed)
this.wcNus.Dispose();
this.isDisposed = true;
}
public void DownloadTitle(
string titleId,
string titleVersion,
string outputDir,
params StoreType[] storeTypes)
{
if (titleId.Length != 16)
throw new Exception("Title ID must be 16 characters long!");
this.downloadTitle(titleId, titleVersion, outputDir, storeTypes);
}
public TMD DownloadTMD(string titleId, string titleVersion) => titleId.Length == 16 ? this.downloadTmd(titleId, titleVersion) : throw new Exception("Title ID must be 16 characters long!");
public Ticket DownloadTicket(string titleId) => titleId.Length == 16 ? this.downloadTicket(titleId) : throw new Exception("Title ID must be 16 characters long!");
public byte[] DownloadSingleContent(string titleId, string titleVersion, string contentId)
{
if (titleId.Length != 16)
throw new Exception("Title ID must be 16 characters long!");
return this.downloadSingleContent(titleId, titleVersion, contentId);
}
public void DownloadSingleContent(
string titleId,
string titleVersion,
string contentId,
string savePath)
{
if (titleId.Length != 16)
throw new Exception("Title ID must be 16 characters long!");
if (!Directory.Exists(Path.GetDirectoryName(savePath)))
Directory.CreateDirectory(Path.GetDirectoryName(savePath));
if (System.IO.File.Exists(savePath))
System.IO.File.Delete(savePath);
byte[] bytes = this.downloadSingleContent(titleId, titleVersion, contentId);
System.IO.File.WriteAllBytes(savePath, bytes);
}
private byte[] downloadSingleContent(string titleId, string titleVersion, string contentId)
{
uint num = uint.Parse(contentId, NumberStyles.HexNumber);
contentId = num.ToString("x8");
this.fireDebug("Downloading Content (Content ID: {0}) of Title {1} v{2}...", (object) contentId, (object) titleId, string.IsNullOrEmpty(titleVersion) ? (object) "[Latest]" : (object) titleVersion);
this.fireDebug(" Checking for Internet connection...");
if (!this.CheckInet())
{
this.fireDebug(" Connection not found...");
throw new Exception("You're not connected to the internet!");
}
this.fireProgress(0);
string str1 = "tmd" + (string.IsNullOrEmpty(titleVersion) ? string.Empty : "." + titleVersion);
string str2 = string.Format("{0}{1}/", (object) "http://nus.cdn.shop.wii.com/ccs/download/", (object) titleId);
string empty = string.Empty;
int contentIndex = 0;
this.fireDebug(" Downloading TMD...");
byte[] tmdFile = this.wcNus.DownloadData(str2 + str1);
this.fireDebug(" Parsing TMD...");
TMD tmd = TMD.Load(tmdFile);
this.fireProgress(20);
this.fireDebug(" Looking for Content ID {0} in TMD...", (object) contentId);
bool flag = false;
for (int index = 0; index < tmd.Contents.Length; ++index)
{
if ((int) tmd.Contents[index].ContentID == (int) num)
{ {
this.fireDebug(" Content ID {0} found in TMD...", (object) contentId); get => useLocalFiles;
flag = true; set => useLocalFiles = value;
empty = tmd.Contents[index].ContentID.ToString("x8");
contentIndex = index;
break;
} }
}
if (!flag)
{
this.fireDebug(" Content ID {0} wasn't found in TMD...", (object) contentId);
throw new Exception("Content ID wasn't found in the TMD!");
}
if (!File.Exists("cetk"))
{
fireDebug(" Downloading Ticket...");
byte[] tikArray = wcNus.DownloadData(str2 + "cetk");
Console.WriteLine("Downloading");
}
Console.WriteLine("Continuing");
this.fireDebug("Parsing Ticket...");
Ticket tik = Ticket.Load("cetk");
this.fireProgress(40);
this.fireDebug(" Downloading Content... ({0} bytes)", (object) tmd.Contents[contentIndex].Size);
byte[] content = this.wcNus.DownloadData(str2 + empty);
this.fireProgress(80);
this.fireDebug(" Decrypting Content...");
byte[] array = this.decryptContent(content, contentIndex, tik, tmd);
Array.Resize<byte>(ref array, (int) tmd.Contents[contentIndex].Size);
if (!Shared.CompareByteArrays(SHA1.Create().ComputeHash(array), tmd.Contents[contentIndex].Hash))
{
this.fireDebug("/!\\ /!\\ /!\\ Hashes do not match /!\\ /!\\ /!\\");
throw new Exception("Hashes do not match!");
}
this.fireProgress(100);
this.fireDebug("Downloading Content (Content ID: {0}) of Title {1} v{2} Finished...", (object) contentId, (object) titleId, string.IsNullOrEmpty(titleVersion) ? (object) "[Latest]" : (object) titleVersion);
return array;
}
private Ticket downloadTicket(string titleId) public bool ContinueWithoutTicket
{
if (!CheckInet())
throw new Exception("You're not connected to the internet!");
string titleUrl = string.Format("{0}{1}/", nusUrl, titleId);
byte[] tikArray = wcNus.DownloadData(titleUrl + "cetk");
return Ticket.Load(tikArray);
}
private TMD downloadTmd(string titleId, string titleVersion)
{
if (!this.CheckInet())
throw new Exception("You're not connected to the internet!");
return TMD.Load(this.wcNus.DownloadData(string.Format("{0}{1}/", (object) "http://nus.cdn.shop.wii.com/ccs/download/", (object) titleId) + ("tmd" + (string.IsNullOrEmpty(titleVersion) ? string.Empty : "." + titleVersion))));
}
private void downloadTitle(
string titleId,
string titleVersion,
string outputDir,
StoreType[] storeTypes)
{
this.fireDebug("Downloading Title {0} v{1}...", (object) titleId, string.IsNullOrEmpty(titleVersion) ? (object) "[Latest]" : (object) titleVersion);
if (storeTypes.Length < 1)
{
this.fireDebug(" No store types were defined...");
throw new Exception("You must at least define one store type!");
}
string str1 = string.Format("{0}{1}/", (object) "http://nus.cdn.shop.wii.com/ccs/download/", (object) titleId);
bool flag1 = false;
bool flag2 = false;
bool flag3 = false;
this.fireProgress(0);
for (int index = 0; index < storeTypes.Length; ++index)
{
switch (storeTypes[index])
{ {
case StoreType.EncryptedContent: get => continueWithoutTicket;
this.fireDebug(" -> Storing Encrypted Content..."); set => continueWithoutTicket = value;
flag1 = true;
break;
case StoreType.DecryptedContent:
this.fireDebug(" -> Storing Decrypted Content...");
flag2 = true;
break;
case StoreType.WAD:
this.fireDebug(" -> Storing WAD...");
flag3 = true;
break;
case StoreType.All:
this.fireDebug(" -> Storing Decrypted Content...");
this.fireDebug(" -> Storing Encrypted Content...");
this.fireDebug(" -> Storing WAD...");
flag2 = true;
flag1 = true;
flag3 = true;
break;
} }
}
this.fireDebug(" Checking for Internet connection...");
if (!this.CheckInet())
{
this.fireDebug(" Connection not found...");
throw new Exception("You're not connected to the internet!");
}
if ((int) outputDir[outputDir.Length - 1] != (int) Path.DirectorySeparatorChar)
outputDir += Path.DirectorySeparatorChar.ToString();
if (!Directory.Exists(outputDir))
Directory.CreateDirectory(outputDir);
string str2 = "tmd" + (string.IsNullOrEmpty(titleVersion) ? string.Empty : "." + titleVersion);
this.fireDebug(" Downloading TMD...");
try
{
this.wcNus.DownloadFile(str1 + str2, outputDir + str2);
}
catch (Exception ex)
{
this.fireDebug(" Downloading TMD Failed...");
throw new Exception("Downloading TMD Failed:\n" + ex.Message);
}
if (!File.Exists(outputDir + "cetk")) public event EventHandler<ProgressChangedEventArgs> Progress;
{
//Download cetk public event EventHandler<MessageEventArgs> Debug;
fireDebug(" Downloading Ticket...");
try ~NusClient() => Dispose(false);
public void Dispose()
{ {
wcNus.DownloadFile(string.Format("{0}{1}/", nusUrl, titleId) + "cetk", outputDir + "cetk"); Dispose(true);
GC.SuppressFinalize(this);
} }
catch (Exception ex)
protected virtual void Dispose(bool disposing)
{ {
if (!continueWithoutTicket || !flag1) if (disposing && !isDisposed)
{ {
fireDebug(" Downloading Ticket Failed..."); wcNus.Dispose();
throw new Exception("CETK Doesn't Exist and Downloading Ticket Failed:\n" + ex.Message);
} }
flag2 = false; isDisposed = true;
flag3 = false;
} }
}
public void DownloadTitle(
string titleId,
string titleVersion,
string outputDir,
params StoreType[] storeTypes)
{
if (titleId.Length != 16)
{
throw new Exception("Title ID must be 16 characters long!");
}
PrivDownloadTitle(titleId, titleVersion, outputDir, storeTypes);
}
public TMD DownloadTMD(string titleId, string titleVersion)
{
return titleId.Length == 16 ? DownloadTmd(titleId, titleVersion) : throw new Exception("Title ID must be 16 characters long!");
}
public Ticket DownloadTicket(string titleId)
{
return titleId.Length == 16 ? PrivDownloadTicket(titleId) : throw new Exception("Title ID must be 16 characters long!");
}
public byte[] DownloadSingleContent(string titleId, string titleVersion, string contentId)
{
if (titleId.Length != 16)
{
throw new Exception("Title ID must be 16 characters long!");
}
return PrivDownloadSingleContent(titleId, titleVersion, contentId);
}
public void DownloadSingleContent(
string titleId,
string titleVersion,
string contentId,
string savePath)
{
if (titleId.Length != 16)
{
throw new Exception("Title ID must be 16 characters long!");
}
if (!Directory.Exists(Path.GetDirectoryName(savePath)))
{
Directory.CreateDirectory(Path.GetDirectoryName(savePath));
}
if (System.IO.File.Exists(savePath))
{
System.IO.File.Delete(savePath);
}
byte[] bytes = PrivDownloadSingleContent(titleId, titleVersion, contentId);
System.IO.File.WriteAllBytes(savePath, bytes);
}
private byte[] PrivDownloadSingleContent(string titleId, string titleVersion, string contentId)
{
uint num = uint.Parse(contentId, NumberStyles.HexNumber);
contentId = num.ToString("x8");
FireDebug("Downloading Content (Content ID: {0}) of Title {1} v{2}...", contentId, titleId, string.IsNullOrEmpty(titleVersion) ? "[Latest]" : titleVersion);
FireDebug(" Checking for Internet connection...");
if (!CheckInet())
{
FireDebug(" Connection not found...");
throw new Exception("You're not connected to the internet!");
}
FireProgress(0);
string str1 = "tmd" + (string.IsNullOrEmpty(titleVersion) ? string.Empty : "." + titleVersion);
string str2 = string.Format("{0}{1}/", "http://nus.cdn.shop.wii.com/ccs/download/", titleId);
string empty = string.Empty;
int contentIndex = 0;
FireDebug(" Downloading TMD...");
byte[] tmdFile = wcNus.DownloadData(str2 + str1);
FireDebug(" Parsing TMD...");
TMD tmd = TMD.Load(tmdFile);
FireProgress(20);
FireDebug(" Looking for Content ID {0} in TMD...", (object)contentId);
bool flag = false;
for (int index = 0; index < tmd.Contents.Length; ++index)
{
if ((int)tmd.Contents[index].ContentID == (int)num)
{
FireDebug(" Content ID {0} found in TMD...", (object)contentId);
flag = true;
empty = tmd.Contents[index].ContentID.ToString("x8");
contentIndex = index;
break;
}
}
if (!flag)
{
FireDebug(" Content ID {0} wasn't found in TMD...", (object)contentId);
throw new Exception("Content ID wasn't found in the TMD!");
}
if (!File.Exists("cetk"))
{
FireDebug(" Downloading Ticket...");
//byte[] tikArray = wcNus.DownloadData(str2 + "cetk");
Console.WriteLine("Downloading");
}
Console.WriteLine("Continuing");
FireDebug("Parsing Ticket...");
Ticket tik = Ticket.Load("cetk");
FireProgress(40);
FireDebug(" Downloading Content... ({0} bytes)", (object)tmd.Contents[contentIndex].Size);
byte[] content = wcNus.DownloadData(str2 + empty);
FireProgress(80);
FireDebug(" Decrypting Content...");
byte[] array = DecryptContent(content, contentIndex, tik, tmd);
Array.Resize<byte>(ref array, (int)tmd.Contents[contentIndex].Size);
if (!Shared.CompareByteArrays(SHA1.Create().ComputeHash(array), tmd.Contents[contentIndex].Hash))
{
FireDebug("/!\\ /!\\ /!\\ Hashes do not match /!\\ /!\\ /!\\");
throw new Exception("Hashes do not match!");
}
FireProgress(100);
FireDebug("Downloading Content (Content ID: {0}) of Title {1} v{2} Finished...", contentId, titleId, string.IsNullOrEmpty(titleVersion) ? "[Latest]" : titleVersion);
return array;
}
private Ticket PrivDownloadTicket(string titleId)
{
if (!CheckInet())
{
throw new Exception("You're not connected to the internet!");
}
string titleUrl = string.Format("{0}{1}/", nusUrl, titleId);
byte[] tikArray = wcNus.DownloadData(titleUrl + "cetk");
return Ticket.Load(tikArray);
}
private TMD DownloadTmd(string titleId, string titleVersion)
{
if (!CheckInet())
{
throw new Exception("You're not connected to the internet!");
}
return TMD.Load(wcNus.DownloadData(string.Format("{0}{1}/", "http://nus.cdn.shop.wii.com/ccs/download/", titleId) + ("tmd" + (string.IsNullOrEmpty(titleVersion) ? string.Empty : "." + titleVersion))));
}
private void PrivDownloadTitle(
string titleId,
string titleVersion,
string outputDir,
StoreType[] storeTypes)
{
FireDebug("Downloading Title {0} v{1}...", titleId, string.IsNullOrEmpty(titleVersion) ? "[Latest]" : titleVersion);
if (storeTypes.Length < 1)
{
FireDebug(" No store types were defined...");
throw new Exception("You must at least define one store type!");
}
string str1 = string.Format("{0}{1}/", "http://nus.cdn.shop.wii.com/ccs/download/", titleId);
bool flag1 = false;
bool flag2 = false;
bool flag3 = false;
FireProgress(0);
for (int index = 0; index < storeTypes.Length; ++index)
{
switch (storeTypes[index])
{
case StoreType.EncryptedContent:
FireDebug(" -> Storing Encrypted Content...");
flag1 = true;
break;
case StoreType.DecryptedContent:
FireDebug(" -> Storing Decrypted Content...");
flag2 = true;
break;
case StoreType.WAD:
FireDebug(" -> Storing WAD...");
flag3 = true;
break;
case StoreType.All:
FireDebug(" -> Storing Decrypted Content...");
FireDebug(" -> Storing Encrypted Content...");
FireDebug(" -> Storing WAD...");
flag2 = true;
flag1 = true;
flag3 = true;
break;
}
}
FireDebug(" Checking for Internet connection...");
if (!CheckInet())
{
FireDebug(" Connection not found...");
throw new Exception("You're not connected to the internet!");
}
if (outputDir[outputDir.Length - 1] != Path.DirectorySeparatorChar)
{
outputDir += Path.DirectorySeparatorChar.ToString();
}
if (!Directory.Exists(outputDir))
{
Directory.CreateDirectory(outputDir);
}
string str2 = "tmd" + (string.IsNullOrEmpty(titleVersion) ? string.Empty : "." + titleVersion);
FireDebug(" Downloading TMD...");
try
{
wcNus.DownloadFile(str1 + str2, outputDir + str2);
}
catch (Exception ex)
{
FireDebug(" Downloading TMD Failed...");
throw new Exception("Downloading TMD Failed:\n" + ex.Message);
}
if (!File.Exists(outputDir + "cetk"))
{
//Download cetk
FireDebug(" Downloading Ticket...");
try
{
wcNus.DownloadFile(string.Format("{0}{1}/", nusUrl, titleId) + "cetk", outputDir + "cetk");
}
catch (Exception ex)
{
if (!continueWithoutTicket || !flag1)
{
FireDebug(" Downloading Ticket Failed...");
throw new Exception("CETK Doesn't Exist and Downloading Ticket Failed:\n" + ex.Message);
}
flag2 = false;
flag3 = false;
}
}
this.fireProgress(10); FireProgress(10);
this.fireDebug(" Parsing TMD..."); FireDebug(" Parsing TMD...");
TMD tmd = TMD.Load(outputDir + str2); TMD tmd = TMD.Load(outputDir + str2);
if (string.IsNullOrEmpty(titleVersion)) if (string.IsNullOrEmpty(titleVersion))
this.fireDebug(" -> Title Version: {0}", (object) tmd.TitleVersion); {
this.fireDebug(" -> {0} Contents", (object) tmd.NumOfContents); FireDebug(" -> Title Version: {0}", (object)tmd.TitleVersion);
this.fireDebug(" Parsing Ticket..."); }
Ticket tik = Ticket.Load(outputDir + "cetk");
string[] strArray1 = new string[(int) tmd.NumOfContents]; FireDebug(" -> {0} Contents", (object)tmd.NumOfContents);
uint contentId; FireDebug(" Parsing Ticket...");
for (int index1 = 0; index1 < (int) tmd.NumOfContents; ++index1) Ticket tik = Ticket.Load(outputDir + "cetk");
{ string[] strArray1 = new string[tmd.NumOfContents];
this.fireDebug(" Downloading Content #{0} of {1}... ({2} bytes)", (object) (index1 + 1), (object) tmd.NumOfContents, (object) tmd.Contents[index1].Size); uint contentId;
this.fireProgress((index1 + 1) * 60 / (int) tmd.NumOfContents + 10); for (int index1 = 0; index1 < tmd.NumOfContents; ++index1)
if (this.useLocalFiles) {
{ FireDebug(" Downloading Content #{0} of {1}... ({2} bytes)", index1 + 1, tmd.NumOfContents, tmd.Contents[index1].Size);
string str3 = outputDir; FireProgress((index1 + 1) * 60 / tmd.NumOfContents + 10);
contentId = tmd.Contents[index1].ContentID; if (useLocalFiles)
string str4 = contentId.ToString("x8"); {
if (System.IO.File.Exists(str3 + str4)) string str3 = outputDir;
{ contentId = tmd.Contents[index1].ContentID;
this.fireDebug(" Using Local File, Skipping..."); string str4 = contentId.ToString("x8");
continue; if (System.IO.File.Exists(str3 + str4))
} {
FireDebug(" Using Local File, Skipping...");
continue;
}
}
try
{
WebClient wcNus = this.wcNus;
string str3 = str1;
contentId = tmd.Contents[index1].ContentID;
string str4 = contentId.ToString("x8");
string address = str3 + str4;
string str5 = outputDir;
contentId = tmd.Contents[index1].ContentID;
string str6 = contentId.ToString("x8");
string fileName = str5 + str6;
wcNus.DownloadFile(address, fileName);
string[] strArray2 = strArray1;
int index2 = index1;
contentId = tmd.Contents[index1].ContentID;
string str7 = contentId.ToString("x8");
strArray2[index2] = str7;
}
catch (Exception ex)
{
FireDebug(" Downloading Content #{0} of {1} failed...", index1 + 1, tmd.NumOfContents);
throw new Exception("Downloading Content Failed:\n" + ex.Message);
}
}
if (flag2 | flag3)
{
SHA1 shA1 = SHA1.Create();
for (int contentIndex = 0; contentIndex < tmd.NumOfContents; ++contentIndex)
{
FireDebug(" Decrypting Content #{0} of {1}...", contentIndex + 1, tmd.NumOfContents);
FireProgress((contentIndex + 1) * 20 / tmd.NumOfContents + 75);
string str3 = outputDir;
contentId = tmd.Contents[contentIndex].ContentID;
string str4 = contentId.ToString("x8");
byte[] array = DecryptContent(System.IO.File.ReadAllBytes(str3 + str4), contentIndex, tik, tmd);
Array.Resize<byte>(ref array, (int)tmd.Contents[contentIndex].Size);
if (!Shared.CompareByteArrays(shA1.ComputeHash(array), tmd.Contents[contentIndex].Hash))
{
FireDebug("/!\\ /!\\ /!\\ Hashes do not match /!\\ /!\\ /!\\");
throw new Exception(string.Format("Content #{0}: Hashes do not match!", contentIndex));
}
string str5 = outputDir;
contentId = tmd.Contents[contentIndex].ContentID;
string str6 = contentId.ToString("x8");
System.IO.File.WriteAllBytes(str5 + str6 + ".app", array);
}
shA1.Clear();
}
if (flag3)
{
FireDebug(" Building Certificate Chain...");
CertificateChain cert = CertificateChain.FromTikTmd(outputDir + "cetk", outputDir + str2);
byte[][] contents = new byte[tmd.NumOfContents][];
for (int index1 = 0; index1 < tmd.NumOfContents; ++index1)
{
byte[][] numArray1 = contents;
int index2 = index1;
string str3 = outputDir;
contentId = tmd.Contents[index1].ContentID;
string str4 = contentId.ToString("x8");
byte[] numArray2 = System.IO.File.ReadAllBytes(str3 + str4 + ".app");
numArray1[index2] = numArray2;
}
FireDebug(" Creating WAD...");
WAD.Create(cert, tik, tmd, contents).Save(outputDir + tmd.TitleID.ToString("x16") + "v" + tmd.TitleVersion.ToString() + ".wad");
}
if (!flag1)
{
FireDebug(" Deleting Encrypted Contents...");
for (int index = 0; index < strArray1.Length; ++index)
{
if (System.IO.File.Exists(outputDir + strArray1[index]))
{
System.IO.File.Delete(outputDir + strArray1[index]);
}
}
}
if (flag3 && !flag2)
{
FireDebug(" Deleting Decrypted Contents...");
for (int index = 0; index < strArray1.Length; ++index)
{
if (System.IO.File.Exists(outputDir + strArray1[index] + ".app"))
{
System.IO.File.Delete(outputDir + strArray1[index] + ".app");
}
}
}
if (!flag2 && !flag1)
{
FireDebug(" Deleting TMD and Ticket...");
System.IO.File.Delete(outputDir + str2);
System.IO.File.Delete(outputDir + "cetk");
}
FireDebug("Downloading Title {0} v{1} Finished...", titleId, string.IsNullOrEmpty(titleVersion) ? "[Latest]" : titleVersion);
FireProgress(100);
} }
try
private byte[] DecryptContent(byte[] content, int contentIndex, Ticket tik, TMD tmd)
{ {
WebClient wcNus = this.wcNus; Array.Resize<byte>(ref content, Shared.AddPadding(content.Length, 16));
string str3 = str1; byte[] titleKey = tik.TitleKey;
contentId = tmd.Contents[index1].ContentID; byte[] numArray = new byte[16];
string str4 = contentId.ToString("x8"); byte[] bytes = BitConverter.GetBytes(tmd.Contents[contentIndex].Index);
string address = str3 + str4; numArray[0] = bytes[1];
string str5 = outputDir; numArray[1] = bytes[0];
contentId = tmd.Contents[index1].ContentID; RijndaelManaged rijndaelManaged = new RijndaelManaged
string str6 = contentId.ToString("x8"); {
string fileName = str5 + str6; Mode = CipherMode.CBC,
wcNus.DownloadFile(address, fileName); Padding = PaddingMode.None,
string[] strArray2 = strArray1; KeySize = 128,
int index2 = index1; BlockSize = 128,
contentId = tmd.Contents[index1].ContentID; Key = titleKey,
string str7 = contentId.ToString("x8"); IV = numArray
strArray2[index2] = str7; };
ICryptoTransform decryptor = rijndaelManaged.CreateDecryptor();
MemoryStream memoryStream = new MemoryStream(content);
CryptoStream cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read);
byte[] buffer = new byte[content.Length];
cryptoStream.Read(buffer, 0, buffer.Length);
cryptoStream.Dispose();
memoryStream.Dispose();
return buffer;
} }
catch (Exception ex)
private bool CheckInet()
{ {
this.fireDebug(" Downloading Content #{0} of {1} failed...", (object) (index1 + 1), (object) tmd.NumOfContents); try
throw new Exception("Downloading Content Failed:\n" + ex.Message); {
Dns.GetHostEntry("www.google.com");
return true;
}
catch
{
return false;
}
} }
}
if (flag2 | flag3) private void FireDebug(string debugMessage, params object[] args)
{
SHA1 shA1 = SHA1.Create();
for (int contentIndex = 0; contentIndex < (int) tmd.NumOfContents; ++contentIndex)
{ {
this.fireDebug(" Decrypting Content #{0} of {1}...", (object) (contentIndex + 1), (object) tmd.NumOfContents); EventHandler<MessageEventArgs> debug = Debug;
this.fireProgress((contentIndex + 1) * 20 / (int) tmd.NumOfContents + 75); if (debug == null)
string str3 = outputDir; {
contentId = tmd.Contents[contentIndex].ContentID; return;
string str4 = contentId.ToString("x8"); }
byte[] array = this.decryptContent(System.IO.File.ReadAllBytes(str3 + str4), contentIndex, tik, tmd);
Array.Resize<byte>(ref array, (int) tmd.Contents[contentIndex].Size); debug(new object(), new MessageEventArgs(string.Format(debugMessage, args)));
if (!Shared.CompareByteArrays(shA1.ComputeHash(array), tmd.Contents[contentIndex].Hash))
{
this.fireDebug("/!\\ /!\\ /!\\ Hashes do not match /!\\ /!\\ /!\\");
throw new Exception(string.Format("Content #{0}: Hashes do not match!", (object) contentIndex));
}
string str5 = outputDir;
contentId = tmd.Contents[contentIndex].ContentID;
string str6 = contentId.ToString("x8");
System.IO.File.WriteAllBytes(str5 + str6 + ".app", array);
} }
shA1.Clear();
} private void FireProgress(int progressPercentage)
if (flag3)
{
this.fireDebug(" Building Certificate Chain...");
CertificateChain cert = CertificateChain.FromTikTmd(outputDir + "cetk", outputDir + str2);
byte[][] contents = new byte[(int) tmd.NumOfContents][];
for (int index1 = 0; index1 < (int) tmd.NumOfContents; ++index1)
{ {
byte[][] numArray1 = contents; EventHandler<ProgressChangedEventArgs> progress = Progress;
int index2 = index1; if (progress == null)
string str3 = outputDir; {
contentId = tmd.Contents[index1].ContentID; return;
string str4 = contentId.ToString("x8"); }
byte[] numArray2 = System.IO.File.ReadAllBytes(str3 + str4 + ".app");
numArray1[index2] = numArray2; progress(new object(), new ProgressChangedEventArgs(progressPercentage, string.Empty));
} }
this.fireDebug(" Creating WAD...");
WAD.Create(cert, tik, tmd, contents).Save(outputDir + tmd.TitleID.ToString("x16") + "v" + tmd.TitleVersion.ToString() + ".wad");
}
if (!flag1)
{
this.fireDebug(" Deleting Encrypted Contents...");
for (int index = 0; index < strArray1.Length; ++index)
{
if (System.IO.File.Exists(outputDir + strArray1[index]))
System.IO.File.Delete(outputDir + strArray1[index]);
}
}
if (flag3 && !flag2)
{
this.fireDebug(" Deleting Decrypted Contents...");
for (int index = 0; index < strArray1.Length; ++index)
{
if (System.IO.File.Exists(outputDir + strArray1[index] + ".app"))
System.IO.File.Delete(outputDir + strArray1[index] + ".app");
}
}
if (!flag2 && !flag1)
{
this.fireDebug(" Deleting TMD and Ticket...");
System.IO.File.Delete(outputDir + str2);
System.IO.File.Delete(outputDir + "cetk");
}
this.fireDebug("Downloading Title {0} v{1} Finished...", (object) titleId, string.IsNullOrEmpty(titleVersion) ? (object) "[Latest]" : (object) titleVersion);
this.fireProgress(100);
} }
private byte[] decryptContent(byte[] content, int contentIndex, Ticket tik, TMD tmd)
{
Array.Resize<byte>(ref content, Shared.AddPadding(content.Length, 16));
byte[] titleKey = tik.TitleKey;
byte[] numArray = new byte[16];
byte[] bytes = BitConverter.GetBytes(tmd.Contents[contentIndex].Index);
numArray[0] = bytes[1];
numArray[1] = bytes[0];
RijndaelManaged rijndaelManaged = new RijndaelManaged();
rijndaelManaged.Mode = CipherMode.CBC;
rijndaelManaged.Padding = PaddingMode.None;
rijndaelManaged.KeySize = 128;
rijndaelManaged.BlockSize = 128;
rijndaelManaged.Key = titleKey;
rijndaelManaged.IV = numArray;
ICryptoTransform decryptor = rijndaelManaged.CreateDecryptor();
MemoryStream memoryStream = new MemoryStream(content);
CryptoStream cryptoStream = new CryptoStream((Stream) memoryStream, decryptor, CryptoStreamMode.Read);
byte[] buffer = new byte[content.Length];
cryptoStream.Read(buffer, 0, buffer.Length);
cryptoStream.Dispose();
memoryStream.Dispose();
return buffer;
}
private bool CheckInet()
{
try
{
Dns.GetHostEntry("www.google.com");
return true;
}
catch
{
return false;
}
}
private void fireDebug(string debugMessage, params object[] args)
{
EventHandler<MessageEventArgs> debug = this.Debug;
if (debug == null)
return;
debug(new object(), new MessageEventArgs(string.Format(debugMessage, args)));
}
private void fireProgress(int progressPercentage)
{
EventHandler<ProgressChangedEventArgs> progress = this.Progress;
if (progress == null)
return;
progress(new object(), new ProgressChangedEventArgs(progressPercentage, (object) string.Empty));
}
}
} }

View file

@ -6,11 +6,11 @@
namespace libWiiSharp namespace libWiiSharp
{ {
public enum Region : ushort public enum Region : ushort
{ {
Japan, Japan,
USA, USA,
Europe, Europe,
Free, Free,
} }
} }

311
Shared.cs
View file

@ -11,138 +11,185 @@ using System.Net;
namespace libWiiSharp namespace libWiiSharp
{ {
public static class Shared public static class Shared
{
public static string[] MergeStringArrays(string[] a, string[] b)
{ {
List<string> stringList = new List<string>((IEnumerable<string>) a); public static string[] MergeStringArrays(string[] a, string[] b)
foreach (string str in b) {
{ List<string> stringList = new List<string>(a);
if (!stringList.Contains(str)) foreach (string str in b)
stringList.Add(str); {
} if (!stringList.Contains(str))
stringList.Sort(); {
return stringList.ToArray(); stringList.Add(str);
}
}
stringList.Sort();
return stringList.ToArray();
}
public static bool CompareByteArrays(
byte[] first,
int firstIndex,
byte[] second,
int secondIndex,
int length)
{
if (first.Length < length || second.Length < length)
{
return false;
}
for (int index = 0; index < length; ++index)
{
if (first[firstIndex + index] != second[secondIndex + index])
{
return false;
}
}
return true;
}
public static bool CompareByteArrays(byte[] first, byte[] second)
{
if (first.Length != second.Length)
{
return false;
}
for (int index = 0; index < first.Length; ++index)
{
if (first[index] != second[index])
{
return false;
}
}
return true;
}
public static string ByteArrayToString(byte[] byteArray, char separator = ' ')
{
string str = string.Empty;
foreach (byte num in byteArray)
{
str = str + num.ToString("x2").ToUpper() + separator.ToString();
}
return str.Remove(str.Length - 1);
}
public static byte[] HexStringToByteArray(string hexString)
{
byte[] numArray = new byte[hexString.Length / 2];
for (int index = 0; index < hexString.Length / 2; ++index)
{
numArray[index] = byte.Parse(hexString.Substring(index * 2, 2), NumberStyles.HexNumber);
}
return numArray;
}
public static int CountCharsInString(string theString, char theChar)
{
int num1 = 0;
foreach (int num2 in theString)
{
if (num2 == theChar)
{
++num1;
}
}
return num1;
}
public static long AddPadding(long value)
{
return Shared.AddPadding(value, 64);
}
public static long AddPadding(long value, int padding)
{
if (value % padding != 0L)
{
value += padding - value % padding;
}
return value;
}
public static int AddPadding(int value)
{
return Shared.AddPadding(value, 64);
}
public static int AddPadding(int value, int padding)
{
if (value % padding != 0)
{
value += padding - value % padding;
}
return value;
}
public static ushort Swap(ushort value)
{
return (ushort)IPAddress.HostToNetworkOrder((short)value);
}
public static uint Swap(uint value)
{
return (uint)IPAddress.HostToNetworkOrder((int)value);
}
public static ulong Swap(ulong value)
{
return (ulong)IPAddress.HostToNetworkOrder((long)value);
}
public static byte[] UShortArrayToByteArray(ushort[] array)
{
List<byte> byteList = new List<byte>();
foreach (ushort num in array)
{
byte[] bytes = BitConverter.GetBytes(num);
byteList.AddRange(bytes);
}
return byteList.ToArray();
}
public static byte[] UIntArrayToByteArray(uint[] array)
{
List<byte> byteList = new List<byte>();
foreach (uint num in array)
{
byte[] bytes = BitConverter.GetBytes(num);
byteList.AddRange(bytes);
}
return byteList.ToArray();
}
public static uint[] ByteArrayToUIntArray(byte[] array)
{
uint[] numArray = new uint[array.Length / 4];
int num = 0;
for (int startIndex = 0; startIndex < array.Length; startIndex += 4)
{
numArray[num++] = BitConverter.ToUInt32(array, startIndex);
}
return numArray;
}
public static ushort[] ByteArrayToUShortArray(byte[] array)
{
ushort[] numArray = new ushort[array.Length / 2];
int num = 0;
for (int startIndex = 0; startIndex < array.Length; startIndex += 2)
{
numArray[num++] = BitConverter.ToUInt16(array, startIndex);
}
return numArray;
}
} }
public static bool CompareByteArrays(
byte[] first,
int firstIndex,
byte[] second,
int secondIndex,
int length)
{
if (first.Length < length || second.Length < length)
return false;
for (int index = 0; index < length; ++index)
{
if ((int) first[firstIndex + index] != (int) second[secondIndex + index])
return false;
}
return true;
}
public static bool CompareByteArrays(byte[] first, byte[] second)
{
if (first.Length != second.Length)
return false;
for (int index = 0; index < first.Length; ++index)
{
if ((int) first[index] != (int) second[index])
return false;
}
return true;
}
public static string ByteArrayToString(byte[] byteArray, char separator = ' ')
{
string str = string.Empty;
foreach (byte num in byteArray)
str = str + num.ToString("x2").ToUpper() + separator.ToString();
return str.Remove(str.Length - 1);
}
public static byte[] HexStringToByteArray(string hexString)
{
byte[] numArray = new byte[hexString.Length / 2];
for (int index = 0; index < hexString.Length / 2; ++index)
numArray[index] = byte.Parse(hexString.Substring(index * 2, 2), NumberStyles.HexNumber);
return numArray;
}
public static int CountCharsInString(string theString, char theChar)
{
int num1 = 0;
foreach (int num2 in theString)
{
if (num2 == (int) theChar)
++num1;
}
return num1;
}
public static long AddPadding(long value) => Shared.AddPadding(value, 64);
public static long AddPadding(long value, int padding)
{
if (value % (long) padding != 0L)
value += (long) padding - value % (long) padding;
return value;
}
public static int AddPadding(int value) => Shared.AddPadding(value, 64);
public static int AddPadding(int value, int padding)
{
if (value % padding != 0)
value += padding - value % padding;
return value;
}
public static ushort Swap(ushort value) => (ushort) IPAddress.HostToNetworkOrder((short) value);
public static uint Swap(uint value) => (uint) IPAddress.HostToNetworkOrder((int) value);
public static ulong Swap(ulong value) => (ulong) IPAddress.HostToNetworkOrder((long) value);
public static byte[] UShortArrayToByteArray(ushort[] array)
{
List<byte> byteList = new List<byte>();
foreach (ushort num in array)
{
byte[] bytes = BitConverter.GetBytes(num);
byteList.AddRange((IEnumerable<byte>) bytes);
}
return byteList.ToArray();
}
public static byte[] UIntArrayToByteArray(uint[] array)
{
List<byte> byteList = new List<byte>();
foreach (uint num in array)
{
byte[] bytes = BitConverter.GetBytes(num);
byteList.AddRange((IEnumerable<byte>) bytes);
}
return byteList.ToArray();
}
public static uint[] ByteArrayToUIntArray(byte[] array)
{
uint[] numArray = new uint[array.Length / 4];
int num = 0;
for (int startIndex = 0; startIndex < array.Length; startIndex += 4)
numArray[num++] = BitConverter.ToUInt32(array, startIndex);
return numArray;
}
public static ushort[] ByteArrayToUShortArray(byte[] array)
{
ushort[] numArray = new ushort[array.Length / 2];
int num = 0;
for (int startIndex = 0; startIndex < array.Length; startIndex += 2)
numArray[num++] = BitConverter.ToUInt16(array, startIndex);
return numArray;
}
}
} }

View file

@ -6,11 +6,11 @@
namespace libWiiSharp namespace libWiiSharp
{ {
public enum StoreType public enum StoreType
{ {
EncryptedContent, EncryptedContent,
DecryptedContent, DecryptedContent,
WAD, WAD,
All, All,
} }
} }

1026
TMD.cs

File diff suppressed because it is too large Load diff

View file

@ -6,42 +6,42 @@
namespace libWiiSharp namespace libWiiSharp
{ {
public class TMD_Content public class TMD_Content
{
private uint contentId;
private ushort index;
private ushort type;
private ulong size;
private byte[] hash = new byte[20];
public uint ContentID
{ {
get => this.contentId; private uint contentId;
set => this.contentId = value; private ushort index;
} private ushort type;
private ulong size;
private byte[] hash = new byte[20];
public ushort Index public uint ContentID
{ {
get => this.index; get => contentId;
set => this.index = value; set => contentId = value;
} }
public ContentType Type public ushort Index
{ {
get => (ContentType) this.type; get => index;
set => this.type = (ushort) value; set => index = value;
} }
public ulong Size public ContentType Type
{ {
get => this.size; get => (ContentType)type;
set => this.size = value; set => type = (ushort)value;
} }
public byte[] Hash public ulong Size
{ {
get => this.hash; get => size;
set => this.hash = value; set => size = value;
}
public byte[] Hash
{
get => hash;
set => hash = value;
}
} }
}
} }

2599
TPL.cs

File diff suppressed because it is too large Load diff

View file

@ -9,27 +9,27 @@ using System.IO;
namespace libWiiSharp namespace libWiiSharp
{ {
public class TPL_Header public class TPL_Header
{
private uint tplMagic = 2142000;
private uint numOfTextures;
private uint headerSize = 12;
public uint TplMagic => this.tplMagic;
public uint NumOfTextures
{ {
get => this.numOfTextures; private readonly uint tplMagic = 2142000;
set => this.numOfTextures = value; private uint numOfTextures;
} private readonly uint headerSize = 12;
public uint HeaderSize => this.headerSize; public uint TplMagic => tplMagic;
public void Write(Stream writeStream) public uint NumOfTextures
{ {
writeStream.Write(BitConverter.GetBytes(Shared.Swap(this.tplMagic)), 0, 4); get => numOfTextures;
writeStream.Write(BitConverter.GetBytes(Shared.Swap(this.numOfTextures)), 0, 4); set => numOfTextures = value;
writeStream.Write(BitConverter.GetBytes(Shared.Swap(this.headerSize)), 0, 4); }
public uint HeaderSize => headerSize;
public void Write(Stream writeStream)
{
writeStream.Write(BitConverter.GetBytes(Shared.Swap(tplMagic)), 0, 4);
writeStream.Write(BitConverter.GetBytes(Shared.Swap(numOfTextures)), 0, 4);
writeStream.Write(BitConverter.GetBytes(Shared.Swap(headerSize)), 0, 4);
}
} }
}
} }

View file

@ -6,11 +6,11 @@
namespace libWiiSharp namespace libWiiSharp
{ {
public enum TPL_PaletteFormat public enum TPL_PaletteFormat
{ {
IA8 = 0, IA8 = 0,
RGB565 = 1, RGB565 = 1,
RGB5A3 = 2, RGB5A3 = 2,
None = 255, // 0x000000FF None = 255, // 0x000000FF
} }
} }

View file

@ -9,51 +9,51 @@ using System.IO;
namespace libWiiSharp namespace libWiiSharp
{ {
public class TPL_PaletteHeader public class TPL_PaletteHeader
{
private ushort numberOfItems;
private byte unpacked;
private byte pad;
private uint paletteFormat = (uint) byte.MaxValue;
private uint paletteDataOffset;
public ushort NumberOfItems
{ {
get => this.numberOfItems; private ushort numberOfItems;
set => this.numberOfItems = value; private byte unpacked;
} private byte pad;
private uint paletteFormat = byte.MaxValue;
private uint paletteDataOffset;
public byte Unpacked public ushort NumberOfItems
{ {
get => this.unpacked; get => numberOfItems;
set => this.unpacked = value; set => numberOfItems = value;
} }
public byte Pad public byte Unpacked
{ {
get => this.pad; get => unpacked;
set => this.pad = value; set => unpacked = value;
} }
public uint PaletteFormat public byte Pad
{ {
get => this.paletteFormat; get => pad;
set => this.paletteFormat = value; set => pad = value;
} }
public uint PaletteDataOffset public uint PaletteFormat
{ {
get => this.paletteDataOffset; get => paletteFormat;
set => this.paletteDataOffset = value; set => paletteFormat = value;
} }
public void Write(Stream writeStream) public uint PaletteDataOffset
{ {
writeStream.Write(BitConverter.GetBytes(Shared.Swap(this.numberOfItems)), 0, 2); get => paletteDataOffset;
writeStream.WriteByte(this.unpacked); set => paletteDataOffset = value;
writeStream.WriteByte(this.pad); }
writeStream.Write(BitConverter.GetBytes(Shared.Swap(this.paletteFormat)), 0, 4);
writeStream.Write(BitConverter.GetBytes(Shared.Swap(this.paletteDataOffset)), 0, 4); public void Write(Stream writeStream)
{
writeStream.Write(BitConverter.GetBytes(Shared.Swap(numberOfItems)), 0, 2);
writeStream.WriteByte(unpacked);
writeStream.WriteByte(pad);
writeStream.Write(BitConverter.GetBytes(Shared.Swap(paletteFormat)), 0, 4);
writeStream.Write(BitConverter.GetBytes(Shared.Swap(paletteDataOffset)), 0, 4);
}
} }
}
} }

View file

@ -9,27 +9,27 @@ using System.IO;
namespace libWiiSharp namespace libWiiSharp
{ {
public class TPL_TextureEntry public class TPL_TextureEntry
{
private uint textureHeaderOffset;
private uint paletteHeaderOffset;
public uint TextureHeaderOffset
{ {
get => this.textureHeaderOffset; private uint textureHeaderOffset;
set => this.textureHeaderOffset = value; private uint paletteHeaderOffset;
}
public uint PaletteHeaderOffset public uint TextureHeaderOffset
{ {
get => this.paletteHeaderOffset; get => textureHeaderOffset;
set => this.paletteHeaderOffset = value; set => textureHeaderOffset = value;
} }
public void Write(Stream writeStream) public uint PaletteHeaderOffset
{ {
writeStream.Write(BitConverter.GetBytes(Shared.Swap(this.textureHeaderOffset)), 0, 4); get => paletteHeaderOffset;
writeStream.Write(BitConverter.GetBytes(Shared.Swap(this.paletteHeaderOffset)), 0, 4); set => paletteHeaderOffset = value;
}
public void Write(Stream writeStream)
{
writeStream.Write(BitConverter.GetBytes(Shared.Swap(textureHeaderOffset)), 0, 4);
writeStream.Write(BitConverter.GetBytes(Shared.Swap(paletteHeaderOffset)), 0, 4);
}
} }
}
} }

View file

@ -6,18 +6,18 @@
namespace libWiiSharp namespace libWiiSharp
{ {
public enum TPL_TextureFormat public enum TPL_TextureFormat
{ {
I4 = 0, I4 = 0,
I8 = 1, I8 = 1,
IA4 = 2, IA4 = 2,
IA8 = 3, IA8 = 3,
RGB565 = 4, RGB565 = 4,
RGB5A3 = 5, RGB5A3 = 5,
RGBA8 = 6, RGBA8 = 6,
CI4 = 8, CI4 = 8,
CI8 = 9, CI8 = 9,
CI14X2 = 10, // 0x0000000A CI14X2 = 10, // 0x0000000A
CMP = 14, // 0x0000000E CMP = 14, // 0x0000000E
} }
} }

View file

@ -9,115 +9,115 @@ using System.IO;
namespace libWiiSharp namespace libWiiSharp
{ {
public class TPL_TextureHeader public class TPL_TextureHeader
{
private ushort textureHeight;
private ushort textureWidth;
private uint textureFormat;
private uint textureDataOffset;
private uint wrapS;
private uint wrapT;
private uint minFilter = 1;
private uint magFilter = 1;
private uint lodBias;
private byte edgeLod;
private byte minLod;
private byte maxLod;
private byte unpacked;
public ushort TextureHeight
{ {
get => this.textureHeight; private ushort textureHeight;
set => this.textureHeight = value; private ushort textureWidth;
} private uint textureFormat;
private uint textureDataOffset;
private uint wrapS;
private uint wrapT;
private uint minFilter = 1;
private uint magFilter = 1;
private uint lodBias;
private byte edgeLod;
private byte minLod;
private byte maxLod;
private byte unpacked;
public ushort TextureWidth public ushort TextureHeight
{ {
get => this.textureWidth; get => textureHeight;
set => this.textureWidth = value; set => textureHeight = value;
} }
public uint TextureFormat public ushort TextureWidth
{ {
get => this.textureFormat; get => textureWidth;
set => this.textureFormat = value; set => textureWidth = value;
} }
public uint TextureDataOffset public uint TextureFormat
{ {
get => this.textureDataOffset; get => textureFormat;
set => this.textureDataOffset = value; set => textureFormat = value;
} }
public uint WrapS public uint TextureDataOffset
{ {
get => this.wrapS; get => textureDataOffset;
set => this.wrapS = value; set => textureDataOffset = value;
} }
public uint WrapT public uint WrapS
{ {
get => this.wrapT; get => wrapS;
set => this.wrapT = value; set => wrapS = value;
} }
public uint MinFilter public uint WrapT
{ {
get => this.minFilter; get => wrapT;
set => this.minFilter = value; set => wrapT = value;
} }
public uint MagFilter public uint MinFilter
{ {
get => this.magFilter; get => minFilter;
set => this.magFilter = value; set => minFilter = value;
} }
public uint LodBias public uint MagFilter
{ {
get => this.lodBias; get => magFilter;
set => this.lodBias = value; set => magFilter = value;
} }
public byte EdgeLod public uint LodBias
{ {
get => this.edgeLod; get => lodBias;
set => this.edgeLod = value; set => lodBias = value;
} }
public byte MinLod public byte EdgeLod
{ {
get => this.minLod; get => edgeLod;
set => this.minLod = value; set => edgeLod = value;
} }
public byte MaxLod public byte MinLod
{ {
get => this.maxLod; get => minLod;
set => this.maxLod = value; set => minLod = value;
} }
public byte Unpacked public byte MaxLod
{ {
get => this.unpacked; get => maxLod;
set => this.unpacked = value; set => maxLod = value;
} }
public void Write(Stream writeStream) public byte Unpacked
{ {
writeStream.Write(BitConverter.GetBytes(Shared.Swap(this.textureHeight)), 0, 2); get => unpacked;
writeStream.Write(BitConverter.GetBytes(Shared.Swap(this.textureWidth)), 0, 2); set => unpacked = value;
writeStream.Write(BitConverter.GetBytes(Shared.Swap(this.textureFormat)), 0, 4); }
writeStream.Write(BitConverter.GetBytes(Shared.Swap(this.textureDataOffset)), 0, 4);
writeStream.Write(BitConverter.GetBytes(Shared.Swap(this.wrapS)), 0, 4); public void Write(Stream writeStream)
writeStream.Write(BitConverter.GetBytes(Shared.Swap(this.wrapT)), 0, 4); {
writeStream.Write(BitConverter.GetBytes(Shared.Swap(this.minFilter)), 0, 4); writeStream.Write(BitConverter.GetBytes(Shared.Swap(textureHeight)), 0, 2);
writeStream.Write(BitConverter.GetBytes(Shared.Swap(this.magFilter)), 0, 4); writeStream.Write(BitConverter.GetBytes(Shared.Swap(textureWidth)), 0, 2);
writeStream.Write(BitConverter.GetBytes(Shared.Swap(this.lodBias)), 0, 4); writeStream.Write(BitConverter.GetBytes(Shared.Swap(textureFormat)), 0, 4);
writeStream.WriteByte(this.edgeLod); writeStream.Write(BitConverter.GetBytes(Shared.Swap(textureDataOffset)), 0, 4);
writeStream.WriteByte(this.minLod); writeStream.Write(BitConverter.GetBytes(Shared.Swap(wrapS)), 0, 4);
writeStream.WriteByte(this.maxLod); writeStream.Write(BitConverter.GetBytes(Shared.Swap(wrapT)), 0, 4);
writeStream.WriteByte(this.unpacked); writeStream.Write(BitConverter.GetBytes(Shared.Swap(minFilter)), 0, 4);
writeStream.Write(BitConverter.GetBytes(Shared.Swap(magFilter)), 0, 4);
writeStream.Write(BitConverter.GetBytes(Shared.Swap(lodBias)), 0, 4);
writeStream.WriteByte(edgeLod);
writeStream.WriteByte(minLod);
writeStream.WriteByte(maxLod);
writeStream.WriteByte(unpacked);
}
} }
}
} }

911
Ticket.cs
View file

@ -19,474 +19,523 @@ namespace libWiiSharp
public class Ticket : IDisposable public class Ticket : IDisposable
{ {
private byte newKeyIndex; private byte newKeyIndex;
private byte[] decryptedTitleKey = new byte[16]; private byte[] decryptedTitleKey = new byte[16];
private bool fakeSign; private bool fakeSign;
private bool titleKeyChanged; private bool titleKeyChanged;
private byte[] newEncryptedTitleKey = new byte[0]; private byte[] newEncryptedTitleKey = new byte[0];
private bool reDecrypt; private bool reDecrypt;
private uint signatureExponent = 65537; private uint signatureExponent = 65537;
private byte[] signature = new byte[256]; private byte[] signature = new byte[256];
private byte[] padding = new byte[60]; private byte[] padding = new byte[60];
private byte[] issuer = new byte[64]; private byte[] issuer = new byte[64];
private byte[] unknown = new byte[63]; private byte[] unknown = new byte[63];
private byte[] encryptedTitleKey = new byte[16]; private byte[] encryptedTitleKey = new byte[16];
private byte unknown2; private byte unknown2;
private ulong ticketId; private ulong ticketId;
private uint consoleId; private uint consoleId;
private ulong titleId; private ulong titleId;
private ushort unknown3 = ushort.MaxValue; private ushort unknown3 = ushort.MaxValue;
private ushort numOfDlc; private ushort numOfDlc;
private ulong unknown4; private ulong unknown4;
private byte padding2; private byte padding2;
private byte commonKeyIndex; private byte commonKeyIndex;
private byte[] unknown5 = new byte[48]; private byte[] unknown5 = new byte[48];
private byte[] unknown6 = new byte[32]; private byte[] unknown6 = new byte[32];
private ushort padding3; private ushort padding3;
private uint enableTimeLimit; private uint enableTimeLimit;
private uint timeLimit; private uint timeLimit;
private byte[] padding4 = new byte[88]; private byte[] padding4 = new byte[88];
private bool isDisposed; private bool isDisposed;
public byte[] TitleKey public byte[] TitleKey
{ {
get => this.decryptedTitleKey; get => decryptedTitleKey;
set set
{ {
this.decryptedTitleKey = value; decryptedTitleKey = value;
this.titleKeyChanged = true; titleKeyChanged = true;
this.reDecrypt = false; reDecrypt = false;
} }
} }
public CommonKeyType CommonKeyIndex public CommonKeyType CommonKeyIndex
{ {
get => (CommonKeyType) this.newKeyIndex; get => (CommonKeyType)newKeyIndex;
set => this.newKeyIndex = (byte) value; set => newKeyIndex = (byte)value;
} }
public ulong TicketID public ulong TicketID
{ {
get => this.ticketId; get => ticketId;
set => this.ticketId = value; set => ticketId = value;
} }
public uint ConsoleID public uint ConsoleID
{ {
get => this.consoleId; get => consoleId;
set => this.consoleId = value; set => consoleId = value;
} }
public ulong TitleID public ulong TitleID
{ {
get => this.titleId; get => titleId;
set set
{ {
this.titleId = value; titleId = value;
if (!this.reDecrypt) if (!reDecrypt)
return; {
this.reDecryptTitleKey(); return;
} }
}
public ushort NumOfDLC ReDecryptTitleKey();
{ }
get => this.numOfDlc; }
set => this.numOfDlc = value;
}
public bool FakeSign public ushort NumOfDLC
{ {
get => this.fakeSign; get => numOfDlc;
set => this.fakeSign = value; set => numOfDlc = value;
} }
public bool TitleKeyChanged => this.titleKeyChanged; public bool FakeSign
{
get => fakeSign;
set => fakeSign = value;
}
public event EventHandler<MessageEventArgs> Debug; public bool TitleKeyChanged => titleKeyChanged;
~Ticket() => this.Dispose(false); public event EventHandler<MessageEventArgs> Debug;
public void Dispose() ~Ticket() => Dispose(false);
{
this.Dispose(true);
GC.SuppressFinalize((object) this);
}
protected virtual void Dispose(bool disposing) public void Dispose()
{ {
if (disposing && !this.isDisposed) Dispose(true);
{ GC.SuppressFinalize(this);
this.decryptedTitleKey = (byte[]) null; }
this.newEncryptedTitleKey = (byte[]) null;
this.signature = (byte[]) null;
this.padding = (byte[]) null;
this.issuer = (byte[]) null;
this.unknown = (byte[]) null;
this.encryptedTitleKey = (byte[]) null;
this.unknown5 = (byte[]) null;
this.unknown6 = (byte[]) null;
this.padding4 = (byte[]) null;
}
this.isDisposed = true;
}
public static Ticket Load(string pathToTicket) => Ticket.Load(File.ReadAllBytes(pathToTicket)); protected virtual void Dispose(bool disposing)
{
if (disposing && !isDisposed)
{
decryptedTitleKey = null;
newEncryptedTitleKey = null;
signature = null;
padding = null;
issuer = null;
unknown = null;
encryptedTitleKey = null;
unknown5 = null;
unknown6 = null;
padding4 = null;
}
isDisposed = true;
}
public static Ticket Load(byte[] ticket) public static Ticket Load(string pathToTicket)
{ {
Ticket ticket1 = new Ticket(); return Ticket.Load(File.ReadAllBytes(pathToTicket));
MemoryStream memoryStream = new MemoryStream(ticket); }
try
{
ticket1.parseTicket((Stream) memoryStream);
}
catch
{
memoryStream.Dispose();
throw;
}
memoryStream.Dispose();
return ticket1;
}
public static Ticket Load(Stream ticket) public static Ticket Load(byte[] ticket)
{ {
Ticket ticket1 = new Ticket(); Ticket ticket1 = new Ticket();
ticket1.parseTicket(ticket); MemoryStream memoryStream = new MemoryStream(ticket);
return ticket1; try
} {
ticket1.ParseTicket(memoryStream);
}
catch
{
memoryStream.Dispose();
throw;
}
memoryStream.Dispose();
return ticket1;
}
public void LoadFile(string pathToTicket) => this.LoadFile(File.ReadAllBytes(pathToTicket)); public static Ticket Load(Stream ticket)
{
Ticket ticket1 = new Ticket();
ticket1.ParseTicket(ticket);
return ticket1;
}
public void LoadFile(byte[] ticket) public void LoadFile(string pathToTicket)
{ {
MemoryStream memoryStream = new MemoryStream(ticket); LoadFile(File.ReadAllBytes(pathToTicket));
try }
{
this.parseTicket((Stream) memoryStream);
}
catch
{
memoryStream.Dispose();
throw;
}
memoryStream.Dispose();
}
public void LoadFile(Stream ticket) => this.parseTicket(ticket); public void LoadFile(byte[] ticket)
{
MemoryStream memoryStream = new MemoryStream(ticket);
try
{
ParseTicket(memoryStream);
}
catch
{
memoryStream.Dispose();
throw;
}
memoryStream.Dispose();
}
public void Save(string savePath) => this.Save(savePath, false); public void LoadFile(Stream ticket)
{
ParseTicket(ticket);
}
public void Save(string savePath, bool fakeSign) public void Save(string savePath)
{ {
if (fakeSign) Save(savePath, false);
this.fakeSign = true; }
if (File.Exists(savePath))
File.Delete(savePath);
using (FileStream fileStream = new FileStream(savePath, FileMode.Create))
this.writeToStream((Stream) fileStream);
}
public MemoryStream ToMemoryStream() => this.ToMemoryStream(false); public void Save(string savePath, bool fakeSign)
{
if (fakeSign)
{
this.fakeSign = true;
}
public MemoryStream ToMemoryStream(bool fakeSign) if (File.Exists(savePath))
{ {
if (fakeSign) File.Delete(savePath);
this.fakeSign = true; }
MemoryStream memoryStream = new MemoryStream();
try
{
this.writeToStream((Stream) memoryStream);
return memoryStream;
}
catch
{
memoryStream.Dispose();
throw;
}
}
public byte[] ToByteArray() => this.ToByteArray(false); using FileStream fileStream = new FileStream(savePath, FileMode.Create);
WriteToStream(fileStream);
}
public byte[] ToByteArray(bool fakeSign) public MemoryStream ToMemoryStream()
{ {
if (fakeSign) return ToMemoryStream(false);
this.fakeSign = true; }
MemoryStream memoryStream = new MemoryStream();
try
{
this.writeToStream((Stream) memoryStream);
}
catch
{
memoryStream.Dispose();
throw;
}
byte[] array = memoryStream.ToArray();
memoryStream.Dispose();
return array;
}
public void SetTitleKey(string newTitleKey) => this.SetTitleKey(newTitleKey.ToCharArray()); public MemoryStream ToMemoryStream(bool fakeSign)
{
if (fakeSign)
{
this.fakeSign = true;
}
public void SetTitleKey(char[] newTitleKey) MemoryStream memoryStream = new MemoryStream();
{ try
if (newTitleKey.Length != 16) {
throw new Exception("The title key must be 16 characters long!"); WriteToStream(memoryStream);
for (int index = 0; index < 16; ++index) return memoryStream;
this.encryptedTitleKey[index] = (byte) newTitleKey[index]; }
this.decryptTitleKey(); catch
this.titleKeyChanged = true; {
this.reDecrypt = true; memoryStream.Dispose();
this.newEncryptedTitleKey = this.encryptedTitleKey; throw;
} }
}
public void SetTitleKey(byte[] newTitleKey) public byte[] ToByteArray()
{ {
this.encryptedTitleKey = newTitleKey.Length == 16 ? newTitleKey : throw new Exception("The title key must be 16 characters long!"); return ToByteArray(false);
this.decryptTitleKey(); }
this.titleKeyChanged = true;
this.reDecrypt = true;
this.newEncryptedTitleKey = newTitleKey;
}
public string GetUpperTitleID() public byte[] ToByteArray(bool fakeSign)
{ {
byte[] bytes = BitConverter.GetBytes(Shared.Swap((uint) this.titleId)); if (fakeSign)
return new string(new char[4] {
{ this.fakeSign = true;
}
MemoryStream memoryStream = new MemoryStream();
try
{
WriteToStream(memoryStream);
}
catch
{
memoryStream.Dispose();
throw;
}
byte[] array = memoryStream.ToArray();
memoryStream.Dispose();
return array;
}
public void SetTitleKey(string newTitleKey)
{
SetTitleKey(newTitleKey.ToCharArray());
}
public void SetTitleKey(char[] newTitleKey)
{
if (newTitleKey.Length != 16)
{
throw new Exception("The title key must be 16 characters long!");
}
for (int index = 0; index < 16; ++index)
{
encryptedTitleKey[index] = (byte)newTitleKey[index];
}
DecryptTitleKey();
titleKeyChanged = true;
reDecrypt = true;
newEncryptedTitleKey = encryptedTitleKey;
}
public void SetTitleKey(byte[] newTitleKey)
{
encryptedTitleKey = newTitleKey.Length == 16 ? newTitleKey : throw new Exception("The title key must be 16 characters long!");
DecryptTitleKey();
titleKeyChanged = true;
reDecrypt = true;
newEncryptedTitleKey = newTitleKey;
}
public string GetUpperTitleID()
{
byte[] bytes = BitConverter.GetBytes(Shared.Swap((uint)titleId));
return new string(new char[4]
{
(char) bytes[0], (char) bytes[0],
(char) bytes[1], (char) bytes[1],
(char) bytes[2], (char) bytes[2],
(char) bytes[3] (char) bytes[3]
}); });
}
private void writeToStream(Stream writeStream)
{
this.fireDebug("Writing Ticket...");
this.fireDebug(" Encrypting Title Key...");
this.encryptTitleKey();
this.fireDebug(" -> Decrypted Title Key: {0}", (object) Shared.ByteArrayToString(this.decryptedTitleKey));
this.fireDebug(" -> Encrypted Title Key: {0}", (object) Shared.ByteArrayToString(this.encryptedTitleKey));
if (this.fakeSign)
{
this.fireDebug(" Clearing Signature...");
this.signature = new byte[256];
}
MemoryStream memoryStream = new MemoryStream();
memoryStream.Seek(0L, SeekOrigin.Begin);
this.fireDebug(" Writing Signature Exponent... (Offset: 0x{0})", (object) memoryStream.Position.ToString("x8").ToUpper());
memoryStream.Write(BitConverter.GetBytes(Shared.Swap(this.signatureExponent)), 0, 4);
this.fireDebug(" Writing Signature... (Offset: 0x{0})", (object) memoryStream.Position.ToString("x8").ToUpper());
memoryStream.Write(this.signature, 0, this.signature.Length);
this.fireDebug(" Writing Padding... (Offset: 0x{0})", (object) memoryStream.Position.ToString("x8").ToUpper());
memoryStream.Write(this.padding, 0, this.padding.Length);
this.fireDebug(" Writing Issuer... (Offset: 0x{0})", (object) memoryStream.Position.ToString("x8").ToUpper());
memoryStream.Write(this.issuer, 0, this.issuer.Length);
this.fireDebug(" Writing Unknown... (Offset: 0x{0})", (object) memoryStream.Position.ToString("x8").ToUpper());
memoryStream.Write(this.unknown, 0, this.unknown.Length);
this.fireDebug(" Writing Title Key... (Offset: 0x{0})", (object) memoryStream.Position.ToString("x8").ToUpper());
memoryStream.Write(this.encryptedTitleKey, 0, this.encryptedTitleKey.Length);
this.fireDebug(" Writing Unknown2... (Offset: 0x{0})", (object) memoryStream.Position.ToString("x8").ToUpper());
memoryStream.WriteByte(this.unknown2);
this.fireDebug(" Writing Ticket ID... (Offset: 0x{0})", (object) memoryStream.Position.ToString("x8").ToUpper());
memoryStream.Write(BitConverter.GetBytes(Shared.Swap(this.ticketId)), 0, 8);
this.fireDebug(" Writing Console ID... (Offset: 0x{0})", (object) memoryStream.Position.ToString("x8").ToUpper());
memoryStream.Write(BitConverter.GetBytes(Shared.Swap(this.consoleId)), 0, 4);
this.fireDebug(" Writing Title ID... (Offset: 0x{0})", (object) memoryStream.Position.ToString("x8").ToUpper());
memoryStream.Write(BitConverter.GetBytes(Shared.Swap(this.titleId)), 0, 8);
this.fireDebug(" Writing Unknwon3... (Offset: 0x{0})", (object) memoryStream.Position.ToString("x8").ToUpper());
memoryStream.Write(BitConverter.GetBytes(Shared.Swap(this.unknown3)), 0, 2);
this.fireDebug(" Writing NumOfDLC... (Offset: 0x{0})", (object) memoryStream.Position.ToString("x8").ToUpper());
memoryStream.Write(BitConverter.GetBytes(Shared.Swap(this.numOfDlc)), 0, 2);
this.fireDebug(" Writing Unknwon4... (Offset: 0x{0})", (object) memoryStream.Position.ToString("x8").ToUpper());
memoryStream.Write(BitConverter.GetBytes(Shared.Swap(this.unknown4)), 0, 8);
this.fireDebug(" Writing Padding2... (Offset: 0x{0})", (object) memoryStream.Position.ToString("x8").ToUpper());
memoryStream.WriteByte(this.padding2);
this.fireDebug(" Writing Common Key Index... (Offset: 0x{0})", (object) memoryStream.Position.ToString("x8").ToUpper());
memoryStream.WriteByte(this.commonKeyIndex);
object[] objArray1 = new object[1];
long position = memoryStream.Position;
objArray1[0] = (object) position.ToString("x8").ToUpper();
this.fireDebug(" Writing Unknown5... (Offset: 0x{0})", objArray1);
memoryStream.Write(this.unknown5, 0, this.unknown5.Length);
object[] objArray2 = new object[1];
position = memoryStream.Position;
objArray2[0] = (object) position.ToString("x8").ToUpper();
this.fireDebug(" Writing Unknown6... (Offset: 0x{0})", objArray2);
memoryStream.Write(this.unknown6, 0, this.unknown6.Length);
object[] objArray3 = new object[1];
position = memoryStream.Position;
objArray3[0] = (object) position.ToString("x8").ToUpper();
this.fireDebug(" Writing Padding3... (Offset: 0x{0})", objArray3);
memoryStream.Write(BitConverter.GetBytes(Shared.Swap(this.padding3)), 0, 2);
object[] objArray4 = new object[1];
position = memoryStream.Position;
objArray4[0] = (object) position.ToString("x8").ToUpper();
this.fireDebug(" Writing Enable Time Limit... (Offset: 0x{0})", objArray4);
memoryStream.Write(BitConverter.GetBytes(Shared.Swap(this.enableTimeLimit)), 0, 4);
object[] objArray5 = new object[1];
position = memoryStream.Position;
objArray5[0] = (object) position.ToString("x8").ToUpper();
this.fireDebug(" Writing Time Limit... (Offset: 0x{0})", objArray5);
memoryStream.Write(BitConverter.GetBytes(Shared.Swap(this.timeLimit)), 0, 4);
object[] objArray6 = new object[1];
position = memoryStream.Position;
objArray6[0] = (object) position.ToString("x8").ToUpper();
this.fireDebug(" Writing Padding4... (Offset: 0x{0})", objArray6);
memoryStream.Write(this.padding4, 0, this.padding4.Length);
byte[] array = memoryStream.ToArray();
memoryStream.Dispose();
if (this.fakeSign)
{
this.fireDebug(" Fakesigning Ticket...");
byte[] numArray = new byte[20];
SHA1 shA1 = SHA1.Create();
for (ushort index = 0; index < ushort.MaxValue; ++index)
{
byte[] bytes = BitConverter.GetBytes(index);
array[498] = bytes[1];
array[499] = bytes[0];
if (shA1.ComputeHash(array)[0] == (byte) 0)
{
this.fireDebug(" -> Signed ({0})", (object) index);
break;
}
if (index == (ushort) 65534)
{
this.fireDebug(" -> Signing Failed...");
throw new Exception("Fakesigning failed...");
}
} }
shA1.Clear();
}
writeStream.Seek(0L, SeekOrigin.Begin);
writeStream.Write(array, 0, array.Length);
this.fireDebug("Writing Ticket Finished...");
}
private void parseTicket(Stream ticketFile) private void WriteToStream(Stream writeStream)
{ {
this.fireDebug("Parsing Ticket..."); FireDebug("Writing Ticket...");
ticketFile.Seek(0L, SeekOrigin.Begin); FireDebug(" Encrypting Title Key...");
byte[] buffer = new byte[8]; EncryptTitleKey();
this.fireDebug(" Reading Signature Exponent... (Offset: 0x{0})", (object) ticketFile.Position.ToString("x8").ToUpper()); FireDebug(" -> Decrypted Title Key: {0}", (object)Shared.ByteArrayToString(decryptedTitleKey));
ticketFile.Read(buffer, 0, 4); FireDebug(" -> Encrypted Title Key: {0}", (object)Shared.ByteArrayToString(encryptedTitleKey));
this.signatureExponent = Shared.Swap(BitConverter.ToUInt32(buffer, 0)); if (fakeSign)
this.fireDebug(" Reading Signature... (Offset: 0x{0})", (object) ticketFile.Position.ToString("x8").ToUpper()); {
ticketFile.Read(this.signature, 0, this.signature.Length); FireDebug(" Clearing Signature...");
this.fireDebug(" Reading Padding... (Offset: 0x{0})", (object) ticketFile.Position.ToString("x8").ToUpper()); signature = new byte[256];
ticketFile.Read(this.padding, 0, this.padding.Length); }
this.fireDebug(" Reading Issuer... (Offset: 0x{0})", (object) ticketFile.Position.ToString("x8").ToUpper()); MemoryStream memoryStream = new MemoryStream();
ticketFile.Read(this.issuer, 0, this.issuer.Length); memoryStream.Seek(0L, SeekOrigin.Begin);
this.fireDebug(" Reading Unknown... (Offset: 0x{0})", (object) ticketFile.Position.ToString("x8").ToUpper()); FireDebug(" Writing Signature Exponent... (Offset: 0x{0})", (object)memoryStream.Position.ToString("x8").ToUpper());
ticketFile.Read(this.unknown, 0, this.unknown.Length); memoryStream.Write(BitConverter.GetBytes(Shared.Swap(signatureExponent)), 0, 4);
this.fireDebug(" Reading Title Key... (Offset: 0x{0})", (object) ticketFile.Position.ToString("x8").ToUpper()); FireDebug(" Writing Signature... (Offset: 0x{0})", (object)memoryStream.Position.ToString("x8").ToUpper());
ticketFile.Read(this.encryptedTitleKey, 0, this.encryptedTitleKey.Length); memoryStream.Write(signature, 0, signature.Length);
this.fireDebug(" Reading Unknown2... (Offset: 0x{0})", (object) ticketFile.Position.ToString("x8").ToUpper()); FireDebug(" Writing Padding... (Offset: 0x{0})", (object)memoryStream.Position.ToString("x8").ToUpper());
this.unknown2 = (byte) ticketFile.ReadByte(); memoryStream.Write(padding, 0, padding.Length);
this.fireDebug(" Reading Ticket ID.. (Offset: 0x{0})", (object) ticketFile.Position.ToString("x8").ToUpper()); FireDebug(" Writing Issuer... (Offset: 0x{0})", (object)memoryStream.Position.ToString("x8").ToUpper());
ticketFile.Read(buffer, 0, 8); memoryStream.Write(issuer, 0, issuer.Length);
this.ticketId = Shared.Swap(BitConverter.ToUInt64(buffer, 0)); FireDebug(" Writing Unknown... (Offset: 0x{0})", (object)memoryStream.Position.ToString("x8").ToUpper());
this.fireDebug(" Reading Console ID... (Offset: 0x{0})", (object) ticketFile.Position.ToString("x8").ToUpper()); memoryStream.Write(unknown, 0, unknown.Length);
ticketFile.Read(buffer, 0, 4); FireDebug(" Writing Title Key... (Offset: 0x{0})", (object)memoryStream.Position.ToString("x8").ToUpper());
this.consoleId = Shared.Swap(BitConverter.ToUInt32(buffer, 0)); memoryStream.Write(encryptedTitleKey, 0, encryptedTitleKey.Length);
this.fireDebug(" Reading Title ID... (Offset: 0x{0})", (object) ticketFile.Position.ToString("x8").ToUpper()); FireDebug(" Writing Unknown2... (Offset: 0x{0})", (object)memoryStream.Position.ToString("x8").ToUpper());
ticketFile.Read(buffer, 0, 8); memoryStream.WriteByte(unknown2);
this.titleId = Shared.Swap(BitConverter.ToUInt64(buffer, 0)); FireDebug(" Writing Ticket ID... (Offset: 0x{0})", (object)memoryStream.Position.ToString("x8").ToUpper());
this.fireDebug(" Reading Unknown3... (Offset: 0x{0})", (object) ticketFile.Position.ToString("x8").ToUpper()); memoryStream.Write(BitConverter.GetBytes(Shared.Swap(ticketId)), 0, 8);
this.fireDebug(" Reading NumOfDLC... (Offset: 0x{0})", (object) ticketFile.Position.ToString("x8").ToUpper()); FireDebug(" Writing Console ID... (Offset: 0x{0})", (object)memoryStream.Position.ToString("x8").ToUpper());
ticketFile.Read(buffer, 0, 4); memoryStream.Write(BitConverter.GetBytes(Shared.Swap(consoleId)), 0, 4);
this.unknown3 = Shared.Swap(BitConverter.ToUInt16(buffer, 0)); FireDebug(" Writing Title ID... (Offset: 0x{0})", (object)memoryStream.Position.ToString("x8").ToUpper());
this.numOfDlc = Shared.Swap(BitConverter.ToUInt16(buffer, 2)); memoryStream.Write(BitConverter.GetBytes(Shared.Swap(titleId)), 0, 8);
this.fireDebug(" Reading Unknown4... (Offset: 0x{0})", (object) ticketFile.Position.ToString("x8").ToUpper()); FireDebug(" Writing Unknwon3... (Offset: 0x{0})", (object)memoryStream.Position.ToString("x8").ToUpper());
ticketFile.Read(buffer, 0, 8); memoryStream.Write(BitConverter.GetBytes(Shared.Swap(unknown3)), 0, 2);
this.unknown4 = Shared.Swap(BitConverter.ToUInt64(buffer, 0)); FireDebug(" Writing NumOfDLC... (Offset: 0x{0})", (object)memoryStream.Position.ToString("x8").ToUpper());
this.fireDebug(" Reading Padding2... (Offset: 0x{0})", (object) ticketFile.Position.ToString("x8").ToUpper()); memoryStream.Write(BitConverter.GetBytes(Shared.Swap(numOfDlc)), 0, 2);
this.padding2 = (byte) ticketFile.ReadByte(); FireDebug(" Writing Unknwon4... (Offset: 0x{0})", (object)memoryStream.Position.ToString("x8").ToUpper());
this.fireDebug(" Reading Common Key Index... (Offset: 0x{0})", (object) ticketFile.Position.ToString("x8").ToUpper()); memoryStream.Write(BitConverter.GetBytes(Shared.Swap(unknown4)), 0, 8);
this.commonKeyIndex = (byte) ticketFile.ReadByte(); FireDebug(" Writing Padding2... (Offset: 0x{0})", (object)memoryStream.Position.ToString("x8").ToUpper());
this.newKeyIndex = this.commonKeyIndex; memoryStream.WriteByte(padding2);
this.fireDebug(" Reading Unknown5... (Offset: 0x{0})", (object) ticketFile.Position.ToString("x8").ToUpper()); FireDebug(" Writing Common Key Index... (Offset: 0x{0})", (object)memoryStream.Position.ToString("x8").ToUpper());
ticketFile.Read(this.unknown5, 0, this.unknown5.Length); memoryStream.WriteByte(commonKeyIndex);
this.fireDebug(" Reading Unknown6... (Offset: 0x{0})", (object) ticketFile.Position.ToString("x8").ToUpper()); object[] objArray1 = new object[1];
ticketFile.Read(this.unknown6, 0, this.unknown6.Length); long position = memoryStream.Position;
this.fireDebug(" Reading Padding3... (Offset: 0x{0})", (object) ticketFile.Position.ToString("x8").ToUpper()); objArray1[0] = position.ToString("x8").ToUpper();
ticketFile.Read(buffer, 0, 2); FireDebug(" Writing Unknown5... (Offset: 0x{0})", objArray1);
this.padding3 = Shared.Swap(BitConverter.ToUInt16(buffer, 0)); memoryStream.Write(unknown5, 0, unknown5.Length);
this.fireDebug(" Reading Enable Time Limit... (Offset: 0x{0})", (object) ticketFile.Position.ToString("x8").ToUpper()); object[] objArray2 = new object[1];
this.fireDebug(" Reading Time Limit... (Offset: 0x{0})", (object) ticketFile.Position.ToString("x8").ToUpper()); position = memoryStream.Position;
ticketFile.Read(buffer, 0, 8); objArray2[0] = position.ToString("x8").ToUpper();
this.enableTimeLimit = Shared.Swap(BitConverter.ToUInt32(buffer, 0)); FireDebug(" Writing Unknown6... (Offset: 0x{0})", objArray2);
this.timeLimit = Shared.Swap(BitConverter.ToUInt32(buffer, 4)); memoryStream.Write(unknown6, 0, unknown6.Length);
this.fireDebug(" Reading Padding4... (Offset: 0x{0})", (object) ticketFile.Position.ToString("x8").ToUpper()); object[] objArray3 = new object[1];
ticketFile.Read(this.padding4, 0, this.padding4.Length); position = memoryStream.Position;
this.fireDebug(" Decrypting Title Key..."); objArray3[0] = position.ToString("x8").ToUpper();
this.decryptTitleKey(); FireDebug(" Writing Padding3... (Offset: 0x{0})", objArray3);
this.fireDebug(" -> Encrypted Title Key: {0}", (object) Shared.ByteArrayToString(this.encryptedTitleKey)); memoryStream.Write(BitConverter.GetBytes(Shared.Swap(padding3)), 0, 2);
this.fireDebug(" -> Decrypted Title Key: {0}", (object) Shared.ByteArrayToString(this.decryptedTitleKey)); object[] objArray4 = new object[1];
this.fireDebug("Parsing Ticket Finished..."); position = memoryStream.Position;
} objArray4[0] = position.ToString("x8").ToUpper();
FireDebug(" Writing Enable Time Limit... (Offset: 0x{0})", objArray4);
memoryStream.Write(BitConverter.GetBytes(Shared.Swap(enableTimeLimit)), 0, 4);
object[] objArray5 = new object[1];
position = memoryStream.Position;
objArray5[0] = position.ToString("x8").ToUpper();
FireDebug(" Writing Time Limit... (Offset: 0x{0})", objArray5);
memoryStream.Write(BitConverter.GetBytes(Shared.Swap(timeLimit)), 0, 4);
object[] objArray6 = new object[1];
position = memoryStream.Position;
objArray6[0] = position.ToString("x8").ToUpper();
FireDebug(" Writing Padding4... (Offset: 0x{0})", objArray6);
memoryStream.Write(padding4, 0, padding4.Length);
byte[] array = memoryStream.ToArray();
memoryStream.Dispose();
if (fakeSign)
{
FireDebug(" Fakesigning Ticket...");
//byte[] numArray = new byte[20];
SHA1 shA1 = SHA1.Create();
for (ushort index = 0; index < ushort.MaxValue; ++index)
{
byte[] bytes = BitConverter.GetBytes(index);
array[498] = bytes[1];
array[499] = bytes[0];
if (shA1.ComputeHash(array)[0] == 0)
{
FireDebug(" -> Signed ({0})", (object)index);
break;
}
if (index == 65534)
{
FireDebug(" -> Signing Failed...");
throw new Exception("Fakesigning failed...");
}
}
shA1.Clear();
}
writeStream.Seek(0L, SeekOrigin.Begin);
writeStream.Write(array, 0, array.Length);
FireDebug("Writing Ticket Finished...");
}
private void decryptTitleKey() private void ParseTicket(Stream ticketFile)
{ {
byte[] numArray = this.commonKeyIndex == (byte) 1 ? CommonKey.GetKoreanKey() : CommonKey.GetStandardKey(); FireDebug("Parsing Ticket...");
byte[] bytes = BitConverter.GetBytes(Shared.Swap(this.titleId)); ticketFile.Seek(0L, SeekOrigin.Begin);
Array.Resize<byte>(ref bytes, 16); byte[] buffer = new byte[8];
RijndaelManaged rijndaelManaged = new RijndaelManaged(); FireDebug(" Reading Signature Exponent... (Offset: 0x{0})", (object)ticketFile.Position.ToString("x8").ToUpper());
rijndaelManaged.Mode = CipherMode.CBC; ticketFile.Read(buffer, 0, 4);
rijndaelManaged.Padding = PaddingMode.None; signatureExponent = Shared.Swap(BitConverter.ToUInt32(buffer, 0));
rijndaelManaged.KeySize = 128; FireDebug(" Reading Signature... (Offset: 0x{0})", (object)ticketFile.Position.ToString("x8").ToUpper());
rijndaelManaged.BlockSize = 128; ticketFile.Read(signature, 0, signature.Length);
rijndaelManaged.Key = numArray; FireDebug(" Reading Padding... (Offset: 0x{0})", (object)ticketFile.Position.ToString("x8").ToUpper());
rijndaelManaged.IV = bytes; ticketFile.Read(padding, 0, padding.Length);
ICryptoTransform decryptor = rijndaelManaged.CreateDecryptor(); FireDebug(" Reading Issuer... (Offset: 0x{0})", (object)ticketFile.Position.ToString("x8").ToUpper());
MemoryStream memoryStream = new MemoryStream(this.encryptedTitleKey); ticketFile.Read(issuer, 0, issuer.Length);
CryptoStream cryptoStream = new CryptoStream((Stream) memoryStream, decryptor, CryptoStreamMode.Read); FireDebug(" Reading Unknown... (Offset: 0x{0})", (object)ticketFile.Position.ToString("x8").ToUpper());
cryptoStream.Read(this.decryptedTitleKey, 0, this.decryptedTitleKey.Length); ticketFile.Read(unknown, 0, unknown.Length);
cryptoStream.Dispose(); FireDebug(" Reading Title Key... (Offset: 0x{0})", (object)ticketFile.Position.ToString("x8").ToUpper());
memoryStream.Dispose(); ticketFile.Read(encryptedTitleKey, 0, encryptedTitleKey.Length);
decryptor.Dispose(); FireDebug(" Reading Unknown2... (Offset: 0x{0})", (object)ticketFile.Position.ToString("x8").ToUpper());
rijndaelManaged.Clear(); unknown2 = (byte)ticketFile.ReadByte();
} FireDebug(" Reading Ticket ID.. (Offset: 0x{0})", (object)ticketFile.Position.ToString("x8").ToUpper());
ticketFile.Read(buffer, 0, 8);
ticketId = Shared.Swap(BitConverter.ToUInt64(buffer, 0));
FireDebug(" Reading Console ID... (Offset: 0x{0})", (object)ticketFile.Position.ToString("x8").ToUpper());
ticketFile.Read(buffer, 0, 4);
consoleId = Shared.Swap(BitConverter.ToUInt32(buffer, 0));
FireDebug(" Reading Title ID... (Offset: 0x{0})", (object)ticketFile.Position.ToString("x8").ToUpper());
ticketFile.Read(buffer, 0, 8);
titleId = Shared.Swap(BitConverter.ToUInt64(buffer, 0));
FireDebug(" Reading Unknown3... (Offset: 0x{0})", (object)ticketFile.Position.ToString("x8").ToUpper());
FireDebug(" Reading NumOfDLC... (Offset: 0x{0})", (object)ticketFile.Position.ToString("x8").ToUpper());
ticketFile.Read(buffer, 0, 4);
unknown3 = Shared.Swap(BitConverter.ToUInt16(buffer, 0));
numOfDlc = Shared.Swap(BitConverter.ToUInt16(buffer, 2));
FireDebug(" Reading Unknown4... (Offset: 0x{0})", (object)ticketFile.Position.ToString("x8").ToUpper());
ticketFile.Read(buffer, 0, 8);
unknown4 = Shared.Swap(BitConverter.ToUInt64(buffer, 0));
FireDebug(" Reading Padding2... (Offset: 0x{0})", (object)ticketFile.Position.ToString("x8").ToUpper());
padding2 = (byte)ticketFile.ReadByte();
FireDebug(" Reading Common Key Index... (Offset: 0x{0})", (object)ticketFile.Position.ToString("x8").ToUpper());
commonKeyIndex = (byte)ticketFile.ReadByte();
newKeyIndex = commonKeyIndex;
FireDebug(" Reading Unknown5... (Offset: 0x{0})", (object)ticketFile.Position.ToString("x8").ToUpper());
ticketFile.Read(unknown5, 0, unknown5.Length);
FireDebug(" Reading Unknown6... (Offset: 0x{0})", (object)ticketFile.Position.ToString("x8").ToUpper());
ticketFile.Read(unknown6, 0, unknown6.Length);
FireDebug(" Reading Padding3... (Offset: 0x{0})", (object)ticketFile.Position.ToString("x8").ToUpper());
ticketFile.Read(buffer, 0, 2);
padding3 = Shared.Swap(BitConverter.ToUInt16(buffer, 0));
FireDebug(" Reading Enable Time Limit... (Offset: 0x{0})", (object)ticketFile.Position.ToString("x8").ToUpper());
FireDebug(" Reading Time Limit... (Offset: 0x{0})", (object)ticketFile.Position.ToString("x8").ToUpper());
ticketFile.Read(buffer, 0, 8);
enableTimeLimit = Shared.Swap(BitConverter.ToUInt32(buffer, 0));
timeLimit = Shared.Swap(BitConverter.ToUInt32(buffer, 4));
FireDebug(" Reading Padding4... (Offset: 0x{0})", (object)ticketFile.Position.ToString("x8").ToUpper());
ticketFile.Read(padding4, 0, padding4.Length);
FireDebug(" Decrypting Title Key...");
DecryptTitleKey();
FireDebug(" -> Encrypted Title Key: {0}", (object)Shared.ByteArrayToString(encryptedTitleKey));
FireDebug(" -> Decrypted Title Key: {0}", (object)Shared.ByteArrayToString(decryptedTitleKey));
FireDebug("Parsing Ticket Finished...");
}
private void encryptTitleKey() private void DecryptTitleKey()
{ {
this.commonKeyIndex = this.newKeyIndex; byte[] numArray = commonKeyIndex == 1 ? CommonKey.GetKoreanKey() : CommonKey.GetStandardKey();
byte[] numArray = this.commonKeyIndex == (byte) 1 ? CommonKey.GetKoreanKey() : CommonKey.GetStandardKey(); byte[] bytes = BitConverter.GetBytes(Shared.Swap(titleId));
byte[] bytes = BitConverter.GetBytes(Shared.Swap(this.titleId)); Array.Resize<byte>(ref bytes, 16);
Array.Resize<byte>(ref bytes, 16); RijndaelManaged rijndaelManaged = new RijndaelManaged
RijndaelManaged rijndaelManaged = new RijndaelManaged(); {
rijndaelManaged.Mode = CipherMode.CBC; Mode = CipherMode.CBC,
rijndaelManaged.Padding = PaddingMode.None; Padding = PaddingMode.None,
rijndaelManaged.KeySize = 128; KeySize = 128,
rijndaelManaged.BlockSize = 128; BlockSize = 128,
rijndaelManaged.Key = numArray; Key = numArray,
rijndaelManaged.IV = bytes; IV = bytes
ICryptoTransform encryptor = rijndaelManaged.CreateEncryptor(); };
MemoryStream memoryStream = new MemoryStream(this.decryptedTitleKey); ICryptoTransform decryptor = rijndaelManaged.CreateDecryptor();
CryptoStream cryptoStream = new CryptoStream((Stream) memoryStream, encryptor, CryptoStreamMode.Read); MemoryStream memoryStream = new MemoryStream(encryptedTitleKey);
cryptoStream.Read(this.encryptedTitleKey, 0, this.encryptedTitleKey.Length); CryptoStream cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read);
cryptoStream.Dispose(); cryptoStream.Read(decryptedTitleKey, 0, decryptedTitleKey.Length);
memoryStream.Dispose(); cryptoStream.Dispose();
encryptor.Dispose(); memoryStream.Dispose();
rijndaelManaged.Clear(); decryptor.Dispose();
} rijndaelManaged.Clear();
}
private void reDecryptTitleKey() private void EncryptTitleKey()
{ {
this.encryptedTitleKey = this.newEncryptedTitleKey; commonKeyIndex = newKeyIndex;
this.decryptTitleKey(); byte[] numArray = commonKeyIndex == 1 ? CommonKey.GetKoreanKey() : CommonKey.GetStandardKey();
} byte[] bytes = BitConverter.GetBytes(Shared.Swap(titleId));
Array.Resize<byte>(ref bytes, 16);
RijndaelManaged rijndaelManaged = new RijndaelManaged
{
Mode = CipherMode.CBC,
Padding = PaddingMode.None,
KeySize = 128,
BlockSize = 128,
Key = numArray,
IV = bytes
};
ICryptoTransform encryptor = rijndaelManaged.CreateEncryptor();
MemoryStream memoryStream = new MemoryStream(decryptedTitleKey);
CryptoStream cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Read);
cryptoStream.Read(encryptedTitleKey, 0, encryptedTitleKey.Length);
cryptoStream.Dispose();
memoryStream.Dispose();
encryptor.Dispose();
rijndaelManaged.Clear();
}
private void fireDebug(string debugMessage, params object[] args) private void ReDecryptTitleKey()
{ {
EventHandler<MessageEventArgs> debug = this.Debug; encryptedTitleKey = newEncryptedTitleKey;
if (debug == null) DecryptTitleKey();
return; }
debug(new object(), new MessageEventArgs(string.Format(debugMessage, args)));
private void FireDebug(string debugMessage, params object[] args)
{
EventHandler<MessageEventArgs> debug = Debug;
if (debug == null)
{
return;
}
debug(new object(), new MessageEventArgs(string.Format(debugMessage, args)));
}
} }
}
} }

1638
U8.cs

File diff suppressed because it is too large Load diff

View file

@ -9,39 +9,39 @@ using System.IO;
namespace libWiiSharp namespace libWiiSharp
{ {
public class U8_Header public class U8_Header
{
private uint u8Magic = 1437218861;
private uint offsetToRootNode = 32;
private uint headerSize;
private uint offsetToData;
private byte[] padding = new byte[16];
public uint U8Magic => this.u8Magic;
public uint OffsetToRootNode => this.offsetToRootNode;
public uint HeaderSize
{ {
get => this.headerSize; private readonly uint u8Magic = 1437218861;
set => this.headerSize = value; private readonly uint offsetToRootNode = 32;
} private uint headerSize;
private uint offsetToData;
private readonly byte[] padding = new byte[16];
public uint OffsetToData public uint U8Magic => u8Magic;
{
get => this.offsetToData;
set => this.offsetToData = value;
}
public byte[] Padding => this.padding; public uint OffsetToRootNode => offsetToRootNode;
public void Write(Stream writeStream) public uint HeaderSize
{ {
writeStream.Write(BitConverter.GetBytes(Shared.Swap(this.u8Magic)), 0, 4); get => headerSize;
writeStream.Write(BitConverter.GetBytes(Shared.Swap(this.offsetToRootNode)), 0, 4); set => headerSize = value;
writeStream.Write(BitConverter.GetBytes(Shared.Swap(this.headerSize)), 0, 4); }
writeStream.Write(BitConverter.GetBytes(Shared.Swap(this.offsetToData)), 0, 4);
writeStream.Write(this.padding, 0, 16); public uint OffsetToData
{
get => offsetToData;
set => offsetToData = value;
}
public byte[] Padding => padding;
public void Write(Stream writeStream)
{
writeStream.Write(BitConverter.GetBytes(Shared.Swap(u8Magic)), 0, 4);
writeStream.Write(BitConverter.GetBytes(Shared.Swap(offsetToRootNode)), 0, 4);
writeStream.Write(BitConverter.GetBytes(Shared.Swap(headerSize)), 0, 4);
writeStream.Write(BitConverter.GetBytes(Shared.Swap(offsetToData)), 0, 4);
writeStream.Write(padding, 0, 16);
}
} }
}
} }

View file

@ -9,43 +9,43 @@ using System.IO;
namespace libWiiSharp namespace libWiiSharp
{ {
public class U8_Node public class U8_Node
{
private ushort type;
private ushort offsetToName;
private uint offsetToData;
private uint sizeOfData;
public U8_NodeType Type
{ {
get => (U8_NodeType) this.type; private ushort type;
set => this.type = (ushort) value; private ushort offsetToName;
} private uint offsetToData;
private uint sizeOfData;
public ushort OffsetToName public U8_NodeType Type
{ {
get => this.offsetToName; get => (U8_NodeType)type;
set => this.offsetToName = value; set => type = (ushort)value;
} }
public uint OffsetToData public ushort OffsetToName
{ {
get => this.offsetToData; get => offsetToName;
set => this.offsetToData = value; set => offsetToName = value;
} }
public uint SizeOfData public uint OffsetToData
{ {
get => this.sizeOfData; get => offsetToData;
set => this.sizeOfData = value; set => offsetToData = value;
} }
public void Write(Stream writeStream) public uint SizeOfData
{ {
writeStream.Write(BitConverter.GetBytes(Shared.Swap(this.type)), 0, 2); get => sizeOfData;
writeStream.Write(BitConverter.GetBytes(Shared.Swap(this.offsetToName)), 0, 2); set => sizeOfData = value;
writeStream.Write(BitConverter.GetBytes(Shared.Swap(this.offsetToData)), 0, 4); }
writeStream.Write(BitConverter.GetBytes(Shared.Swap(this.sizeOfData)), 0, 4);
public void Write(Stream writeStream)
{
writeStream.Write(BitConverter.GetBytes(Shared.Swap(type)), 0, 2);
writeStream.Write(BitConverter.GetBytes(Shared.Swap(offsetToName)), 0, 2);
writeStream.Write(BitConverter.GetBytes(Shared.Swap(offsetToData)), 0, 4);
writeStream.Write(BitConverter.GetBytes(Shared.Swap(sizeOfData)), 0, 4);
}
} }
}
} }

View file

@ -6,9 +6,9 @@
namespace libWiiSharp namespace libWiiSharp
{ {
public enum U8_NodeType : ushort public enum U8_NodeType : ushort
{ {
File = 0, File = 0,
Directory = 256, // 0x0100 Directory = 256, // 0x0100
} }
} }

2004
WAD.cs

File diff suppressed because it is too large Load diff

377
Wave.cs
View file

@ -9,200 +9,213 @@ using System.IO;
namespace libWiiSharp namespace libWiiSharp
{ {
public class Wave : IDisposable public class Wave : IDisposable
{
private WaveHeader header = new WaveHeader();
private WaveFmtChunk fmt = new WaveFmtChunk();
private WaveDataChunk data = new WaveDataChunk();
private WaveSmplChunk smpl = new WaveSmplChunk();
private bool hasSmpl;
private bool isDisposed;
public int SampleRate => (int) this.fmt.SampleRate;
public int BitDepth => (int) this.fmt.BitsPerSample;
public int NumChannels => (int) this.fmt.NumChannels;
public int NumLoops => !this.hasSmpl ? 0 : (int) this.smpl.NumLoops;
public int LoopStart => this.NumLoops == 0 ? 0 : (int) this.smpl.Loops[0].LoopStart;
public int NumSamples => (int) ((long) this.data.DataSize / (long) ((int) this.fmt.BitsPerSample / 8) / (long) this.fmt.NumChannels);
public int DataFormat => (int) this.fmt.AudioFormat;
public byte[] SampleData => this.data.Data;
public int PlayLength => (int) ((long) (this.data.DataSize / (uint) this.fmt.NumChannels) / (long) ((int) this.fmt.BitsPerSample / 8) / (long) this.fmt.SampleRate);
public Wave(string pathToFile)
{ {
using (FileStream fileStream = new FileStream(pathToFile, FileMode.Open)) private WaveHeader header = new WaveHeader();
{ private WaveFmtChunk fmt = new WaveFmtChunk();
using (BinaryReader reader = new BinaryReader((Stream) fileStream)) private WaveDataChunk data = new WaveDataChunk();
this.parseWave(reader); private WaveSmplChunk smpl = new WaveSmplChunk();
} private bool hasSmpl;
} private bool isDisposed;
public Wave(Stream wave) => this.parseWave(new BinaryReader(wave)); public int SampleRate => (int)fmt.SampleRate;
public Wave(byte[] waveFile) public int BitDepth => fmt.BitsPerSample;
{
using (MemoryStream memoryStream = new MemoryStream(waveFile))
{
using (BinaryReader reader = new BinaryReader((Stream) memoryStream))
this.parseWave(reader);
}
}
public Wave(int numChannels, int bitsPerSample, int sampleRate, byte[] samples) public int NumChannels => fmt.NumChannels;
{
this.fmt.SampleRate = (uint) sampleRate;
this.fmt.NumChannels = (ushort) numChannels;
this.fmt.BitsPerSample = (ushort) bitsPerSample;
this.data.Data = samples;
}
~Wave() => this.Dispose(false); public int NumLoops => !hasSmpl ? 0 : (int)smpl.NumLoops;
public void Dispose() public int LoopStart => NumLoops == 0 ? 0 : (int)smpl.Loops[0].LoopStart;
{
this.Dispose(true);
GC.SuppressFinalize((object) this);
}
protected virtual void Dispose(bool disposing) public int NumSamples => (int)(data.DataSize / (fmt.BitsPerSample / 8) / fmt.NumChannels);
{
if (disposing && !this.isDisposed)
{
this.header = (WaveHeader) null;
this.fmt = (WaveFmtChunk) null;
this.data = (WaveDataChunk) null;
this.smpl = (WaveSmplChunk) null;
}
this.isDisposed = true;
}
public void Write(Stream writeStream) => this.writeToStream(new BinaryWriter(writeStream)); public int DataFormat => (int)fmt.AudioFormat;
public MemoryStream ToMemoryStream() public byte[] SampleData => data.Data;
{
MemoryStream memoryStream = new MemoryStream();
this.writeToStream(new BinaryWriter((Stream) memoryStream));
return memoryStream;
}
public byte[] ToByteArray() => this.ToMemoryStream().ToArray(); public int PlayLength => (int)(data.DataSize / fmt.NumChannels / (fmt.BitsPerSample / 8) / fmt.SampleRate);
public void Save(string savePath) public Wave(string pathToFile)
{
using (FileStream fileStream = new FileStream(savePath, FileMode.Create))
{
using (BinaryWriter writer = new BinaryWriter((Stream) fileStream))
this.writeToStream(writer);
}
}
public void AddLoop(int loopStartSample)
{
this.smpl.AddLoop(loopStartSample, this.NumSamples);
this.hasSmpl = true;
}
public void RemoveLoop() => this.hasSmpl = false;
public void TrimStart(int newStartSample)
{
int offset = (int) this.fmt.NumChannels * ((int) this.fmt.BitsPerSample / 8) * newStartSample;
MemoryStream memoryStream = new MemoryStream();
memoryStream.Write(this.data.Data, offset, this.data.Data.Length - offset);
this.data.Data = memoryStream.ToArray();
memoryStream.Dispose();
}
private void writeToStream(BinaryWriter writer)
{
this.header.FileSize = (uint) (4 + (int) this.fmt.FmtSize + 8 + (int) this.data.DataSize + 8 + (this.hasSmpl ? (int) this.smpl.SmplSize + 8 : 0));
this.header.Write(writer);
this.fmt.Write(writer);
this.data.Write(writer);
if (!this.hasSmpl)
return;
this.smpl.Write(writer);
}
private void parseWave(BinaryReader reader)
{
bool[] flagArray = new bool[3];
while (reader.BaseStream.Position < reader.BaseStream.Length - 4L)
{
uint num1 = Shared.Swap(reader.ReadUInt32());
uint num2 = reader.ReadUInt32();
long offset = reader.BaseStream.Position + (long) num2;
switch (num1)
{ {
case 1380533830: using FileStream fileStream = new FileStream(pathToFile, FileMode.Open);
try using BinaryReader reader = new BinaryReader(fileStream);
{ ParseWave(reader);
reader.BaseStream.Seek(-8L, SeekOrigin.Current); }
this.header.Read(reader);
flagArray[0] = true; public Wave(Stream wave)
break; {
} ParseWave(new BinaryReader(wave));
catch }
{
reader.BaseStream.Seek(offset, SeekOrigin.Begin); public Wave(byte[] waveFile)
break; {
} using MemoryStream memoryStream = new MemoryStream(waveFile);
case 1684108385: using BinaryReader reader = new BinaryReader(memoryStream);
try ParseWave(reader);
{ }
reader.BaseStream.Seek(-8L, SeekOrigin.Current);
this.data.Read(reader); public Wave(int numChannels, int bitsPerSample, int sampleRate, byte[] samples)
flagArray[2] = true; {
break; fmt.SampleRate = (uint)sampleRate;
} fmt.NumChannels = (ushort)numChannels;
catch fmt.BitsPerSample = (ushort)bitsPerSample;
{ data.Data = samples;
reader.BaseStream.Seek(offset, SeekOrigin.Begin); }
break;
} ~Wave() => Dispose(false);
case 1718449184:
try public void Dispose()
{ {
reader.BaseStream.Seek(-8L, SeekOrigin.Current); Dispose(true);
this.fmt.Read(reader); GC.SuppressFinalize(this);
flagArray[1] = true; }
break;
} protected virtual void Dispose(bool disposing)
catch {
{ if (disposing && !isDisposed)
reader.BaseStream.Seek(offset, SeekOrigin.Begin); {
break; header = null;
} fmt = null;
case 1936552044: data = null;
try smpl = null;
{ }
reader.BaseStream.Seek(-8L, SeekOrigin.Current); isDisposed = true;
this.smpl.Read(reader); }
this.hasSmpl = true;
break; public void Write(Stream writeStream)
} {
catch WriteToStream(new BinaryWriter(writeStream));
{ }
reader.BaseStream.Seek(offset, SeekOrigin.Begin);
break; public MemoryStream ToMemoryStream()
} {
default: MemoryStream memoryStream = new MemoryStream();
reader.BaseStream.Seek((long) num2, SeekOrigin.Current); WriteToStream(new BinaryWriter(memoryStream));
break; return memoryStream;
}
public byte[] ToByteArray()
{
return ToMemoryStream().ToArray();
}
public void Save(string savePath)
{
using FileStream fileStream = new FileStream(savePath, FileMode.Create);
using BinaryWriter writer = new BinaryWriter(fileStream);
WriteToStream(writer);
}
public void AddLoop(int loopStartSample)
{
smpl.AddLoop(loopStartSample, NumSamples);
hasSmpl = true;
}
public void RemoveLoop()
{
hasSmpl = false;
}
public void TrimStart(int newStartSample)
{
int offset = fmt.NumChannels * (fmt.BitsPerSample / 8) * newStartSample;
MemoryStream memoryStream = new MemoryStream();
memoryStream.Write(data.Data, offset, data.Data.Length - offset);
data.Data = memoryStream.ToArray();
memoryStream.Dispose();
}
private void WriteToStream(BinaryWriter writer)
{
header.FileSize = (uint)(4 + (int)fmt.FmtSize + 8 + (int)data.DataSize + 8 + (hasSmpl ? (int)smpl.SmplSize + 8 : 0));
header.Write(writer);
fmt.Write(writer);
data.Write(writer);
if (!hasSmpl)
{
return;
}
smpl.Write(writer);
}
private void ParseWave(BinaryReader reader)
{
bool[] flagArray = new bool[3];
while (reader.BaseStream.Position < reader.BaseStream.Length - 4L)
{
uint num1 = Shared.Swap(reader.ReadUInt32());
uint num2 = reader.ReadUInt32();
long offset = reader.BaseStream.Position + num2;
switch (num1)
{
case 1380533830:
try
{
reader.BaseStream.Seek(-8L, SeekOrigin.Current);
header.Read(reader);
flagArray[0] = true;
break;
}
catch
{
reader.BaseStream.Seek(offset, SeekOrigin.Begin);
break;
}
case 1684108385:
try
{
reader.BaseStream.Seek(-8L, SeekOrigin.Current);
data.Read(reader);
flagArray[2] = true;
break;
}
catch
{
reader.BaseStream.Seek(offset, SeekOrigin.Begin);
break;
}
case 1718449184:
try
{
reader.BaseStream.Seek(-8L, SeekOrigin.Current);
fmt.Read(reader);
flagArray[1] = true;
break;
}
catch
{
reader.BaseStream.Seek(offset, SeekOrigin.Begin);
break;
}
case 1936552044:
try
{
reader.BaseStream.Seek(-8L, SeekOrigin.Current);
smpl.Read(reader);
hasSmpl = true;
break;
}
catch
{
reader.BaseStream.Seek(offset, SeekOrigin.Begin);
break;
}
default:
reader.BaseStream.Seek(num2, SeekOrigin.Current);
break;
}
if (flagArray[0] && flagArray[1] && (flagArray[2] && hasSmpl))
{
break;
}
}
if (!flagArray[0] || !flagArray[1] || !flagArray[2])
{
throw new Exception("Couldn't parse Wave file...");
}
} }
if (flagArray[0] && flagArray[1] && (flagArray[2] && this.hasSmpl))
break;
}
if (!flagArray[0] || !flagArray[1] || !flagArray[2])
throw new Exception("Couldn't parse Wave file...");
} }
}
} }

View file

@ -9,35 +9,35 @@ using System.IO;
namespace libWiiSharp namespace libWiiSharp
{ {
internal class WaveDataChunk internal class WaveDataChunk
{
private uint dataId = 1684108385;
private uint dataSize = 8;
private byte[] data;
public uint DataSize => this.dataSize;
public byte[] Data
{ {
get => this.data; private readonly uint dataId = 1684108385;
set private uint dataSize = 8;
{ private byte[] data;
this.data = value;
this.dataSize = (uint) this.data.Length;
}
}
public void Write(BinaryWriter writer) public uint DataSize => dataSize;
{
writer.Write(Shared.Swap(this.dataId));
writer.Write(this.dataSize);
writer.Write(this.data, 0, this.data.Length);
}
public void Read(BinaryReader reader) public byte[] Data
{ {
this.dataSize = (int) Shared.Swap(reader.ReadUInt32()) == (int) this.dataId ? reader.ReadUInt32() : throw new Exception("Wrong chunk ID!"); get => data;
this.data = reader.ReadBytes((int) this.dataSize); set
{
data = value;
dataSize = (uint)data.Length;
}
}
public void Write(BinaryWriter writer)
{
writer.Write(Shared.Swap(dataId));
writer.Write(dataSize);
writer.Write(data, 0, data.Length);
}
public void Read(BinaryReader reader)
{
dataSize = (int)Shared.Swap(reader.ReadUInt32()) == (int)dataId ? reader.ReadUInt32() : throw new Exception("Wrong chunk ID!");
data = reader.ReadBytes((int)dataSize);
}
} }
}
} }

View file

@ -9,62 +9,62 @@ using System.IO;
namespace libWiiSharp namespace libWiiSharp
{ {
internal class WaveFmtChunk internal class WaveFmtChunk
{
private uint fmtId = 1718449184;
private uint fmtSize = 16;
private ushort audioFormat = 1;
private ushort numChannels = 2;
private uint sampleRate = 44100;
private uint byteRate;
private ushort blockAlign;
private ushort bitsPerSample = 16;
public uint FmtSize => this.fmtSize;
public ushort NumChannels
{ {
get => this.numChannels; private readonly uint fmtId = 1718449184;
set => this.numChannels = value; private uint fmtSize = 16;
} private ushort audioFormat = 1;
private ushort numChannels = 2;
private uint sampleRate = 44100;
private uint byteRate;
private ushort blockAlign;
private ushort bitsPerSample = 16;
public uint SampleRate public uint FmtSize => fmtSize;
{
get => this.sampleRate;
set => this.sampleRate = value;
}
public ushort BitsPerSample public ushort NumChannels
{ {
get => this.bitsPerSample; get => numChannels;
set => this.bitsPerSample = value; set => numChannels = value;
} }
public uint AudioFormat => (uint) this.audioFormat; public uint SampleRate
{
get => sampleRate;
set => sampleRate = value;
}
public void Write(BinaryWriter writer) public ushort BitsPerSample
{ {
this.byteRate = this.sampleRate * (uint) this.numChannels * (uint) this.bitsPerSample / 8U; get => bitsPerSample;
this.blockAlign = (ushort) ((int) this.numChannels * (int) this.bitsPerSample / 8); set => bitsPerSample = value;
writer.Write(Shared.Swap(this.fmtId)); }
writer.Write(this.fmtSize);
writer.Write(this.audioFormat);
writer.Write(this.numChannels);
writer.Write(this.sampleRate);
writer.Write(this.byteRate);
writer.Write(this.blockAlign);
writer.Write(this.bitsPerSample);
}
public void Read(BinaryReader reader) public uint AudioFormat => audioFormat;
{
this.fmtSize = (int) Shared.Swap(reader.ReadUInt32()) == (int) this.fmtId ? reader.ReadUInt32() : throw new Exception("Wrong chunk ID!"); public void Write(BinaryWriter writer)
this.audioFormat = reader.ReadUInt16(); {
this.numChannels = reader.ReadUInt16(); byteRate = sampleRate * numChannels * bitsPerSample / 8U;
this.sampleRate = reader.ReadUInt32(); blockAlign = (ushort)(numChannels * bitsPerSample / 8);
this.byteRate = reader.ReadUInt32(); writer.Write(Shared.Swap(fmtId));
this.blockAlign = reader.ReadUInt16(); writer.Write(fmtSize);
this.bitsPerSample = reader.ReadUInt16(); writer.Write(audioFormat);
writer.Write(numChannels);
writer.Write(sampleRate);
writer.Write(byteRate);
writer.Write(blockAlign);
writer.Write(bitsPerSample);
}
public void Read(BinaryReader reader)
{
fmtSize = (int)Shared.Swap(reader.ReadUInt32()) == (int)fmtId ? reader.ReadUInt32() : throw new Exception("Wrong chunk ID!");
audioFormat = reader.ReadUInt16();
numChannels = reader.ReadUInt16();
sampleRate = reader.ReadUInt32();
byteRate = reader.ReadUInt32();
blockAlign = reader.ReadUInt16();
bitsPerSample = reader.ReadUInt16();
}
} }
}
} }

View file

@ -9,30 +9,32 @@ using System.IO;
namespace libWiiSharp namespace libWiiSharp
{ {
internal class WaveHeader internal class WaveHeader
{
private uint headerId = 1380533830;
private uint fileSize = 12;
private uint format = 1463899717;
public uint FileSize
{ {
get => this.fileSize; private readonly uint headerId = 1380533830;
set => this.fileSize = value; private uint fileSize = 12;
} private readonly uint format = 1463899717;
public void Write(BinaryWriter writer) public uint FileSize
{ {
writer.Write(Shared.Swap(this.headerId)); get => fileSize;
writer.Write(this.fileSize); set => fileSize = value;
writer.Write(Shared.Swap(this.format)); }
}
public void Read(BinaryReader reader) public void Write(BinaryWriter writer)
{ {
this.fileSize = (int) Shared.Swap(reader.ReadUInt32()) == (int) this.headerId ? reader.ReadUInt32() : throw new Exception("Not a valid RIFF Wave file!"); writer.Write(Shared.Swap(headerId));
if ((int) Shared.Swap(reader.ReadUInt32()) != (int) this.format) writer.Write(fileSize);
throw new Exception("Not a valid RIFF Wave file!"); writer.Write(Shared.Swap(format));
}
public void Read(BinaryReader reader)
{
fileSize = (int)Shared.Swap(reader.ReadUInt32()) == (int)headerId ? reader.ReadUInt32() : throw new Exception("Not a valid RIFF Wave file!");
if ((int)Shared.Swap(reader.ReadUInt32()) != (int)format)
{
throw new Exception("Not a valid RIFF Wave file!");
}
}
} }
}
} }

View file

@ -10,79 +10,81 @@ using System.IO;
namespace libWiiSharp namespace libWiiSharp
{ {
internal class WaveSmplChunk internal class WaveSmplChunk
{
private uint smplId = 1936552044;
private uint smplSize = 36;
private uint manufacturer;
private uint product;
private uint samplePeriod;
private uint unityNote = 60;
private uint pitchFraction;
private uint smpteFormat;
private uint smpteOffset;
private uint numLoops;
private uint samplerData;
private List<WaveSmplLoop> smplLoops = new List<WaveSmplLoop>();
public uint SmplSize => this.smplSize;
public uint NumLoops => this.numLoops;
public WaveSmplLoop[] Loops => this.smplLoops.ToArray();
public void AddLoop(int loopStartSample, int loopEndSample)
{ {
this.RemoveAllLoops(); private readonly uint smplId = 1936552044;
++this.numLoops; private uint smplSize = 36;
this.smplLoops.Add(new WaveSmplLoop() private uint manufacturer;
{ private uint product;
LoopStart = (uint) loopStartSample, private uint samplePeriod;
LoopEnd = (uint) loopEndSample private uint unityNote = 60;
}); private uint pitchFraction;
} private uint smpteFormat;
private uint smpteOffset;
private uint numLoops;
private uint samplerData;
private readonly List<WaveSmplLoop> smplLoops = new List<WaveSmplLoop>();
public void RemoveAllLoops() public uint SmplSize => smplSize;
{
this.smplLoops.Clear();
this.numLoops = 0U;
}
public void Write(BinaryWriter writer) public uint NumLoops => numLoops;
{
writer.Write(Shared.Swap(this.smplId));
writer.Write(this.smplSize);
writer.Write(this.manufacturer);
writer.Write(this.product);
writer.Write(this.samplePeriod);
writer.Write(this.unityNote);
writer.Write(this.pitchFraction);
writer.Write(this.smpteFormat);
writer.Write(this.smpteOffset);
writer.Write(this.numLoops);
writer.Write(this.samplerData);
for (int index = 0; (long) index < (long) this.numLoops; ++index)
this.smplLoops[index].Write(writer);
}
public void Read(BinaryReader reader) public WaveSmplLoop[] Loops => smplLoops.ToArray();
{
this.smplSize = (int) Shared.Swap(reader.ReadUInt32()) == (int) this.smplId ? reader.ReadUInt32() : throw new Exception("Wrong chunk ID!"); public void AddLoop(int loopStartSample, int loopEndSample)
this.manufacturer = reader.ReadUInt32(); {
this.product = reader.ReadUInt32(); RemoveAllLoops();
this.samplePeriod = reader.ReadUInt32(); ++numLoops;
this.unityNote = reader.ReadUInt32(); smplLoops.Add(new WaveSmplLoop()
this.pitchFraction = reader.ReadUInt32(); {
this.smpteFormat = reader.ReadUInt32(); LoopStart = (uint)loopStartSample,
this.smpteOffset = reader.ReadUInt32(); LoopEnd = (uint)loopEndSample
this.numLoops = reader.ReadUInt32(); });
this.samplerData = reader.ReadUInt32(); }
for (int index = 0; (long) index < (long) this.numLoops; ++index)
{ public void RemoveAllLoops()
WaveSmplLoop waveSmplLoop = new WaveSmplLoop(); {
waveSmplLoop.Read(reader); smplLoops.Clear();
this.smplLoops.Add(waveSmplLoop); numLoops = 0U;
} }
public void Write(BinaryWriter writer)
{
writer.Write(Shared.Swap(smplId));
writer.Write(smplSize);
writer.Write(manufacturer);
writer.Write(product);
writer.Write(samplePeriod);
writer.Write(unityNote);
writer.Write(pitchFraction);
writer.Write(smpteFormat);
writer.Write(smpteOffset);
writer.Write(numLoops);
writer.Write(samplerData);
for (int index = 0; index < numLoops; ++index)
{
smplLoops[index].Write(writer);
}
}
public void Read(BinaryReader reader)
{
smplSize = (int)Shared.Swap(reader.ReadUInt32()) == (int)smplId ? reader.ReadUInt32() : throw new Exception("Wrong chunk ID!");
manufacturer = reader.ReadUInt32();
product = reader.ReadUInt32();
samplePeriod = reader.ReadUInt32();
unityNote = reader.ReadUInt32();
pitchFraction = reader.ReadUInt32();
smpteFormat = reader.ReadUInt32();
smpteOffset = reader.ReadUInt32();
numLoops = reader.ReadUInt32();
samplerData = reader.ReadUInt32();
for (int index = 0; index < numLoops; ++index)
{
WaveSmplLoop waveSmplLoop = new WaveSmplLoop();
waveSmplLoop.Read(reader);
smplLoops.Add(waveSmplLoop);
}
}
} }
}
} }

View file

@ -8,45 +8,45 @@ using System.IO;
namespace libWiiSharp namespace libWiiSharp
{ {
internal class WaveSmplLoop internal class WaveSmplLoop
{
private uint cuePointId;
private uint type;
private uint start;
private uint end;
private uint fraction;
private uint playCount;
public uint LoopStart
{ {
get => this.start; private uint cuePointId;
set => this.start = value; private uint type;
} private uint start;
private uint end;
private uint fraction;
private uint playCount;
public uint LoopEnd public uint LoopStart
{ {
get => this.end; get => start;
set => this.end = value; set => start = value;
} }
public void Write(BinaryWriter writer) public uint LoopEnd
{ {
writer.Write(this.cuePointId); get => end;
writer.Write(this.type); set => end = value;
writer.Write(this.start); }
writer.Write(this.end);
writer.Write(this.fraction);
writer.Write(this.playCount);
}
public void Read(BinaryReader reader) public void Write(BinaryWriter writer)
{ {
this.cuePointId = reader.ReadUInt32(); writer.Write(cuePointId);
this.type = reader.ReadUInt32(); writer.Write(type);
this.start = reader.ReadUInt32(); writer.Write(start);
this.end = reader.ReadUInt32(); writer.Write(end);
this.fraction = reader.ReadUInt32(); writer.Write(fraction);
this.playCount = reader.ReadUInt32(); writer.Write(playCount);
}
public void Read(BinaryReader reader)
{
cuePointId = reader.ReadUInt32();
type = reader.ReadUInt32();
start = reader.ReadUInt32();
end = reader.ReadUInt32();
fraction = reader.ReadUInt32();
playCount = reader.ReadUInt32();
}
} }
}
} }