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)]

365
BNS.cs
View file

@ -29,9 +29,12 @@ 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,
@ -51,7 +54,8 @@ namespace libWiiSharp
3795, 3795,
-1759 -1759
}; };
private int[] defTbl = new int[16] */
private readonly int[] defTbl = new int[16]
{ {
1820, 1820,
-856, -856,
@ -74,7 +78,7 @@ namespace libWiiSharp
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 wave = new Wave(bns.bnsInfo.ChannelCount, 16, bns.bnsInfo.SampleRate, samples);
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(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 wave = new Wave(bns.bnsInfo.ChannelCount, 16, bns.bnsInfo.SampleRate, samples);
if (bns.bnsInfo.HasLoop == 1)
{
wave.AddLoop((int)bns.bnsInfo.LoopStart); wave.AddLoop((int)bns.bnsInfo.LoopStart);
}
return wave; return wave;
} }
@ -529,65 +618,73 @@ 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();
} }
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);
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); 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()); }
this.fileSize = Shared.Swap(binaryReader.ReadUInt32()); flags = Shared.Swap(binaryReader.ReadUInt32());
this.size = Shared.Swap(binaryReader.ReadUInt16()); fileSize = Shared.Swap(binaryReader.ReadUInt32());
this.chunkCount = Shared.Swap(binaryReader.ReadUInt16()); size = Shared.Swap(binaryReader.ReadUInt16());
this.infoOffset = Shared.Swap(binaryReader.ReadUInt32()); chunkCount = Shared.Swap(binaryReader.ReadUInt16());
this.infoLength = Shared.Swap(binaryReader.ReadUInt32()); infoOffset = Shared.Swap(binaryReader.ReadUInt32());
this.dataOffset = Shared.Swap(binaryReader.ReadUInt32()); infoLength = Shared.Swap(binaryReader.ReadUInt32());
this.dataLength = Shared.Swap(binaryReader.ReadUInt32()); dataOffset = 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,17 +24,29 @@ 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")
@ -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 + "_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;
} }
@ -52,27 +66,35 @@ namespace libWiiSharp
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)
Array.Resize<byte>(ref part, 768);
return part[388] == (byte) 88 && part[389] == (byte) 83 && Shared.CompareByteArrays(this.sha.ComputeHash(part), Shared.HexStringToByteArray("09787045037121477824BC6A3E5E076156573F8A"));
} }
private bool isCertCa(byte[] part) if (part.Length > 768)
{
Array.Resize<byte>(ref part, 768);
}
return part[388] == 88 && part[389] == 83 && Shared.CompareByteArrays(sha.ComputeHash(part), Shared.HexStringToByteArray("09787045037121477824BC6A3E5E076156573F8A"));
}
private bool IsCertCa(byte[] part)
{ {
if (part.Length < 1024) if (part.Length < 1024)
{
return false; return false;
if (part.Length > 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"));
} }
private bool isCertCp(byte[] part) if (part.Length > 1024)
{
Array.Resize<byte>(ref part, 1024);
}
return part[644] == 67 && part[645] == 65 && Shared.CompareByteArrays(sha.ComputeHash(part), Shared.HexStringToByteArray("5B7D3EE28706AD8DA2CBD5A6B75C15D0F9B6F318"));
}
private bool IsCertCp(byte[] part)
{ {
if (part.Length < 768) if (part.Length < 768)
{
return false; return false;
if (part.Length > 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"));
} }
private void fireDebug(string debugMessage, params object[] args) if (part.Length > 768)
{ {
EventHandler<MessageEventArgs> debug = this.Debug; Array.Resize<byte>(ref part, 768);
}
return part[388] == 67 && part[389] == 80 && Shared.CompareByteArrays(sha.ComputeHash(part), Shared.HexStringToByteArray("6824D6DA4C25184F0D6DAF6EDB9C0FC57522A41C"));
}
private void FireDebug(string debugMessage, params object[] args)
{
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(); {
else ToCI8();
this.toCI14X2();
} }
else else
this.toCI4(); {
ToCI14X2();
}
}
else
{
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,63 +182,69 @@ 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); return 0;
for (int index = 0; index < this.rgbaPalette.Length; ++index) }
ushort paletteValue1 = ConvertToPaletteValue((int)value);
for (int index = 0; index < rgbaPalette.Length; ++index)
{
ushort paletteValue2 = ConvertToPaletteValue((int)rgbaPalette[index]);
if (paletteValue1 == paletteValue2)
{ {
ushort paletteValue2 = this.convertToPaletteValue((int) this.rgbaPalette[index]);
if ((int) paletteValue1 == (int) paletteValue2)
return (uint)index; return (uint)index;
uint distance = this.getDistance(paletteValue1, paletteValue2); }
uint distance = GetDistance(paletteValue1, paletteValue2);
if (distance < num1) if (distance < num1)
{ {
num1 = distance; num1 = distance;
@ -231,18 +254,18 @@ namespace libWiiSharp
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);
@ -251,39 +274,39 @@ namespace libWiiSharp
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

@ -22,12 +22,12 @@ namespace libWiiSharp
{ {
public struct ContentIndices : IComparable public struct ContentIndices : IComparable
{ {
private int index; private readonly int index;
private int contentIndex; private readonly int contentIndex;
public int Index => this.index; public int Index => index;
public int ContentIndex => this.contentIndex; public int ContentIndex => contentIndex;
public ContentIndices(int index, int contentIndex) public ContentIndices(int index, int contentIndex)
{ {
@ -38,7 +38,10 @@ namespace libWiiSharp
public int CompareTo(object obj) public int CompareTo(object obj)
{ {
if (obj is ContentIndices contentIndices) if (obj is ContentIndices contentIndices)
return this.contentIndex.CompareTo(contentIndices.contentIndex); {
return contentIndex.CompareTo(contentIndices.contentIndex);
}
throw new ArgumentException(); 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.
@ -63,9 +66,15 @@ namespace libWiiSharp
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;
} }
@ -82,22 +91,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;
} }
#endregion #endregion
@ -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,12 +358,20 @@ 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.SetTitleFromString(titles.Length > 1 ? titles[1] : titles[0], length);
}
imet.iconSize = (uint)iconSize; imet.iconSize = (uint)iconSize;
imet.bannerSize = (uint)bannerSize; imet.bannerSize = (uint)bannerSize;
imet.soundSize = (uint)soundSize; imet.soundSize = (uint)soundSize;
@ -370,7 +402,7 @@ namespace libWiiSharp
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);
writeStream.Write(unknownTitle2, 0, unknownTitle2.Length);
writeStream.Write(koreanTitle, 0, koreanTitle.Length);
writeStream.Write(padding2, 0, padding2.Length);
int position = (int)writeStream.Position; int position = (int)writeStream.Position;
this.hash = new byte[16]; hash = new byte[16];
writeStream.Write(this.hash, 0, this.hash.Length); 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,20 +656,20 @@ 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()
{ {
@ -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,7 +753,7 @@ 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);
} }
@ -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,7 +782,7 @@ 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);
} }
@ -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.
@ -123,30 +90,44 @@ namespace libWiiSharp
{ {
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,20 +182,30 @@ 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
{ {
@ -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();
@ -264,7 +271,7 @@ namespace libWiiSharp
{ {
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;
@ -283,7 +290,7 @@ namespace libWiiSharp
{ {
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());
@ -293,7 +300,14 @@ namespace libWiiSharp
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();
@ -311,7 +325,7 @@ namespace libWiiSharp
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; return num;
} }
private int patchEsIdentify(ref byte[] esModule) private int PrivPatchEsIdentify(ref byte[] esModule)
{ {
this.fireDebug("Patching ES_Identify..."); FireDebug("Patching ES_Identify...");
int num = 0; int num = 0;
byte[] second = new byte[4] byte[] second = new byte[4]
{ {
(byte) 40, 40,
(byte) 3, 3,
(byte) 209, 209,
(byte) 35 35
}; };
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 at Offset: 0x{0}", (object) firstIndex.ToString("x8").ToUpper()); FireDebug(" Patching 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;
} }
} }
this.fireDebug("Patching ES_Identify Finished... (Patches applied: {0})", (object) num); FireDebug("Patching ES_Identify Finished... (Patches applied: {0})", (object)num);
return num; return num;
} }
private int patchNandPermissions(ref byte[] esModule) private int PrivPatchNandPermissions(ref byte[] esModule)
{ {
this.fireDebug("Patching NAND Permissions..."); 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
} }

118
Lz77.cs
View file

@ -11,20 +11,23 @@ namespace libWiiSharp
{ {
public class Lz77 public class Lz77
{ {
private const int N = 4096; //private const int N = 4096;
private const int F = 18; //private const int F = 18;
private const int threshold = 2; //private const int threshold = 2;
private static uint lz77Magic = 1280980791; private static readonly uint lz77Magic = 1280980791;
private int[] leftSon = new int[4097]; //private readonly int[] leftSon = new int[4097];
private int[] rightSon = new int[4353]; //private readonly int[] rightSon = new int[4353];
private int[] dad = new int[4097]; //private readonly int[] dad = new int[4097];
private ushort[] textBuffer = new ushort[4113]; private readonly ushort[] textBuffer = new ushort[4113];
private int matchPosition; //private int matchPosition;
private int matchLength; //private int matchLength;
public static uint Lz77Magic => Lz77.lz77Magic; public static uint Lz77Magic => Lz77.lz77Magic;
public static bool IsLz77Compressed(string file) => Lz77.IsLz77Compressed(File.ReadAllBytes(file)); public static bool IsLz77Compressed(string file)
{
return Lz77.IsLz77Compressed(File.ReadAllBytes(file));
}
public static bool IsLz77Compressed(byte[] file) public static bool IsLz77Compressed(byte[] file)
{ {
@ -43,42 +46,73 @@ namespace libWiiSharp
public void Compress(string inFile, string outFile) public void Compress(string inFile, string outFile)
{ {
Stream stream = (Stream) null; Stream stream = null;
using (FileStream fileStream = new FileStream(inFile, FileMode.Open)) using (FileStream fileStream = new FileStream(inFile, FileMode.Open))
stream = this.compress((Stream) fileStream); {
stream = Compress(fileStream);
}
byte[] buffer = new byte[stream.Length]; byte[] buffer = new byte[stream.Length];
stream.Read(buffer, 0, buffer.Length); stream.Read(buffer, 0, buffer.Length);
if (File.Exists(outFile)) if (File.Exists(outFile))
{
File.Delete(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(); using (FileStream fileStream = new FileStream(outFile, FileMode.Create))
{
fileStream.Write(buffer, 0, buffer.Length);
}
}
public Stream Compress(Stream file) => this.compress(file); public byte[] Compress(byte[] file)
{
return ((MemoryStream)Compress(new MemoryStream(file))).ToArray();
}
public Stream Compress(Stream file)
{
return Compress(file);
}
public void Decompress(string inFile, string outFile) public void Decompress(string inFile, string outFile)
{ {
Stream stream = (Stream) null; Stream stream = null;
using (FileStream fileStream = new FileStream(inFile, FileMode.Open)) using (FileStream fileStream = new FileStream(inFile, FileMode.Open))
stream = this.decompress((Stream) fileStream); {
stream = Decompress(fileStream);
}
byte[] buffer = new byte[stream.Length]; byte[] buffer = new byte[stream.Length];
stream.Read(buffer, 0, buffer.Length); stream.Read(buffer, 0, buffer.Length);
if (File.Exists(outFile)) if (File.Exists(outFile))
{
File.Delete(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(); using (FileStream fileStream = new FileStream(outFile, FileMode.Create))
{
fileStream.Write(buffer, 0, buffer.Length);
}
}
public Stream Decompress(Stream file) => this.decompress(file); public byte[] Decompress(byte[] file)
{
return ((MemoryStream)PrivDecompress(new MemoryStream(file))).ToArray();
}
private Stream decompress(Stream inFile) public Stream Decompress(Stream file)
{
return PrivDecompress(file);
}
private Stream PrivDecompress(Stream inFile)
{ {
if (!Lz77.IsLz77Compressed(inFile)) if (!Lz77.IsLz77Compressed(inFile))
{
return inFile; return inFile;
}
inFile.Seek(0L, SeekOrigin.Begin); inFile.Seek(0L, SeekOrigin.Begin);
uint num1 = 0; uint num1 = 0;
Headers.HeaderType headerType = Headers.DetectHeader(inFile); Headers.HeaderType headerType = Headers.DetectHeader(inFile);
@ -90,14 +124,17 @@ namespace libWiiSharp
inFile.Dispose(); inFile.Dispose();
throw new Exception("Invaild Magic!"); throw new Exception("Invaild Magic!");
} }
if (buffer[4] != (byte) 16) if (buffer[4] != 16)
{ {
inFile.Dispose(); inFile.Dispose();
throw new Exception("Unsupported Compression Type!"); throw new Exception("Unsupported Compression Type!");
} }
uint num2 = BitConverter.ToUInt32(buffer, 4) >> 8; uint num2 = BitConverter.ToUInt32(buffer, 4) >> 8;
for (int index = 0; index < 4078; ++index) for (int index = 0; index < 4078; ++index)
this.textBuffer[index] = (ushort) 223; {
textBuffer[index] = 223;
}
int num3 = 4078; int num3 = 4078;
uint num4 = 7; uint num4 = 7;
int num5 = 7; int num5 = 7;
@ -116,29 +153,38 @@ label_10:
num5 = 0; num5 = 0;
} }
else else
{
goto label_24; goto label_24;
} }
}
if (((int)num4 & 128) == 0) if (((int)num4 & 128) == 0)
{ {
int num6; int num6;
if ((long) (num6 = inFile.ReadByte()) != inFile.Length - 1L) if ((num6 = inFile.ReadByte()) != inFile.Length - 1L)
{ {
if (num1 < num2) if (num1 < num2)
{
memoryStream.WriteByte((byte)num6); memoryStream.WriteByte((byte)num6);
}
ushort[] textBuffer = this.textBuffer; ushort[] textBuffer = this.textBuffer;
int index = num3; int index = num3;
int num7 = index + 1; int num7 = index + 1;
int num8 = (int) (byte) num6; int num8 = (byte)num6;
textBuffer[index] = (ushort)num8; textBuffer[index] = (ushort)num8;
num3 = num7 & 4095; num3 = num7 & 4095;
++num1; ++num1;
} }
else else
{
goto label_24; goto label_24;
} }
}
else else
{
break; break;
} }
}
int num9; int num9;
int num10; int num10;
if ((num9 = inFile.ReadByte()) != -1 && (num10 = inFile.ReadByte()) != -1) if ((num9 = inFile.ReadByte()) != -1 && (num10 = inFile.ReadByte()) != -1)
@ -147,13 +193,16 @@ label_10:
int num7 = (num9 >> 4 & 15) + 2; int num7 = (num9 >> 4 & 15) + 2;
for (int index1 = 0; index1 <= num7; ++index1) for (int index1 = 0; index1 <= num7; ++index1)
{ {
int num8 = (int) this.textBuffer[num3 - num6 - 1 & 4095]; int num8 = this.textBuffer[num3 - num6 - 1 & 4095];
if (num1 < num2) if (num1 < num2)
{
memoryStream.WriteByte((byte)num8); memoryStream.WriteByte((byte)num8);
}
ushort[] textBuffer = this.textBuffer; ushort[] textBuffer = this.textBuffer;
int index2 = num3; int index2 = num3;
int num11 = index2 + 1; int num11 = index2 + 1;
int num12 = (int) (byte) num8; int num12 = (byte)num8;
textBuffer[index2] = (ushort)num12; textBuffer[index2] = (ushort)num12;
num3 = num11 & 4095; num3 = num11 & 4095;
++num1; ++num1;
@ -161,10 +210,10 @@ label_10:
goto label_10; goto label_10;
} }
label_24: label_24:
return (Stream) memoryStream; return memoryStream;
} }
/*
private Stream compress(Stream inFile) private Stream PrivCompress(Stream inFile)
{ {
if (Lz77.IsLz77Compressed(inFile)) if (Lz77.IsLz77Compressed(inFile))
return inFile; return inFile;
@ -268,7 +317,6 @@ label_24:
for (int index = 0; index < 4096; ++index) for (int index = 0; index < 4096; ++index)
this.dad[index] = 4096; this.dad[index] = 4096;
} }
private void InsertNode(int r) private void InsertNode(int r)
{ {
int num1 = 1; int num1 = 1;
@ -319,7 +367,6 @@ label_24:
this.leftSon[this.dad[index]] = r; this.leftSon[this.dad[index]] = r;
this.dad[index] = 4096; this.dad[index] = 4096;
} }
private void DeleteNode(int p) private void DeleteNode(int p)
{ {
if (this.dad[p] == 4096) if (this.dad[p] == 4096)
@ -356,5 +403,6 @@ label_24:
this.leftSon[this.dad[p]] = index; this.leftSon[this.dad[p]] = index;
this.dad[p] = 4096; this.dad[p] = 4096;
} }
*/
} }
} }

View file

@ -10,10 +10,13 @@ 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

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

View file

@ -15,12 +15,14 @@ namespace libWiiSharp
{ {
public static string[] MergeStringArrays(string[] a, string[] b) public static string[] MergeStringArrays(string[] a, string[] b)
{ {
List<string> stringList = new List<string>((IEnumerable<string>) a); List<string> stringList = new List<string>(a);
foreach (string str in b) foreach (string str in b)
{ {
if (!stringList.Contains(str)) if (!stringList.Contains(str))
{
stringList.Add(str); stringList.Add(str);
} }
}
stringList.Sort(); stringList.Sort();
return stringList.ToArray(); return stringList.ToArray();
} }
@ -33,24 +35,34 @@ namespace libWiiSharp
int length) int length)
{ {
if (first.Length < length || second.Length < length) if (first.Length < length || second.Length < length)
{
return false; return false;
}
for (int index = 0; index < length; ++index) for (int index = 0; index < length; ++index)
{ {
if ((int) first[firstIndex + index] != (int) second[secondIndex + index]) if (first[firstIndex + index] != second[secondIndex + index])
{
return false; return false;
} }
}
return true; return true;
} }
public static bool CompareByteArrays(byte[] first, byte[] second) public static bool CompareByteArrays(byte[] first, byte[] second)
{ {
if (first.Length != second.Length) if (first.Length != second.Length)
{
return false; return false;
}
for (int index = 0; index < first.Length; ++index) for (int index = 0; index < first.Length; ++index)
{ {
if ((int) first[index] != (int) second[index]) if (first[index] != second[index])
{
return false; return false;
} }
}
return true; return true;
} }
@ -58,7 +70,10 @@ namespace libWiiSharp
{ {
string str = string.Empty; string str = string.Empty;
foreach (byte num in byteArray) foreach (byte num in byteArray)
{
str = str + num.ToString("x2").ToUpper() + separator.ToString(); str = str + num.ToString("x2").ToUpper() + separator.ToString();
}
return str.Remove(str.Length - 1); return str.Remove(str.Length - 1);
} }
@ -66,7 +81,10 @@ namespace libWiiSharp
{ {
byte[] numArray = new byte[hexString.Length / 2]; byte[] numArray = new byte[hexString.Length / 2];
for (int index = 0; index < hexString.Length / 2; ++index) for (int index = 0; index < hexString.Length / 2; ++index)
{
numArray[index] = byte.Parse(hexString.Substring(index * 2, 2), NumberStyles.HexNumber); numArray[index] = byte.Parse(hexString.Substring(index * 2, 2), NumberStyles.HexNumber);
}
return numArray; return numArray;
} }
@ -75,35 +93,58 @@ namespace libWiiSharp
int num1 = 0; int num1 = 0;
foreach (int num2 in theString) foreach (int num2 in theString)
{ {
if (num2 == (int) theChar) if (num2 == theChar)
{
++num1; ++num1;
} }
}
return num1; return num1;
} }
public static long AddPadding(long value) => Shared.AddPadding(value, 64); public static long AddPadding(long value)
{
return Shared.AddPadding(value, 64);
}
public static long AddPadding(long value, int padding) public static long AddPadding(long value, int padding)
{ {
if (value % (long) padding != 0L) if (value % padding != 0L)
value += (long) padding - value % (long) padding; {
value += padding - value % padding;
}
return value; return value;
} }
public static int AddPadding(int value) => Shared.AddPadding(value, 64); public static int AddPadding(int value)
{
return Shared.AddPadding(value, 64);
}
public static int AddPadding(int value, int padding) public static int AddPadding(int value, int padding)
{ {
if (value % padding != 0) if (value % padding != 0)
{
value += padding - value % padding; value += padding - value % padding;
}
return value; return value;
} }
public static ushort Swap(ushort value) => (ushort) IPAddress.HostToNetworkOrder((short) value); public static ushort Swap(ushort value)
{
return (ushort)IPAddress.HostToNetworkOrder((short)value);
}
public static uint Swap(uint value) => (uint) IPAddress.HostToNetworkOrder((int) value); public static uint Swap(uint value)
{
return (uint)IPAddress.HostToNetworkOrder((int)value);
}
public static ulong Swap(ulong value) => (ulong) IPAddress.HostToNetworkOrder((long) value); public static ulong Swap(ulong value)
{
return (ulong)IPAddress.HostToNetworkOrder((long)value);
}
public static byte[] UShortArrayToByteArray(ushort[] array) public static byte[] UShortArrayToByteArray(ushort[] array)
{ {
@ -111,7 +152,7 @@ namespace libWiiSharp
foreach (ushort num in array) foreach (ushort num in array)
{ {
byte[] bytes = BitConverter.GetBytes(num); byte[] bytes = BitConverter.GetBytes(num);
byteList.AddRange((IEnumerable<byte>) bytes); byteList.AddRange(bytes);
} }
return byteList.ToArray(); return byteList.ToArray();
} }
@ -122,7 +163,7 @@ namespace libWiiSharp
foreach (uint num in array) foreach (uint num in array)
{ {
byte[] bytes = BitConverter.GetBytes(num); byte[] bytes = BitConverter.GetBytes(num);
byteList.AddRange((IEnumerable<byte>) bytes); byteList.AddRange(bytes);
} }
return byteList.ToArray(); return byteList.ToArray();
} }
@ -132,7 +173,10 @@ namespace libWiiSharp
uint[] numArray = new uint[array.Length / 4]; uint[] numArray = new uint[array.Length / 4];
int num = 0; int num = 0;
for (int startIndex = 0; startIndex < array.Length; startIndex += 4) for (int startIndex = 0; startIndex < array.Length; startIndex += 4)
{
numArray[num++] = BitConverter.ToUInt32(array, startIndex); numArray[num++] = BitConverter.ToUInt32(array, startIndex);
}
return numArray; return numArray;
} }
@ -141,7 +185,10 @@ namespace libWiiSharp
ushort[] numArray = new ushort[array.Length / 2]; ushort[] numArray = new ushort[array.Length / 2];
int num = 0; int num = 0;
for (int startIndex = 0; startIndex < array.Length; startIndex += 2) for (int startIndex = 0; startIndex < array.Length; startIndex += 2)
{
numArray[num++] = BitConverter.ToUInt16(array, startIndex); numArray[num++] = BitConverter.ToUInt16(array, startIndex);
}
return numArray; return numArray;
} }
} }

444
TMD.cs
View file

@ -46,88 +46,94 @@ namespace libWiiSharp
public Region Region public Region Region
{ {
get => (Region) this.region; get => (Region)region;
set => this.region = (ushort) value; set => region = (ushort)value;
} }
public ulong StartupIOS public ulong StartupIOS
{ {
get => this.startupIos; get => startupIos;
set => this.startupIos = value; set => startupIos = value;
} }
public ulong TitleID public ulong TitleID
{ {
get => this.titleId; get => titleId;
set => this.titleId = value; set => titleId = value;
} }
public ushort TitleVersion public ushort TitleVersion
{ {
get => this.titleVersion; get => titleVersion;
set => this.titleVersion = value; set => titleVersion = value;
} }
public ushort NumOfContents => this.numOfContents; public ushort NumOfContents => numOfContents;
public ushort BootIndex public ushort BootIndex
{ {
get => this.bootIndex; get => bootIndex;
set set
{ {
if ((int) value > (int) this.numOfContents) if (value > numOfContents)
{
return; return;
this.bootIndex = value; }
bootIndex = value;
} }
} }
public TMD_Content[] Contents public TMD_Content[] Contents
{ {
get => this.contents.ToArray(); get => contents.ToArray();
set set
{ {
this.contents = new List<TMD_Content>((IEnumerable<TMD_Content>) value); contents = new List<TMD_Content>(value);
this.numOfContents = (ushort) value.Length; numOfContents = (ushort)value.Length;
} }
} }
public bool FakeSign public bool FakeSign
{ {
get => this.fakeSign; get => fakeSign;
set => this.fakeSign = value; set => fakeSign = value;
} }
public bool SortContents public bool SortContents
{ {
get => this.sortContents; get => sortContents;
set => this.sortContents = true; set => sortContents = true;
} }
public event EventHandler<MessageEventArgs> Debug; public event EventHandler<MessageEventArgs> Debug;
~TMD() => this.Dispose(false); ~TMD() => 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.signature = (byte[]) null; signature = null;
this.padding = (byte[]) null; padding = null;
this.issuer = (byte[]) null; issuer = null;
this.reserved = (byte[]) null; reserved = null;
this.contents.Clear(); contents.Clear();
this.contents = (List<TMD_Content>) null; contents = null;
} }
this.isDisposed = true; isDisposed = true;
} }
public static TMD Load(string pathToTmd) => TMD.Load(File.ReadAllBytes(pathToTmd)); public static TMD Load(string pathToTmd)
{
return TMD.Load(File.ReadAllBytes(pathToTmd));
}
public static TMD Load(byte[] tmdFile) public static TMD Load(byte[] tmdFile)
{ {
@ -135,7 +141,7 @@ namespace libWiiSharp
MemoryStream memoryStream = new MemoryStream(tmdFile); MemoryStream memoryStream = new MemoryStream(tmdFile);
try try
{ {
tmd.parseTmd((Stream) memoryStream); tmd.ParseTmd(memoryStream);
} }
catch catch
{ {
@ -149,18 +155,21 @@ namespace libWiiSharp
public static TMD Load(Stream tmd) public static TMD Load(Stream tmd)
{ {
TMD tmd1 = new TMD(); TMD tmd1 = new TMD();
tmd1.parseTmd(tmd); tmd1.ParseTmd(tmd);
return tmd1; return tmd1;
} }
public void LoadFile(string pathToTmd) => this.LoadFile(File.ReadAllBytes(pathToTmd)); public void LoadFile(string pathToTmd)
{
LoadFile(File.ReadAllBytes(pathToTmd));
}
public void LoadFile(byte[] tmdFile) public void LoadFile(byte[] tmdFile)
{ {
MemoryStream memoryStream = new MemoryStream(tmdFile); MemoryStream memoryStream = new MemoryStream(tmdFile);
try try
{ {
this.parseTmd((Stream) memoryStream); ParseTmd(memoryStream);
} }
catch catch
{ {
@ -170,30 +179,48 @@ namespace libWiiSharp
memoryStream.Dispose(); memoryStream.Dispose();
} }
public void LoadFile(Stream tmd) => this.parseTmd(tmd); public void LoadFile(Stream tmd)
{
ParseTmd(tmd);
}
public void Save(string savePath) => this.Save(savePath, false); public void Save(string savePath)
{
Save(savePath, false);
}
public void Save(string savePath, bool fakeSign) public void Save(string savePath, bool fakeSign)
{ {
if (fakeSign) if (fakeSign)
{
this.fakeSign = true; 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); if (File.Exists(savePath))
{
File.Delete(savePath);
}
using FileStream fileStream = new FileStream(savePath, FileMode.Create);
WriteToStream(fileStream);
}
public MemoryStream ToMemoryStream()
{
return ToMemoryStream(false);
}
public MemoryStream ToMemoryStream(bool fakeSign) public MemoryStream ToMemoryStream(bool fakeSign)
{ {
if (fakeSign) if (fakeSign)
{
this.fakeSign = true; this.fakeSign = true;
}
MemoryStream memoryStream = new MemoryStream(); MemoryStream memoryStream = new MemoryStream();
try try
{ {
this.writeToStream((Stream) memoryStream); WriteToStream(memoryStream);
return memoryStream; return memoryStream;
} }
catch catch
@ -203,16 +230,22 @@ namespace libWiiSharp
} }
} }
public byte[] ToByteArray() => this.ToByteArray(false); public byte[] ToByteArray()
{
return ToByteArray(false);
}
public byte[] ToByteArray(bool fakeSign) public byte[] ToByteArray(bool fakeSign)
{ {
if (fakeSign) if (fakeSign)
{
this.fakeSign = true; this.fakeSign = true;
}
MemoryStream memoryStream = new MemoryStream(); MemoryStream memoryStream = new MemoryStream();
try try
{ {
this.writeToStream((Stream) memoryStream); WriteToStream(memoryStream);
} }
catch catch
{ {
@ -228,12 +261,12 @@ namespace libWiiSharp
{ {
bool flag = true; bool flag = true;
char directorySeparatorChar; char directorySeparatorChar;
for (int index = 0; index < this.contents.Count; ++index) for (int index = 0; index < contents.Count; ++index)
{ {
string str1 = contentDir; string str1 = contentDir;
directorySeparatorChar = Path.DirectorySeparatorChar; directorySeparatorChar = Path.DirectorySeparatorChar;
string str2 = directorySeparatorChar.ToString(); string str2 = directorySeparatorChar.ToString();
string str3 = this.contents[index].ContentID.ToString("x8"); string str3 = contents[index].ContentID.ToString("x8");
if (!File.Exists(str1 + str2 + str3 + ".app")) if (!File.Exists(str1 + str2 + str3 + ".app"))
{ {
flag = false; flag = false;
@ -242,34 +275,39 @@ namespace libWiiSharp
} }
if (!flag) if (!flag)
{ {
for (int index = 0; index < this.contents.Count; ++index) for (int index = 0; index < contents.Count; ++index)
{ {
string str1 = contentDir; string str1 = contentDir;
directorySeparatorChar = Path.DirectorySeparatorChar; directorySeparatorChar = Path.DirectorySeparatorChar;
string str2 = directorySeparatorChar.ToString(); string str2 = directorySeparatorChar.ToString();
string str3 = this.contents[index].ContentID.ToString("x8"); string str3 = contents[index].ContentID.ToString("x8");
if (!File.Exists(str1 + str2 + str3 + ".app")) if (!File.Exists(str1 + str2 + str3 + ".app"))
{
throw new Exception("Couldn't find all content files!"); throw new Exception("Couldn't find all content files!");
} }
} }
byte[][] conts = new byte[this.contents.Count][]; }
for (int index = 0; index < this.contents.Count; ++index) byte[][] conts = new byte[contents.Count][];
for (int index = 0; index < contents.Count; ++index)
{ {
string str1 = contentDir; string str1 = contentDir;
directorySeparatorChar = Path.DirectorySeparatorChar; directorySeparatorChar = Path.DirectorySeparatorChar;
string str2 = directorySeparatorChar.ToString(); string str2 = directorySeparatorChar.ToString();
string str3 = flag ? this.contents[index].ContentID.ToString("x8") : this.contents[index].Index.ToString("x8"); string str3 = flag ? contents[index].ContentID.ToString("x8") : contents[index].Index.ToString("x8");
string path = str1 + str2 + str3 + ".app"; string path = str1 + str2 + str3 + ".app";
conts[index] = File.ReadAllBytes(path); conts[index] = File.ReadAllBytes(path);
} }
this.updateContents(conts); UpdateContents(conts);
} }
public void UpdateContents(byte[][] contents) => this.updateContents(contents); public void UpdateContents(byte[][] contents)
{
UpdateContents(contents);
}
public string GetUpperTitleID() public string GetUpperTitleID()
{ {
byte[] bytes = BitConverter.GetBytes(Shared.Swap((uint) this.titleId)); byte[] bytes = BitConverter.GetBytes(Shared.Swap((uint)titleId));
return new string(new char[4] return new string(new char[4]
{ {
(char) bytes[0], (char) bytes[0],
@ -279,134 +317,149 @@ namespace libWiiSharp
}); });
} }
public string GetNandBlocks() => this.calculateNandBlocks(); public string GetNandBlocks()
{
return CalculateNandBlocks();
}
public void AddContent(TMD_Content content) public void AddContent(TMD_Content content)
{ {
this.contents.Add(content); contents.Add(content);
this.numOfContents = (ushort) this.contents.Count; numOfContents = (ushort)contents.Count;
} }
public void RemoveContent(int contentIndex) public void RemoveContent(int contentIndex)
{ {
for (int index = 0; index < (int) this.numOfContents; ++index) for (int index = 0; index < numOfContents; ++index)
{ {
if ((int) this.contents[index].Index == contentIndex) if (contents[index].Index == contentIndex)
{ {
this.contents.RemoveAt(index); contents.RemoveAt(index);
break; break;
} }
} }
this.numOfContents = (ushort) this.contents.Count; numOfContents = (ushort)contents.Count;
} }
public void RemoveContentByID(int contentId) public void RemoveContentByID(int contentId)
{ {
for (int index = 0; index < (int) this.numOfContents; ++index) for (int index = 0; index < numOfContents; ++index)
{ {
if ((long) this.contents[index].ContentID == (long) contentId) if (contents[index].ContentID == contentId)
{ {
this.contents.RemoveAt(index); contents.RemoveAt(index);
break; break;
} }
} }
this.numOfContents = (ushort) this.contents.Count; numOfContents = (ushort)contents.Count;
} }
public ContentIndices[] GetSortedContentList() public ContentIndices[] GetSortedContentList()
{ {
List<ContentIndices> contentIndicesList = new List<ContentIndices>(); List<ContentIndices> contentIndicesList = new List<ContentIndices>();
for (int index = 0; index < this.contents.Count; ++index) for (int index = 0; index < contents.Count; ++index)
contentIndicesList.Add(new ContentIndices(index, (int) this.contents[index].Index)); {
if (this.sortContents) contentIndicesList.Add(new ContentIndices(index, contents[index].Index));
}
if (sortContents)
{
contentIndicesList.Sort(); contentIndicesList.Sort();
}
return contentIndicesList.ToArray(); return contentIndicesList.ToArray();
} }
private void writeToStream(Stream writeStream) private void WriteToStream(Stream writeStream)
{ {
this.fireDebug("Writing TMD..."); FireDebug("Writing TMD...");
if (this.fakeSign) if (fakeSign)
{ {
this.fireDebug(" Clearing Signature..."); FireDebug(" Clearing Signature...");
this.signature = new byte[256]; signature = new byte[256];
} }
MemoryStream memoryStream = new MemoryStream(); MemoryStream memoryStream = new MemoryStream();
memoryStream.Seek(0L, SeekOrigin.Begin); memoryStream.Seek(0L, SeekOrigin.Begin);
this.fireDebug(" Writing Signature Exponent... (Offset: 0x{0})", (object) memoryStream.Position.ToString("x8").ToUpper()); FireDebug(" Writing Signature Exponent... (Offset: 0x{0})", (object)memoryStream.Position.ToString("x8").ToUpper());
memoryStream.Write(BitConverter.GetBytes(Shared.Swap(this.signatureExponent)), 0, 4); memoryStream.Write(BitConverter.GetBytes(Shared.Swap(signatureExponent)), 0, 4);
this.fireDebug(" Writing Signature... (Offset: 0x{0})", (object) memoryStream.Position.ToString("x8").ToUpper()); FireDebug(" Writing Signature... (Offset: 0x{0})", (object)memoryStream.Position.ToString("x8").ToUpper());
memoryStream.Write(this.signature, 0, this.signature.Length); memoryStream.Write(signature, 0, signature.Length);
this.fireDebug(" Writing Padding... (Offset: 0x{0})", (object) memoryStream.Position.ToString("x8").ToUpper()); FireDebug(" Writing Padding... (Offset: 0x{0})", (object)memoryStream.Position.ToString("x8").ToUpper());
memoryStream.Write(this.padding, 0, this.padding.Length); memoryStream.Write(padding, 0, padding.Length);
this.fireDebug(" Writing Issuer... (Offset: 0x{0})", (object) memoryStream.Position.ToString("x8").ToUpper()); FireDebug(" Writing Issuer... (Offset: 0x{0})", (object)memoryStream.Position.ToString("x8").ToUpper());
memoryStream.Write(this.issuer, 0, this.issuer.Length); memoryStream.Write(issuer, 0, issuer.Length);
this.fireDebug(" Writing Version... (Offset: 0x{0})", (object) memoryStream.Position.ToString("x8").ToUpper()); FireDebug(" Writing Version... (Offset: 0x{0})", (object)memoryStream.Position.ToString("x8").ToUpper());
memoryStream.WriteByte(this.version); memoryStream.WriteByte(version);
this.fireDebug(" Writing CA Crl Version... (Offset: 0x{0})", (object) memoryStream.Position.ToString("x8").ToUpper()); FireDebug(" Writing CA Crl Version... (Offset: 0x{0})", (object)memoryStream.Position.ToString("x8").ToUpper());
memoryStream.WriteByte(this.caCrlVersion); memoryStream.WriteByte(caCrlVersion);
this.fireDebug(" Writing Signer Crl Version... (Offset: 0x{0})", (object) memoryStream.Position.ToString("x8").ToUpper()); FireDebug(" Writing Signer Crl Version... (Offset: 0x{0})", (object)memoryStream.Position.ToString("x8").ToUpper());
memoryStream.WriteByte(this.signerCrlVersion); memoryStream.WriteByte(signerCrlVersion);
this.fireDebug(" Writing Padding Byte... (Offset: 0x{0})", (object) memoryStream.Position.ToString("x8").ToUpper()); FireDebug(" Writing Padding Byte... (Offset: 0x{0})", (object)memoryStream.Position.ToString("x8").ToUpper());
memoryStream.WriteByte(this.paddingByte); memoryStream.WriteByte(paddingByte);
this.fireDebug(" Writing Startup IOS... (Offset: 0x{0})", (object) memoryStream.Position.ToString("x8").ToUpper()); FireDebug(" Writing Startup IOS... (Offset: 0x{0})", (object)memoryStream.Position.ToString("x8").ToUpper());
memoryStream.Write(BitConverter.GetBytes(Shared.Swap(this.startupIos)), 0, 8); memoryStream.Write(BitConverter.GetBytes(Shared.Swap(startupIos)), 0, 8);
this.fireDebug(" Writing Title ID... (Offset: 0x{0})", (object) memoryStream.Position.ToString("x8").ToUpper()); FireDebug(" Writing Title ID... (Offset: 0x{0})", (object)memoryStream.Position.ToString("x8").ToUpper());
memoryStream.Write(BitConverter.GetBytes(Shared.Swap(this.titleId)), 0, 8); memoryStream.Write(BitConverter.GetBytes(Shared.Swap(titleId)), 0, 8);
this.fireDebug(" Writing Title Type... (Offset: 0x{0})", (object) memoryStream.Position.ToString("x8").ToUpper()); FireDebug(" Writing Title Type... (Offset: 0x{0})", (object)memoryStream.Position.ToString("x8").ToUpper());
memoryStream.Write(BitConverter.GetBytes(Shared.Swap(this.titleType)), 0, 4); memoryStream.Write(BitConverter.GetBytes(Shared.Swap(titleType)), 0, 4);
this.fireDebug(" Writing Group ID... (Offset: 0x{0})", (object) memoryStream.Position.ToString("x8").ToUpper()); FireDebug(" Writing Group ID... (Offset: 0x{0})", (object)memoryStream.Position.ToString("x8").ToUpper());
memoryStream.Write(BitConverter.GetBytes(Shared.Swap(this.groupId)), 0, 2); memoryStream.Write(BitConverter.GetBytes(Shared.Swap(groupId)), 0, 2);
this.fireDebug(" Writing Padding2... (Offset: 0x{0})", (object) memoryStream.Position.ToString("x8").ToUpper()); FireDebug(" Writing Padding2... (Offset: 0x{0})", (object)memoryStream.Position.ToString("x8").ToUpper());
memoryStream.Write(BitConverter.GetBytes(Shared.Swap(this.padding2)), 0, 2); memoryStream.Write(BitConverter.GetBytes(Shared.Swap(padding2)), 0, 2);
this.fireDebug(" Writing Region... (Offset: 0x{0})", (object) memoryStream.Position.ToString("x8").ToUpper()); FireDebug(" Writing Region... (Offset: 0x{0})", (object)memoryStream.Position.ToString("x8").ToUpper());
memoryStream.Write(BitConverter.GetBytes(Shared.Swap(this.region)), 0, 2); memoryStream.Write(BitConverter.GetBytes(Shared.Swap(region)), 0, 2);
this.fireDebug(" Writing Reserved... (Offset: 0x{0})", (object) memoryStream.Position.ToString("x8").ToUpper()); FireDebug(" Writing Reserved... (Offset: 0x{0})", (object)memoryStream.Position.ToString("x8").ToUpper());
memoryStream.Write(this.reserved, 0, this.reserved.Length); memoryStream.Write(reserved, 0, reserved.Length);
this.fireDebug(" Writing Access Rights... (Offset: 0x{0})", (object) memoryStream.Position.ToString("x8").ToUpper()); FireDebug(" Writing Access Rights... (Offset: 0x{0})", (object)memoryStream.Position.ToString("x8").ToUpper());
memoryStream.Write(BitConverter.GetBytes(Shared.Swap(this.accessRights)), 0, 4); memoryStream.Write(BitConverter.GetBytes(Shared.Swap(accessRights)), 0, 4);
this.fireDebug(" Writing Title Version... (Offset: 0x{0})", (object) memoryStream.Position.ToString("x8").ToUpper()); FireDebug(" Writing Title Version... (Offset: 0x{0})", (object)memoryStream.Position.ToString("x8").ToUpper());
memoryStream.Write(BitConverter.GetBytes(Shared.Swap(this.titleVersion)), 0, 2); memoryStream.Write(BitConverter.GetBytes(Shared.Swap(titleVersion)), 0, 2);
this.fireDebug(" Writing NumOfContents... (Offset: 0x{0})", (object) memoryStream.Position.ToString("x8").ToUpper()); FireDebug(" Writing NumOfContents... (Offset: 0x{0})", (object)memoryStream.Position.ToString("x8").ToUpper());
memoryStream.Write(BitConverter.GetBytes(Shared.Swap(this.numOfContents)), 0, 2); memoryStream.Write(BitConverter.GetBytes(Shared.Swap(numOfContents)), 0, 2);
this.fireDebug(" Writing Boot Index... (Offset: 0x{0})", (object) memoryStream.Position.ToString("x8").ToUpper()); FireDebug(" Writing Boot Index... (Offset: 0x{0})", (object)memoryStream.Position.ToString("x8").ToUpper());
memoryStream.Write(BitConverter.GetBytes(Shared.Swap(this.bootIndex)), 0, 2); memoryStream.Write(BitConverter.GetBytes(Shared.Swap(bootIndex)), 0, 2);
this.fireDebug(" Writing Padding3... (Offset: 0x{0})", (object) memoryStream.Position.ToString("x8").ToUpper()); FireDebug(" Writing Padding3... (Offset: 0x{0})", (object)memoryStream.Position.ToString("x8").ToUpper());
memoryStream.Write(BitConverter.GetBytes(Shared.Swap(this.padding3)), 0, 2); memoryStream.Write(BitConverter.GetBytes(Shared.Swap(padding3)), 0, 2);
List<ContentIndices> contentIndicesList = new List<ContentIndices>(); List<ContentIndices> contentIndicesList = new List<ContentIndices>();
for (int index = 0; index < this.contents.Count; ++index) for (int index = 0; index < contents.Count; ++index)
contentIndicesList.Add(new ContentIndices(index, (int) this.contents[index].Index)); {
if (this.sortContents) contentIndicesList.Add(new ContentIndices(index, contents[index].Index));
}
if (sortContents)
{
contentIndicesList.Sort(); contentIndicesList.Sort();
}
for (int index = 0; index < contentIndicesList.Count; ++index) for (int index = 0; index < contentIndicesList.Count; ++index)
{ {
this.fireDebug(" Writing Content #{1} of {2}... (Offset: 0x{0})", (object) memoryStream.Position.ToString("x8").ToUpper().ToUpper(), (object) (index + 1), (object) this.numOfContents); FireDebug(" Writing Content #{1} of {2}... (Offset: 0x{0})", memoryStream.Position.ToString("x8").ToUpper().ToUpper(), index + 1, numOfContents);
memoryStream.Write(BitConverter.GetBytes(Shared.Swap(this.contents[contentIndicesList[index].Index].ContentID)), 0, 4); memoryStream.Write(BitConverter.GetBytes(Shared.Swap(contents[contentIndicesList[index].Index].ContentID)), 0, 4);
memoryStream.Write(BitConverter.GetBytes(Shared.Swap(this.contents[contentIndicesList[index].Index].Index)), 0, 2); memoryStream.Write(BitConverter.GetBytes(Shared.Swap(contents[contentIndicesList[index].Index].Index)), 0, 2);
memoryStream.Write(BitConverter.GetBytes(Shared.Swap((ushort) this.contents[contentIndicesList[index].Index].Type)), 0, 2); memoryStream.Write(BitConverter.GetBytes(Shared.Swap((ushort)contents[contentIndicesList[index].Index].Type)), 0, 2);
memoryStream.Write(BitConverter.GetBytes(Shared.Swap(this.contents[contentIndicesList[index].Index].Size)), 0, 8); memoryStream.Write(BitConverter.GetBytes(Shared.Swap(contents[contentIndicesList[index].Index].Size)), 0, 8);
memoryStream.Write(this.contents[contentIndicesList[index].Index].Hash, 0, this.contents[contentIndicesList[index].Index].Hash.Length); memoryStream.Write(contents[contentIndicesList[index].Index].Hash, 0, contents[contentIndicesList[index].Index].Hash.Length);
} }
byte[] array = memoryStream.ToArray(); byte[] array = memoryStream.ToArray();
memoryStream.Dispose(); memoryStream.Dispose();
if (this.fakeSign) if (fakeSign)
{ {
this.fireDebug(" Fakesigning TMD..."); FireDebug(" Fakesigning TMD...");
byte[] numArray = new byte[20]; //byte[] numArray = new byte[20];
SHA1 shA1 = SHA1.Create(); SHA1 shA1 = SHA1.Create();
for (ushort index = 0; index < ushort.MaxValue; ++index) for (ushort index = 0; index < ushort.MaxValue; ++index)
{ {
byte[] bytes = BitConverter.GetBytes(index); byte[] bytes = BitConverter.GetBytes(index);
array[482] = bytes[1]; array[482] = bytes[1];
array[483] = bytes[0]; array[483] = bytes[0];
if (shA1.ComputeHash(array)[0] == (byte) 0) if (shA1.ComputeHash(array)[0] == 0)
{ {
this.fireDebug(" -> Signed ({0})", (object) index); FireDebug(" -> Signed ({0})", (object)index);
break; break;
} }
if (index == (ushort) 65534) if (index == 65534)
{ {
this.fireDebug(" -> Signing Failed..."); FireDebug(" -> Signing Failed...");
throw new Exception("Fakesigning failed..."); throw new Exception("Fakesigning failed...");
} }
} }
@ -414,10 +467,11 @@ namespace libWiiSharp
} }
writeStream.Seek(0L, SeekOrigin.Begin); writeStream.Seek(0L, SeekOrigin.Begin);
writeStream.Write(array, 0, array.Length); writeStream.Write(array, 0, array.Length);
this.fireDebug("Writing TMD Finished..."); FireDebug("Writing TMD Finished...");
} }
private void updateContents(byte[][] conts) /*
private void PrivUpdateContents(byte[][] conts)
{ {
SHA1 shA1 = SHA1.Create(); SHA1 shA1 = SHA1.Create();
for (int index = 0; index < this.contents.Count; ++index) for (int index = 0; index < this.contents.Count; ++index)
@ -427,68 +481,71 @@ namespace libWiiSharp
} }
shA1.Clear(); shA1.Clear();
} }
*/
private void parseTmd(Stream tmdFile) private void ParseTmd(Stream tmdFile)
{ {
this.fireDebug("Pasing TMD..."); FireDebug("Pasing TMD...");
tmdFile.Seek(0L, SeekOrigin.Begin); tmdFile.Seek(0L, SeekOrigin.Begin);
byte[] buffer = new byte[8]; byte[] buffer = new byte[8];
this.fireDebug(" Reading Signature Exponent... (Offset: 0x{0})", (object) tmdFile.Position.ToString("x8").ToUpper()); FireDebug(" Reading Signature Exponent... (Offset: 0x{0})", (object)tmdFile.Position.ToString("x8").ToUpper());
tmdFile.Read(buffer, 0, 4); tmdFile.Read(buffer, 0, 4);
this.signatureExponent = Shared.Swap(BitConverter.ToUInt32(buffer, 0)); signatureExponent = Shared.Swap(BitConverter.ToUInt32(buffer, 0));
this.fireDebug(" Reading Signature... (Offset: 0x{0})", (object) tmdFile.Position.ToString("x8").ToUpper()); FireDebug(" Reading Signature... (Offset: 0x{0})", (object)tmdFile.Position.ToString("x8").ToUpper());
tmdFile.Read(this.signature, 0, this.signature.Length); tmdFile.Read(signature, 0, signature.Length);
this.fireDebug(" Reading Padding... (Offset: 0x{0})", (object) tmdFile.Position.ToString("x8").ToUpper()); FireDebug(" Reading Padding... (Offset: 0x{0})", (object)tmdFile.Position.ToString("x8").ToUpper());
tmdFile.Read(this.padding, 0, this.padding.Length); tmdFile.Read(padding, 0, padding.Length);
this.fireDebug(" Reading Issuer... (Offset: 0x{0})", (object) tmdFile.Position.ToString("x8").ToUpper()); FireDebug(" Reading Issuer... (Offset: 0x{0})", (object)tmdFile.Position.ToString("x8").ToUpper());
tmdFile.Read(this.issuer, 0, this.issuer.Length); tmdFile.Read(issuer, 0, issuer.Length);
this.fireDebug(" Reading Version... (Offset: 0x{0})", (object) tmdFile.Position.ToString("x8").ToUpper()); FireDebug(" Reading Version... (Offset: 0x{0})", (object)tmdFile.Position.ToString("x8").ToUpper());
this.fireDebug(" Reading CA Crl Version... (Offset: 0x{0})", (object) tmdFile.Position.ToString("x8").ToUpper()); FireDebug(" Reading CA Crl Version... (Offset: 0x{0})", (object)tmdFile.Position.ToString("x8").ToUpper());
this.fireDebug(" Reading Signer Crl Version... (Offset: 0x{0})", (object) tmdFile.Position.ToString("x8").ToUpper()); FireDebug(" Reading Signer Crl Version... (Offset: 0x{0})", (object)tmdFile.Position.ToString("x8").ToUpper());
this.fireDebug(" Reading Padding Byte... (Offset: 0x{0})", (object) tmdFile.Position.ToString("x8").ToUpper()); FireDebug(" Reading Padding Byte... (Offset: 0x{0})", (object)tmdFile.Position.ToString("x8").ToUpper());
tmdFile.Read(buffer, 0, 4); tmdFile.Read(buffer, 0, 4);
this.version = buffer[0]; version = buffer[0];
this.caCrlVersion = buffer[1]; caCrlVersion = buffer[1];
this.signerCrlVersion = buffer[2]; signerCrlVersion = buffer[2];
this.paddingByte = buffer[3]; paddingByte = buffer[3];
this.fireDebug(" Reading Startup IOS... (Offset: 0x{0})", (object) tmdFile.Position.ToString("x8").ToUpper()); FireDebug(" Reading Startup IOS... (Offset: 0x{0})", (object)tmdFile.Position.ToString("x8").ToUpper());
tmdFile.Read(buffer, 0, 8); tmdFile.Read(buffer, 0, 8);
this.startupIos = Shared.Swap(BitConverter.ToUInt64(buffer, 0)); startupIos = Shared.Swap(BitConverter.ToUInt64(buffer, 0));
this.fireDebug(" Reading Title ID... (Offset: 0x{0})", (object) tmdFile.Position.ToString("x8").ToUpper()); FireDebug(" Reading Title ID... (Offset: 0x{0})", (object)tmdFile.Position.ToString("x8").ToUpper());
tmdFile.Read(buffer, 0, 8); tmdFile.Read(buffer, 0, 8);
this.titleId = Shared.Swap(BitConverter.ToUInt64(buffer, 0)); titleId = Shared.Swap(BitConverter.ToUInt64(buffer, 0));
this.fireDebug(" Reading Title Type... (Offset: 0x{0})", (object) tmdFile.Position.ToString("x8").ToUpper()); FireDebug(" Reading Title Type... (Offset: 0x{0})", (object)tmdFile.Position.ToString("x8").ToUpper());
tmdFile.Read(buffer, 0, 4); tmdFile.Read(buffer, 0, 4);
this.titleType = Shared.Swap(BitConverter.ToUInt32(buffer, 0)); titleType = Shared.Swap(BitConverter.ToUInt32(buffer, 0));
this.fireDebug(" Reading Group ID... (Offset: 0x{0})", (object) tmdFile.Position.ToString("x8").ToUpper()); FireDebug(" Reading Group ID... (Offset: 0x{0})", (object)tmdFile.Position.ToString("x8").ToUpper());
tmdFile.Read(buffer, 0, 2); tmdFile.Read(buffer, 0, 2);
this.groupId = Shared.Swap(BitConverter.ToUInt16(buffer, 0)); groupId = Shared.Swap(BitConverter.ToUInt16(buffer, 0));
this.fireDebug(" Reading Padding2... (Offset: 0x{0})", (object) tmdFile.Position.ToString("x8").ToUpper()); FireDebug(" Reading Padding2... (Offset: 0x{0})", (object)tmdFile.Position.ToString("x8").ToUpper());
tmdFile.Read(buffer, 0, 2); tmdFile.Read(buffer, 0, 2);
this.padding2 = Shared.Swap(BitConverter.ToUInt16(buffer, 0)); padding2 = Shared.Swap(BitConverter.ToUInt16(buffer, 0));
this.fireDebug(" Reading Region... (Offset: 0x{0})", (object) tmdFile.Position.ToString("x8").ToUpper()); FireDebug(" Reading Region... (Offset: 0x{0})", (object)tmdFile.Position.ToString("x8").ToUpper());
tmdFile.Read(buffer, 0, 2); tmdFile.Read(buffer, 0, 2);
this.region = Shared.Swap(BitConverter.ToUInt16(buffer, 0)); region = Shared.Swap(BitConverter.ToUInt16(buffer, 0));
this.fireDebug(" Reading Reserved... (Offset: 0x{0})", (object) tmdFile.Position.ToString("x8").ToUpper()); FireDebug(" Reading Reserved... (Offset: 0x{0})", (object)tmdFile.Position.ToString("x8").ToUpper());
tmdFile.Read(this.reserved, 0, this.reserved.Length); tmdFile.Read(reserved, 0, reserved.Length);
this.fireDebug(" Reading Access Rights... (Offset: 0x{0})", (object) tmdFile.Position.ToString("x8").ToUpper()); FireDebug(" Reading Access Rights... (Offset: 0x{0})", (object)tmdFile.Position.ToString("x8").ToUpper());
tmdFile.Read(buffer, 0, 4); tmdFile.Read(buffer, 0, 4);
this.accessRights = Shared.Swap(BitConverter.ToUInt32(buffer, 0)); accessRights = Shared.Swap(BitConverter.ToUInt32(buffer, 0));
this.fireDebug(" Reading Title Version... (Offset: 0x{0})", (object) tmdFile.Position.ToString("x8").ToUpper()); FireDebug(" Reading Title Version... (Offset: 0x{0})", (object)tmdFile.Position.ToString("x8").ToUpper());
this.fireDebug(" Reading NumOfContents... (Offset: 0x{0})", (object) tmdFile.Position.ToString("x8").ToUpper()); FireDebug(" Reading NumOfContents... (Offset: 0x{0})", (object)tmdFile.Position.ToString("x8").ToUpper());
this.fireDebug(" Reading Boot Index... (Offset: 0x{0})", (object) tmdFile.Position.ToString("x8").ToUpper()); FireDebug(" Reading Boot Index... (Offset: 0x{0})", (object)tmdFile.Position.ToString("x8").ToUpper());
this.fireDebug(" Reading Padding3... (Offset: 0x{0})", (object) tmdFile.Position.ToString("x8").ToUpper()); FireDebug(" Reading Padding3... (Offset: 0x{0})", (object)tmdFile.Position.ToString("x8").ToUpper());
tmdFile.Read(buffer, 0, 8); tmdFile.Read(buffer, 0, 8);
this.titleVersion = Shared.Swap(BitConverter.ToUInt16(buffer, 0)); titleVersion = Shared.Swap(BitConverter.ToUInt16(buffer, 0));
this.numOfContents = Shared.Swap(BitConverter.ToUInt16(buffer, 2)); numOfContents = Shared.Swap(BitConverter.ToUInt16(buffer, 2));
this.bootIndex = Shared.Swap(BitConverter.ToUInt16(buffer, 4)); bootIndex = Shared.Swap(BitConverter.ToUInt16(buffer, 4));
this.padding3 = Shared.Swap(BitConverter.ToUInt16(buffer, 6)); padding3 = Shared.Swap(BitConverter.ToUInt16(buffer, 6));
this.contents = new List<TMD_Content>(); contents = new List<TMD_Content>();
for (int index = 0; index < (int) this.numOfContents; ++index) for (int index = 0; index < numOfContents; ++index)
{ {
this.fireDebug(" Reading Content #{0} of {1}... (Offset: 0x{2})", (object) (index + 1), (object) this.numOfContents, (object) tmdFile.Position.ToString("x8").ToUpper().ToUpper()); FireDebug(" Reading Content #{0} of {1}... (Offset: 0x{2})", index + 1, numOfContents, tmdFile.Position.ToString("x8").ToUpper().ToUpper());
TMD_Content tmdContent = new TMD_Content(); TMD_Content tmdContent = new TMD_Content
tmdContent.Hash = new byte[20]; {
Hash = new byte[20]
};
tmdFile.Read(buffer, 0, 8); tmdFile.Read(buffer, 0, 8);
tmdContent.ContentID = Shared.Swap(BitConverter.ToUInt32(buffer, 0)); tmdContent.ContentID = Shared.Swap(BitConverter.ToUInt32(buffer, 0));
tmdContent.Index = Shared.Swap(BitConverter.ToUInt16(buffer, 4)); tmdContent.Index = Shared.Swap(BitConverter.ToUInt16(buffer, 4));
@ -496,31 +553,36 @@ namespace libWiiSharp
tmdFile.Read(buffer, 0, 8); tmdFile.Read(buffer, 0, 8);
tmdContent.Size = Shared.Swap(BitConverter.ToUInt64(buffer, 0)); tmdContent.Size = Shared.Swap(BitConverter.ToUInt64(buffer, 0));
tmdFile.Read(tmdContent.Hash, 0, tmdContent.Hash.Length); tmdFile.Read(tmdContent.Hash, 0, tmdContent.Hash.Length);
this.contents.Add(tmdContent); contents.Add(tmdContent);
} }
this.fireDebug("Pasing TMD Finished..."); FireDebug("Pasing TMD Finished...");
} }
private string calculateNandBlocks() private string CalculateNandBlocks()
{ {
int num1 = 0; int num1 = 0;
int num2 = 0; int num2 = 0;
for (int index = 0; index < (int) this.numOfContents; ++index) for (int index = 0; index < numOfContents; ++index)
{ {
num2 += (int) this.contents[index].Size; num2 += (int)contents[index].Size;
if (this.contents[index].Type == ContentType.Normal) if (contents[index].Type == ContentType.Normal)
num1 += (int) this.contents[index].Size; {
num1 += (int)contents[index].Size;
} }
int num3 = (int) Math.Ceiling((double) num1 / 131072.0); }
int num4 = (int) Math.Ceiling((double) num2 / 131072.0); int num3 = (int)Math.Ceiling(num1 / 131072.0);
return num3 == num4 ? num4.ToString() : string.Format("{0} - {1}", (object) num3, (object) num4); int num4 = (int)Math.Ceiling(num2 / 131072.0);
return num3 == num4 ? num4.ToString() : string.Format("{0} - {1}", num3, num4);
} }
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

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

769
TPL.cs

File diff suppressed because it is too large Load diff

View file

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

View file

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

View file

@ -16,20 +16,20 @@ namespace libWiiSharp
public uint TextureHeaderOffset public uint TextureHeaderOffset
{ {
get => this.textureHeaderOffset; get => textureHeaderOffset;
set => this.textureHeaderOffset = value; set => textureHeaderOffset = value;
} }
public uint PaletteHeaderOffset public uint PaletteHeaderOffset
{ {
get => this.paletteHeaderOffset; get => paletteHeaderOffset;
set => this.paletteHeaderOffset = value; set => paletteHeaderOffset = value;
} }
public void Write(Stream writeStream) public void Write(Stream writeStream)
{ {
writeStream.Write(BitConverter.GetBytes(Shared.Swap(this.textureHeaderOffset)), 0, 4); writeStream.Write(BitConverter.GetBytes(Shared.Swap(textureHeaderOffset)), 0, 4);
writeStream.Write(BitConverter.GetBytes(Shared.Swap(this.paletteHeaderOffset)), 0, 4); writeStream.Write(BitConverter.GetBytes(Shared.Swap(paletteHeaderOffset)), 0, 4);
} }
} }
} }

View file

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

465
Ticket.cs
View file

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

802
U8.cs

File diff suppressed because it is too large Load diff

View file

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

View file

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

802
WAD.cs

File diff suppressed because it is too large Load diff

139
Wave.cs
View file

@ -18,135 +18,144 @@ namespace libWiiSharp
private bool hasSmpl; private bool hasSmpl;
private bool isDisposed; private bool isDisposed;
public int SampleRate => (int) this.fmt.SampleRate; public int SampleRate => (int)fmt.SampleRate;
public int BitDepth => (int) this.fmt.BitsPerSample; public int BitDepth => fmt.BitsPerSample;
public int NumChannels => (int) this.fmt.NumChannels; public int NumChannels => fmt.NumChannels;
public int NumLoops => !this.hasSmpl ? 0 : (int) this.smpl.NumLoops; public int NumLoops => !hasSmpl ? 0 : (int)smpl.NumLoops;
public int LoopStart => this.NumLoops == 0 ? 0 : (int) this.smpl.Loops[0].LoopStart; public int LoopStart => NumLoops == 0 ? 0 : (int)smpl.Loops[0].LoopStart;
public int NumSamples => (int) ((long) this.data.DataSize / (long) ((int) this.fmt.BitsPerSample / 8) / (long) this.fmt.NumChannels); public int NumSamples => (int)(data.DataSize / (fmt.BitsPerSample / 8) / fmt.NumChannels);
public int DataFormat => (int) this.fmt.AudioFormat; public int DataFormat => (int)fmt.AudioFormat;
public byte[] SampleData => this.data.Data; public byte[] SampleData => 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 int PlayLength => (int)(data.DataSize / fmt.NumChannels / (fmt.BitsPerSample / 8) / fmt.SampleRate);
public Wave(string pathToFile) public Wave(string pathToFile)
{ {
using (FileStream fileStream = new FileStream(pathToFile, FileMode.Open)) using FileStream fileStream = new FileStream(pathToFile, FileMode.Open);
{ using BinaryReader reader = new BinaryReader(fileStream);
using (BinaryReader reader = new BinaryReader((Stream) fileStream)) ParseWave(reader);
this.parseWave(reader);
}
} }
public Wave(Stream wave) => this.parseWave(new BinaryReader(wave)); public Wave(Stream wave)
{
ParseWave(new BinaryReader(wave));
}
public Wave(byte[] waveFile) public Wave(byte[] waveFile)
{ {
using (MemoryStream memoryStream = new MemoryStream(waveFile)) using MemoryStream memoryStream = new MemoryStream(waveFile);
{ using BinaryReader reader = new BinaryReader(memoryStream);
using (BinaryReader reader = new BinaryReader((Stream) memoryStream)) ParseWave(reader);
this.parseWave(reader);
}
} }
public Wave(int numChannels, int bitsPerSample, int sampleRate, byte[] samples) public Wave(int numChannels, int bitsPerSample, int sampleRate, byte[] samples)
{ {
this.fmt.SampleRate = (uint) sampleRate; fmt.SampleRate = (uint)sampleRate;
this.fmt.NumChannels = (ushort) numChannels; fmt.NumChannels = (ushort)numChannels;
this.fmt.BitsPerSample = (ushort) bitsPerSample; fmt.BitsPerSample = (ushort)bitsPerSample;
this.data.Data = samples; data.Data = samples;
} }
~Wave() => this.Dispose(false); ~Wave() => 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.header = (WaveHeader) null; header = null;
this.fmt = (WaveFmtChunk) null; fmt = null;
this.data = (WaveDataChunk) null; data = null;
this.smpl = (WaveSmplChunk) null; smpl = null;
} }
this.isDisposed = true; isDisposed = true;
} }
public void Write(Stream writeStream) => this.writeToStream(new BinaryWriter(writeStream)); public void Write(Stream writeStream)
{
WriteToStream(new BinaryWriter(writeStream));
}
public MemoryStream ToMemoryStream() public MemoryStream ToMemoryStream()
{ {
MemoryStream memoryStream = new MemoryStream(); MemoryStream memoryStream = new MemoryStream();
this.writeToStream(new BinaryWriter((Stream) memoryStream)); WriteToStream(new BinaryWriter(memoryStream));
return memoryStream; return memoryStream;
} }
public byte[] ToByteArray() => this.ToMemoryStream().ToArray(); public byte[] ToByteArray()
{
return ToMemoryStream().ToArray();
}
public void Save(string savePath) public void Save(string savePath)
{ {
using (FileStream fileStream = new FileStream(savePath, FileMode.Create)) using FileStream fileStream = new FileStream(savePath, FileMode.Create);
{ using BinaryWriter writer = new BinaryWriter(fileStream);
using (BinaryWriter writer = new BinaryWriter((Stream) fileStream)) WriteToStream(writer);
this.writeToStream(writer);
}
} }
public void AddLoop(int loopStartSample) public void AddLoop(int loopStartSample)
{ {
this.smpl.AddLoop(loopStartSample, this.NumSamples); smpl.AddLoop(loopStartSample, NumSamples);
this.hasSmpl = true; hasSmpl = true;
} }
public void RemoveLoop() => this.hasSmpl = false; public void RemoveLoop()
{
hasSmpl = false;
}
public void TrimStart(int newStartSample) public void TrimStart(int newStartSample)
{ {
int offset = (int) this.fmt.NumChannels * ((int) this.fmt.BitsPerSample / 8) * newStartSample; int offset = fmt.NumChannels * (fmt.BitsPerSample / 8) * newStartSample;
MemoryStream memoryStream = new MemoryStream(); MemoryStream memoryStream = new MemoryStream();
memoryStream.Write(this.data.Data, offset, this.data.Data.Length - offset); memoryStream.Write(data.Data, offset, data.Data.Length - offset);
this.data.Data = memoryStream.ToArray(); data.Data = memoryStream.ToArray();
memoryStream.Dispose(); memoryStream.Dispose();
} }
private void writeToStream(BinaryWriter writer) 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)
{ {
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; return;
this.smpl.Write(writer);
} }
private void parseWave(BinaryReader reader) smpl.Write(writer);
}
private void ParseWave(BinaryReader reader)
{ {
bool[] flagArray = new bool[3]; bool[] flagArray = new bool[3];
while (reader.BaseStream.Position < reader.BaseStream.Length - 4L) while (reader.BaseStream.Position < reader.BaseStream.Length - 4L)
{ {
uint num1 = Shared.Swap(reader.ReadUInt32()); uint num1 = Shared.Swap(reader.ReadUInt32());
uint num2 = reader.ReadUInt32(); uint num2 = reader.ReadUInt32();
long offset = reader.BaseStream.Position + (long) num2; long offset = reader.BaseStream.Position + num2;
switch (num1) switch (num1)
{ {
case 1380533830: case 1380533830:
try try
{ {
reader.BaseStream.Seek(-8L, SeekOrigin.Current); reader.BaseStream.Seek(-8L, SeekOrigin.Current);
this.header.Read(reader); header.Read(reader);
flagArray[0] = true; flagArray[0] = true;
break; break;
} }
@ -159,7 +168,7 @@ namespace libWiiSharp
try try
{ {
reader.BaseStream.Seek(-8L, SeekOrigin.Current); reader.BaseStream.Seek(-8L, SeekOrigin.Current);
this.data.Read(reader); data.Read(reader);
flagArray[2] = true; flagArray[2] = true;
break; break;
} }
@ -172,7 +181,7 @@ namespace libWiiSharp
try try
{ {
reader.BaseStream.Seek(-8L, SeekOrigin.Current); reader.BaseStream.Seek(-8L, SeekOrigin.Current);
this.fmt.Read(reader); fmt.Read(reader);
flagArray[1] = true; flagArray[1] = true;
break; break;
} }
@ -185,8 +194,8 @@ namespace libWiiSharp
try try
{ {
reader.BaseStream.Seek(-8L, SeekOrigin.Current); reader.BaseStream.Seek(-8L, SeekOrigin.Current);
this.smpl.Read(reader); smpl.Read(reader);
this.hasSmpl = true; hasSmpl = true;
break; break;
} }
catch catch
@ -195,14 +204,18 @@ namespace libWiiSharp
break; break;
} }
default: default:
reader.BaseStream.Seek((long) num2, SeekOrigin.Current); reader.BaseStream.Seek(num2, SeekOrigin.Current);
break; break;
} }
if (flagArray[0] && flagArray[1] && (flagArray[2] && this.hasSmpl)) if (flagArray[0] && flagArray[1] && (flagArray[2] && hasSmpl))
{
break; break;
} }
}
if (!flagArray[0] || !flagArray[1] || !flagArray[2]) if (!flagArray[0] || !flagArray[1] || !flagArray[2])
{
throw new Exception("Couldn't parse Wave file..."); throw new Exception("Couldn't parse Wave file...");
} }
} }
} }
}

View file

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

View file

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

View file

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

View file

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

View file

@ -19,34 +19,34 @@ namespace libWiiSharp
public uint LoopStart public uint LoopStart
{ {
get => this.start; get => start;
set => this.start = value; set => start = value;
} }
public uint LoopEnd public uint LoopEnd
{ {
get => this.end; get => end;
set => this.end = value; set => end = value;
} }
public void Write(BinaryWriter writer) public void Write(BinaryWriter writer)
{ {
writer.Write(this.cuePointId); writer.Write(cuePointId);
writer.Write(this.type); writer.Write(type);
writer.Write(this.start); writer.Write(start);
writer.Write(this.end); writer.Write(end);
writer.Write(this.fraction); writer.Write(fraction);
writer.Write(this.playCount); writer.Write(playCount);
} }
public void Read(BinaryReader reader) public void Read(BinaryReader reader)
{ {
this.cuePointId = reader.ReadUInt32(); cuePointId = reader.ReadUInt32();
this.type = reader.ReadUInt32(); type = reader.ReadUInt32();
this.start = reader.ReadUInt32(); start = reader.ReadUInt32();
this.end = reader.ReadUInt32(); end = reader.ReadUInt32();
this.fraction = reader.ReadUInt32(); fraction = reader.ReadUInt32();
this.playCount = reader.ReadUInt32(); playCount = reader.ReadUInt32();
} }
} }
} }