diff --git a/7zip/Common/CRC.cs b/7zip/Common/CRC.cs index 62bb847..fe51f6c 100644 --- a/7zip/Common/CRC.cs +++ b/7zip/Common/CRC.cs @@ -2,54 +2,54 @@ namespace SevenZip { - class CRC - { - public static readonly uint[] Table; + class CRC + { + public static readonly uint[] Table; - static CRC() - { - Table = new uint[256]; - const uint kPoly = 0xEDB88320; - for (uint i = 0; i < 256; i++) - { - uint r = i; - for (int j = 0; j < 8; j++) - if ((r & 1) != 0) - r = (r >> 1) ^ kPoly; - else - r >>= 1; - Table[i] = r; - } - } + static CRC() + { + Table = new uint[256]; + const uint kPoly = 0xEDB88320; + for (uint i = 0; i < 256; i++) + { + uint r = i; + for (int j = 0; j < 8; j++) + if ((r & 1) != 0) + r = (r >> 1) ^ kPoly; + else + r >>= 1; + Table[i] = r; + } + } - uint _value = 0xFFFFFFFF; + uint _value = 0xFFFFFFFF; - public void Init() { _value = 0xFFFFFFFF; } + public void Init() { _value = 0xFFFFFFFF; } - public void UpdateByte(byte b) - { - _value = Table[(((byte)(_value)) ^ b)] ^ (_value >> 8); - } + public void UpdateByte(byte b) + { + _value = Table[(((byte)(_value)) ^ b)] ^ (_value >> 8); + } - public void Update(byte[] data, uint offset, uint size) - { - for (uint i = 0; i < size; i++) - _value = Table[(((byte)(_value)) ^ data[offset + i])] ^ (_value >> 8); - } + public void Update(byte[] data, uint offset, uint size) + { + for (uint i = 0; i < size; i++) + _value = Table[(((byte)(_value)) ^ data[offset + i])] ^ (_value >> 8); + } - public uint GetDigest() { return _value ^ 0xFFFFFFFF; } + public uint GetDigest() { return _value ^ 0xFFFFFFFF; } - static uint CalculateDigest(byte[] data, uint offset, uint size) - { - CRC crc = new CRC(); - // crc.Init(); - crc.Update(data, offset, size); - return crc.GetDigest(); - } + static uint CalculateDigest(byte[] data, uint offset, uint size) + { + CRC crc = new CRC(); + // crc.Init(); + crc.Update(data, offset, size); + return crc.GetDigest(); + } - static bool VerifyDigest(uint digest, byte[] data, uint offset, uint size) - { - return (CalculateDigest(data, offset, size) == digest); - } - } + static bool VerifyDigest(uint digest, byte[] data, uint offset, uint size) + { + return (CalculateDigest(data, offset, size) == digest); + } + } } diff --git a/7zip/Common/CommandLineParser.cs b/7zip/Common/CommandLineParser.cs index b46f6f2..8c82ed8 100644 --- a/7zip/Common/CommandLineParser.cs +++ b/7zip/Common/CommandLineParser.cs @@ -5,270 +5,270 @@ using System.Collections; namespace SevenZip.CommandLineParser { - public enum SwitchType - { - Simple, - PostMinus, - LimitedPostString, - UnLimitedPostString, - PostChar - } + public enum SwitchType + { + Simple, + PostMinus, + LimitedPostString, + UnLimitedPostString, + PostChar + } - public class SwitchForm - { - public string IDString; - public SwitchType Type; - public bool Multi; - public int MinLen; - public int MaxLen; - public string PostCharSet; + public class SwitchForm + { + public string IDString; + public SwitchType Type; + public bool Multi; + public int MinLen; + public int MaxLen; + public string PostCharSet; - public SwitchForm(string idString, SwitchType type, bool multi, - int minLen, int maxLen, string postCharSet) - { - IDString = idString; - Type = type; - Multi = multi; - MinLen = minLen; - MaxLen = maxLen; - PostCharSet = postCharSet; - } - public SwitchForm(string idString, SwitchType type, bool multi, int minLen): - this(idString, type, multi, minLen, 0, "") - { - } - public SwitchForm(string idString, SwitchType type, bool multi): - this(idString, type, multi, 0) - { - } - } + public SwitchForm(string idString, SwitchType type, bool multi, + int minLen, int maxLen, string postCharSet) + { + IDString = idString; + Type = type; + Multi = multi; + MinLen = minLen; + MaxLen = maxLen; + PostCharSet = postCharSet; + } + public SwitchForm(string idString, SwitchType type, bool multi, int minLen) : + this(idString, type, multi, minLen, 0, "") + { + } + public SwitchForm(string idString, SwitchType type, bool multi) : + this(idString, type, multi, 0) + { + } + } - public class SwitchResult - { - public bool ThereIs; - public bool WithMinus; - public ArrayList PostStrings = new ArrayList(); - public int PostCharIndex; - public SwitchResult() - { - ThereIs = false; - } - } + public class SwitchResult + { + public bool ThereIs; + public bool WithMinus; + public ArrayList PostStrings = new ArrayList(); + public int PostCharIndex; + public SwitchResult() + { + ThereIs = false; + } + } - public class Parser - { - public ArrayList NonSwitchStrings = new ArrayList(); - SwitchResult[] _switches; + public class Parser + { + public ArrayList NonSwitchStrings = new ArrayList(); + SwitchResult[] _switches; - public Parser(int numSwitches) - { - _switches = new SwitchResult[numSwitches]; - for (int i = 0; i < numSwitches; i++) - _switches[i] = new SwitchResult(); - } + public Parser(int numSwitches) + { + _switches = new SwitchResult[numSwitches]; + for (int i = 0; i < numSwitches; i++) + _switches[i] = new SwitchResult(); + } - bool ParseString(string srcString, SwitchForm[] switchForms) - { - int len = srcString.Length; - if (len == 0) - return false; - int pos = 0; - if (!IsItSwitchChar(srcString[pos])) - return false; - while (pos < len) - { - if (IsItSwitchChar(srcString[pos])) - pos++; - const int kNoLen = -1; - int matchedSwitchIndex = 0; - int maxLen = kNoLen; - for (int switchIndex = 0; switchIndex < _switches.Length; switchIndex++) - { - int switchLen = switchForms[switchIndex].IDString.Length; - if (switchLen <= maxLen || pos + switchLen > len) - continue; - if (String.Compare(switchForms[switchIndex].IDString, 0, - srcString, pos, switchLen, true) == 0) - { - matchedSwitchIndex = switchIndex; - maxLen = switchLen; - } - } - if (maxLen == kNoLen) - throw new Exception("maxLen == kNoLen"); - SwitchResult matchedSwitch = _switches[matchedSwitchIndex]; - SwitchForm switchForm = switchForms[matchedSwitchIndex]; - if ((!switchForm.Multi) && matchedSwitch.ThereIs) - throw new Exception("switch must be single"); - matchedSwitch.ThereIs = true; - pos += maxLen; - int tailSize = len - pos; - SwitchType type = switchForm.Type; - switch (type) - { - case SwitchType.PostMinus: - { - if (tailSize == 0) - matchedSwitch.WithMinus = false; - else - { - matchedSwitch.WithMinus = (srcString[pos] == kSwitchMinus); - if (matchedSwitch.WithMinus) - pos++; - } - break; - } - case SwitchType.PostChar: - { - if (tailSize < switchForm.MinLen) - throw new Exception("switch is not full"); - string charSet = switchForm.PostCharSet; - const int kEmptyCharValue = -1; - if (tailSize == 0) - matchedSwitch.PostCharIndex = kEmptyCharValue; - else - { - int index = charSet.IndexOf(srcString[pos]); - if (index < 0) - matchedSwitch.PostCharIndex = kEmptyCharValue; - else - { - matchedSwitch.PostCharIndex = index; - pos++; - } - } - break; - } - case SwitchType.LimitedPostString: - case SwitchType.UnLimitedPostString: - { - int minLen = switchForm.MinLen; - if (tailSize < minLen) - throw new Exception("switch is not full"); - if (type == SwitchType.UnLimitedPostString) - { - matchedSwitch.PostStrings.Add(srcString.Substring(pos)); - return true; - } - String stringSwitch = srcString.Substring(pos, minLen); - pos += minLen; - for (int i = minLen; i < switchForm.MaxLen && pos < len; i++, pos++) - { - char c = srcString[pos]; - if (IsItSwitchChar(c)) - break; - stringSwitch += c; - } - matchedSwitch.PostStrings.Add(stringSwitch); - break; - } - } - } - return true; + bool ParseString(string srcString, SwitchForm[] switchForms) + { + int len = srcString.Length; + if (len == 0) + return false; + int pos = 0; + if (!IsItSwitchChar(srcString[pos])) + return false; + while (pos < len) + { + if (IsItSwitchChar(srcString[pos])) + pos++; + const int kNoLen = -1; + int matchedSwitchIndex = 0; + int maxLen = kNoLen; + for (int switchIndex = 0; switchIndex < _switches.Length; switchIndex++) + { + int switchLen = switchForms[switchIndex].IDString.Length; + if (switchLen <= maxLen || pos + switchLen > len) + continue; + if (String.Compare(switchForms[switchIndex].IDString, 0, + srcString, pos, switchLen, true) == 0) + { + matchedSwitchIndex = switchIndex; + maxLen = switchLen; + } + } + if (maxLen == kNoLen) + throw new Exception("maxLen == kNoLen"); + SwitchResult matchedSwitch = _switches[matchedSwitchIndex]; + SwitchForm switchForm = switchForms[matchedSwitchIndex]; + if ((!switchForm.Multi) && matchedSwitch.ThereIs) + throw new Exception("switch must be single"); + matchedSwitch.ThereIs = true; + pos += maxLen; + int tailSize = len - pos; + SwitchType type = switchForm.Type; + switch (type) + { + case SwitchType.PostMinus: + { + if (tailSize == 0) + matchedSwitch.WithMinus = false; + else + { + matchedSwitch.WithMinus = (srcString[pos] == kSwitchMinus); + if (matchedSwitch.WithMinus) + pos++; + } + break; + } + case SwitchType.PostChar: + { + if (tailSize < switchForm.MinLen) + throw new Exception("switch is not full"); + string charSet = switchForm.PostCharSet; + const int kEmptyCharValue = -1; + if (tailSize == 0) + matchedSwitch.PostCharIndex = kEmptyCharValue; + else + { + int index = charSet.IndexOf(srcString[pos]); + if (index < 0) + matchedSwitch.PostCharIndex = kEmptyCharValue; + else + { + matchedSwitch.PostCharIndex = index; + pos++; + } + } + break; + } + case SwitchType.LimitedPostString: + case SwitchType.UnLimitedPostString: + { + int minLen = switchForm.MinLen; + if (tailSize < minLen) + throw new Exception("switch is not full"); + if (type == SwitchType.UnLimitedPostString) + { + matchedSwitch.PostStrings.Add(srcString.Substring(pos)); + return true; + } + String stringSwitch = srcString.Substring(pos, minLen); + pos += minLen; + for (int i = minLen; i < switchForm.MaxLen && pos < len; i++, pos++) + { + char c = srcString[pos]; + if (IsItSwitchChar(c)) + break; + stringSwitch += c; + } + matchedSwitch.PostStrings.Add(stringSwitch); + break; + } + } + } + return true; - } + } - public void ParseStrings(SwitchForm[] switchForms, string[] commandStrings) - { - int numCommandStrings = commandStrings.Length; - bool stopSwitch = false; - for (int i = 0; i < numCommandStrings; i++) - { - string s = commandStrings[i]; - if (stopSwitch) - NonSwitchStrings.Add(s); - else - if (s == kStopSwitchParsing) - stopSwitch = true; - else - if (!ParseString(s, switchForms)) - NonSwitchStrings.Add(s); - } - } + public void ParseStrings(SwitchForm[] switchForms, string[] commandStrings) + { + int numCommandStrings = commandStrings.Length; + bool stopSwitch = false; + for (int i = 0; i < numCommandStrings; i++) + { + string s = commandStrings[i]; + if (stopSwitch) + NonSwitchStrings.Add(s); + else + if (s == kStopSwitchParsing) + stopSwitch = true; + else + if (!ParseString(s, switchForms)) + NonSwitchStrings.Add(s); + } + } - public SwitchResult this[int index] { get { return _switches[index]; } } + public SwitchResult this[int index] { get { return _switches[index]; } } - public static int ParseCommand(CommandForm[] commandForms, string commandString, - out string postString) - { - for (int i = 0; i < commandForms.Length; i++) - { - string id = commandForms[i].IDString; - if (commandForms[i].PostStringMode) - { - if (commandString.IndexOf(id) == 0) - { - postString = commandString.Substring(id.Length); - return i; - } - } - else - if (commandString == id) - { - postString = ""; - return i; - } - } - postString = ""; - return -1; - } + public static int ParseCommand(CommandForm[] commandForms, string commandString, + out string postString) + { + for (int i = 0; i < commandForms.Length; i++) + { + string id = commandForms[i].IDString; + if (commandForms[i].PostStringMode) + { + if (commandString.IndexOf(id) == 0) + { + postString = commandString.Substring(id.Length); + return i; + } + } + else + if (commandString == id) + { + postString = ""; + return i; + } + } + postString = ""; + return -1; + } - static bool ParseSubCharsCommand(int numForms, CommandSubCharsSet[] forms, - string commandString, ArrayList indices) - { - indices.Clear(); - int numUsedChars = 0; - for (int i = 0; i < numForms; i++) - { - CommandSubCharsSet charsSet = forms[i]; - int currentIndex = -1; - int len = charsSet.Chars.Length; - for (int j = 0; j < len; j++) - { - char c = charsSet.Chars[j]; - int newIndex = commandString.IndexOf(c); - if (newIndex >= 0) - { - if (currentIndex >= 0) - return false; - if (commandString.IndexOf(c, newIndex + 1) >= 0) - return false; - currentIndex = j; - numUsedChars++; - } - } - if (currentIndex == -1 && !charsSet.EmptyAllowed) - return false; - indices.Add(currentIndex); - } - return (numUsedChars == commandString.Length); - } - const char kSwitchID1 = '-'; - const char kSwitchID2 = '/'; + static bool ParseSubCharsCommand(int numForms, CommandSubCharsSet[] forms, + string commandString, ArrayList indices) + { + indices.Clear(); + int numUsedChars = 0; + for (int i = 0; i < numForms; i++) + { + CommandSubCharsSet charsSet = forms[i]; + int currentIndex = -1; + int len = charsSet.Chars.Length; + for (int j = 0; j < len; j++) + { + char c = charsSet.Chars[j]; + int newIndex = commandString.IndexOf(c); + if (newIndex >= 0) + { + if (currentIndex >= 0) + return false; + if (commandString.IndexOf(c, newIndex + 1) >= 0) + return false; + currentIndex = j; + numUsedChars++; + } + } + if (currentIndex == -1 && !charsSet.EmptyAllowed) + return false; + indices.Add(currentIndex); + } + return (numUsedChars == commandString.Length); + } + const char kSwitchID1 = '-'; + const char kSwitchID2 = '/'; - const char kSwitchMinus = '-'; - const string kStopSwitchParsing = "--"; + const char kSwitchMinus = '-'; + const string kStopSwitchParsing = "--"; - static bool IsItSwitchChar(char c) - { - return (c == kSwitchID1 || c == kSwitchID2); - } - } + static bool IsItSwitchChar(char c) + { + return (c == kSwitchID1 || c == kSwitchID2); + } + } - public class CommandForm - { - public string IDString = ""; - public bool PostStringMode = false; - public CommandForm(string idString, bool postStringMode) - { - IDString = idString; - PostStringMode = postStringMode; - } - } + public class CommandForm + { + public string IDString = ""; + public bool PostStringMode = false; + public CommandForm(string idString, bool postStringMode) + { + IDString = idString; + PostStringMode = postStringMode; + } + } - class CommandSubCharsSet - { - public string Chars = ""; - public bool EmptyAllowed = false; - } + class CommandSubCharsSet + { + public string Chars = ""; + public bool EmptyAllowed = false; + } } diff --git a/7zip/Common/InBuffer.cs b/7zip/Common/InBuffer.cs index 9c47c73..773f0a6 100644 --- a/7zip/Common/InBuffer.cs +++ b/7zip/Common/InBuffer.cs @@ -2,71 +2,71 @@ namespace SevenZip.Buffer { - public class InBuffer - { - byte[] m_Buffer; - uint m_Pos; - uint m_Limit; - uint m_BufferSize; - System.IO.Stream m_Stream; - bool m_StreamWasExhausted; - ulong m_ProcessedSize; + public class InBuffer + { + byte[] m_Buffer; + uint m_Pos; + uint m_Limit; + uint m_BufferSize; + System.IO.Stream m_Stream; + bool m_StreamWasExhausted; + ulong m_ProcessedSize; - public InBuffer(uint bufferSize) - { - m_Buffer = new byte[bufferSize]; - m_BufferSize = bufferSize; - } + public InBuffer(uint bufferSize) + { + m_Buffer = new byte[bufferSize]; + m_BufferSize = bufferSize; + } - public void Init(System.IO.Stream stream) - { - m_Stream = stream; - m_ProcessedSize = 0; - m_Limit = 0; - m_Pos = 0; - m_StreamWasExhausted = false; - } + public void Init(System.IO.Stream stream) + { + m_Stream = stream; + m_ProcessedSize = 0; + m_Limit = 0; + m_Pos = 0; + m_StreamWasExhausted = false; + } - public bool ReadBlock() - { - if (m_StreamWasExhausted) - return false; - m_ProcessedSize += m_Pos; - int aNumProcessedBytes = m_Stream.Read(m_Buffer, 0, (int)m_BufferSize); - m_Pos = 0; - m_Limit = (uint)aNumProcessedBytes; - m_StreamWasExhausted = (aNumProcessedBytes == 0); - return (!m_StreamWasExhausted); - } + public bool ReadBlock() + { + if (m_StreamWasExhausted) + return false; + m_ProcessedSize += m_Pos; + int aNumProcessedBytes = m_Stream.Read(m_Buffer, 0, (int)m_BufferSize); + m_Pos = 0; + m_Limit = (uint)aNumProcessedBytes; + m_StreamWasExhausted = (aNumProcessedBytes == 0); + return (!m_StreamWasExhausted); + } - public void ReleaseStream() - { - // m_Stream.Close(); - m_Stream = null; - } + public void ReleaseStream() + { + // m_Stream.Close(); + m_Stream = null; + } - public bool ReadByte(byte b) // check it - { - if (m_Pos >= m_Limit) - if (!ReadBlock()) - return false; - b = m_Buffer[m_Pos++]; - return true; - } + public bool ReadByte(byte b) // check it + { + if (m_Pos >= m_Limit) + if (!ReadBlock()) + return false; + b = m_Buffer[m_Pos++]; + return true; + } - public byte ReadByte() - { - // return (byte)m_Stream.ReadByte(); - if (m_Pos >= m_Limit) - if (!ReadBlock()) - return 0xFF; - return m_Buffer[m_Pos++]; - } + public byte ReadByte() + { + // return (byte)m_Stream.ReadByte(); + if (m_Pos >= m_Limit) + if (!ReadBlock()) + return 0xFF; + return m_Buffer[m_Pos++]; + } - public ulong GetProcessedSize() - { - return m_ProcessedSize + m_Pos; - } - } + public ulong GetProcessedSize() + { + return m_ProcessedSize + m_Pos; + } + } } diff --git a/7zip/Common/OutBuffer.cs b/7zip/Common/OutBuffer.cs index c205aa6..a4378ea 100644 --- a/7zip/Common/OutBuffer.cs +++ b/7zip/Common/OutBuffer.cs @@ -2,46 +2,46 @@ namespace SevenZip.Buffer { - public class OutBuffer - { - byte[] m_Buffer; - uint m_Pos; - uint m_BufferSize; - System.IO.Stream m_Stream; - ulong m_ProcessedSize; + public class OutBuffer + { + byte[] m_Buffer; + uint m_Pos; + uint m_BufferSize; + System.IO.Stream m_Stream; + ulong m_ProcessedSize; - public OutBuffer(uint bufferSize) - { - m_Buffer = new byte[bufferSize]; - m_BufferSize = bufferSize; - } + public OutBuffer(uint bufferSize) + { + m_Buffer = new byte[bufferSize]; + m_BufferSize = bufferSize; + } - public void SetStream(System.IO.Stream stream) { m_Stream = stream; } - public void FlushStream() { m_Stream.Flush(); } - public void CloseStream() { m_Stream.Close(); } - public void ReleaseStream() { m_Stream = null; } + public void SetStream(System.IO.Stream stream) { m_Stream = stream; } + public void FlushStream() { m_Stream.Flush(); } + public void CloseStream() { m_Stream.Close(); } + public void ReleaseStream() { m_Stream = null; } - public void Init() - { - m_ProcessedSize = 0; - m_Pos = 0; - } + public void Init() + { + m_ProcessedSize = 0; + m_Pos = 0; + } - public void WriteByte(byte b) - { - m_Buffer[m_Pos++] = b; - if (m_Pos >= m_BufferSize) - FlushData(); - } + public void WriteByte(byte b) + { + m_Buffer[m_Pos++] = b; + if (m_Pos >= m_BufferSize) + FlushData(); + } - public void FlushData() - { - if (m_Pos == 0) - return; - m_Stream.Write(m_Buffer, 0, (int)m_Pos); - m_Pos = 0; - } + public void FlushData() + { + if (m_Pos == 0) + return; + m_Stream.Write(m_Buffer, 0, (int)m_Pos); + m_Pos = 0; + } - public ulong GetProcessedSize() { return m_ProcessedSize + m_Pos; } - } + public ulong GetProcessedSize() { return m_ProcessedSize + m_Pos; } + } } diff --git a/7zip/Compress/LZ/IMatchFinder.cs b/7zip/Compress/LZ/IMatchFinder.cs index 30fab86..d484fe8 100644 --- a/7zip/Compress/LZ/IMatchFinder.cs +++ b/7zip/Compress/LZ/IMatchFinder.cs @@ -4,21 +4,21 @@ using System; namespace SevenZip.Compression.LZ { - interface IInWindowStream - { - void SetStream(System.IO.Stream inStream); - void Init(); - void ReleaseStream(); - Byte GetIndexByte(Int32 index); - UInt32 GetMatchLen(Int32 index, UInt32 distance, UInt32 limit); - UInt32 GetNumAvailableBytes(); - } + interface IInWindowStream + { + void SetStream(System.IO.Stream inStream); + void Init(); + void ReleaseStream(); + Byte GetIndexByte(Int32 index); + UInt32 GetMatchLen(Int32 index, UInt32 distance, UInt32 limit); + UInt32 GetNumAvailableBytes(); + } - interface IMatchFinder : IInWindowStream - { - void Create(UInt32 historySize, UInt32 keepAddBufferBefore, - UInt32 matchMaxLen, UInt32 keepAddBufferAfter); - UInt32 GetMatches(UInt32[] distances); - void Skip(UInt32 num); - } + interface IMatchFinder : IInWindowStream + { + void Create(UInt32 historySize, UInt32 keepAddBufferBefore, + UInt32 matchMaxLen, UInt32 keepAddBufferAfter); + UInt32 GetMatches(UInt32[] distances); + void Skip(UInt32 num); + } } diff --git a/7zip/Compress/LZ/LzBinTree.cs b/7zip/Compress/LZ/LzBinTree.cs index 7a9ca20..dfc09a6 100644 --- a/7zip/Compress/LZ/LzBinTree.cs +++ b/7zip/Compress/LZ/LzBinTree.cs @@ -4,364 +4,364 @@ using System; namespace SevenZip.Compression.LZ { - public class BinTree : InWindow, IMatchFinder - { - UInt32 _cyclicBufferPos; - UInt32 _cyclicBufferSize = 0; - UInt32 _matchMaxLen; + public class BinTree : InWindow, IMatchFinder + { + UInt32 _cyclicBufferPos; + UInt32 _cyclicBufferSize = 0; + UInt32 _matchMaxLen; - UInt32[] _son; - UInt32[] _hash; + UInt32[] _son; + UInt32[] _hash; - UInt32 _cutValue = 0xFF; - UInt32 _hashMask; - UInt32 _hashSizeSum = 0; + UInt32 _cutValue = 0xFF; + UInt32 _hashMask; + UInt32 _hashSizeSum = 0; - bool HASH_ARRAY = true; + bool HASH_ARRAY = true; - const UInt32 kHash2Size = 1 << 10; - const UInt32 kHash3Size = 1 << 16; - const UInt32 kBT2HashSize = 1 << 16; - const UInt32 kStartMaxLen = 1; - const UInt32 kHash3Offset = kHash2Size; - const UInt32 kEmptyHashValue = 0; - const UInt32 kMaxValForNormalize = ((UInt32)1 << 31) - 1; - - UInt32 kNumHashDirectBytes = 0; - UInt32 kMinMatchCheck = 4; - UInt32 kFixHashSize = kHash2Size + kHash3Size; - - public void SetType(int numHashBytes) - { - HASH_ARRAY = (numHashBytes > 2); - if (HASH_ARRAY) - { - kNumHashDirectBytes = 0; - kMinMatchCheck = 4; - kFixHashSize = kHash2Size + kHash3Size; - } - else - { - kNumHashDirectBytes = 2; - kMinMatchCheck = 2 + 1; - kFixHashSize = 0; - } - } + const UInt32 kHash2Size = 1 << 10; + const UInt32 kHash3Size = 1 << 16; + const UInt32 kBT2HashSize = 1 << 16; + const UInt32 kStartMaxLen = 1; + const UInt32 kHash3Offset = kHash2Size; + const UInt32 kEmptyHashValue = 0; + const UInt32 kMaxValForNormalize = ((UInt32)1 << 31) - 1; - public new void SetStream(System.IO.Stream stream) { base.SetStream(stream); } - public new void ReleaseStream() { base.ReleaseStream(); } - - public new void Init() - { - base.Init(); - for (UInt32 i = 0; i < _hashSizeSum; i++) - _hash[i] = kEmptyHashValue; - _cyclicBufferPos = 0; - ReduceOffsets(-1); - } + UInt32 kNumHashDirectBytes = 0; + UInt32 kMinMatchCheck = 4; + UInt32 kFixHashSize = kHash2Size + kHash3Size; - public new void MovePos() - { - if (++_cyclicBufferPos >= _cyclicBufferSize) - _cyclicBufferPos = 0; - base.MovePos(); - if (_pos == kMaxValForNormalize) - Normalize(); - } + public void SetType(int numHashBytes) + { + HASH_ARRAY = (numHashBytes > 2); + if (HASH_ARRAY) + { + kNumHashDirectBytes = 0; + kMinMatchCheck = 4; + kFixHashSize = kHash2Size + kHash3Size; + } + else + { + kNumHashDirectBytes = 2; + kMinMatchCheck = 2 + 1; + kFixHashSize = 0; + } + } - public new Byte GetIndexByte(Int32 index) { return base.GetIndexByte(index); } + public new void SetStream(System.IO.Stream stream) { base.SetStream(stream); } + public new void ReleaseStream() { base.ReleaseStream(); } - public new UInt32 GetMatchLen(Int32 index, UInt32 distance, UInt32 limit) - { return base.GetMatchLen(index, distance, limit); } + public new void Init() + { + base.Init(); + for (UInt32 i = 0; i < _hashSizeSum; i++) + _hash[i] = kEmptyHashValue; + _cyclicBufferPos = 0; + ReduceOffsets(-1); + } - public new UInt32 GetNumAvailableBytes() { return base.GetNumAvailableBytes(); } + public new void MovePos() + { + if (++_cyclicBufferPos >= _cyclicBufferSize) + _cyclicBufferPos = 0; + base.MovePos(); + if (_pos == kMaxValForNormalize) + Normalize(); + } - public void Create(UInt32 historySize, UInt32 keepAddBufferBefore, - UInt32 matchMaxLen, UInt32 keepAddBufferAfter) - { - if (historySize > kMaxValForNormalize - 256) - throw new Exception(); - _cutValue = 16 + (matchMaxLen >> 1); - - UInt32 windowReservSize = (historySize + keepAddBufferBefore + - matchMaxLen + keepAddBufferAfter) / 2 + 256; + public new Byte GetIndexByte(Int32 index) { return base.GetIndexByte(index); } - base.Create(historySize + keepAddBufferBefore, matchMaxLen + keepAddBufferAfter, windowReservSize); + public new UInt32 GetMatchLen(Int32 index, UInt32 distance, UInt32 limit) + { return base.GetMatchLen(index, distance, limit); } - _matchMaxLen = matchMaxLen; + public new UInt32 GetNumAvailableBytes() { return base.GetNumAvailableBytes(); } - UInt32 cyclicBufferSize = historySize + 1; - if (_cyclicBufferSize != cyclicBufferSize) - _son = new UInt32[(_cyclicBufferSize = cyclicBufferSize) * 2]; + public void Create(UInt32 historySize, UInt32 keepAddBufferBefore, + UInt32 matchMaxLen, UInt32 keepAddBufferAfter) + { + if (historySize > kMaxValForNormalize - 256) + throw new Exception(); + _cutValue = 16 + (matchMaxLen >> 1); - UInt32 hs = kBT2HashSize; + UInt32 windowReservSize = (historySize + keepAddBufferBefore + + matchMaxLen + keepAddBufferAfter) / 2 + 256; - if (HASH_ARRAY) - { - hs = historySize - 1; - hs |= (hs >> 1); - hs |= (hs >> 2); - hs |= (hs >> 4); - hs |= (hs >> 8); - hs >>= 1; - hs |= 0xFFFF; - if (hs > (1 << 24)) - hs >>= 1; - _hashMask = hs; - hs++; - hs += kFixHashSize; - } - if (hs != _hashSizeSum) - _hash = new UInt32[_hashSizeSum = hs]; - } + base.Create(historySize + keepAddBufferBefore, matchMaxLen + keepAddBufferAfter, windowReservSize); - public UInt32 GetMatches(UInt32[] distances) - { - UInt32 lenLimit; - if (_pos + _matchMaxLen <= _streamPos) - lenLimit = _matchMaxLen; - else - { - lenLimit = _streamPos - _pos; - if (lenLimit < kMinMatchCheck) - { - MovePos(); - return 0; - } - } + _matchMaxLen = matchMaxLen; - UInt32 offset = 0; - UInt32 matchMinPos = (_pos > _cyclicBufferSize) ? (_pos - _cyclicBufferSize) : 0; - UInt32 cur = _bufferOffset + _pos; - UInt32 maxLen = kStartMaxLen; // to avoid items for len < hashSize; - UInt32 hashValue, hash2Value = 0, hash3Value = 0; + UInt32 cyclicBufferSize = historySize + 1; + if (_cyclicBufferSize != cyclicBufferSize) + _son = new UInt32[(_cyclicBufferSize = cyclicBufferSize) * 2]; - if (HASH_ARRAY) - { - UInt32 temp = CRC.Table[_bufferBase[cur]] ^ _bufferBase[cur + 1]; - hash2Value = temp & (kHash2Size - 1); - temp ^= ((UInt32)(_bufferBase[cur + 2]) << 8); - hash3Value = temp & (kHash3Size - 1); - hashValue = (temp ^ (CRC.Table[_bufferBase[cur + 3]] << 5)) & _hashMask; - } - else - hashValue = _bufferBase[cur] ^ ((UInt32)(_bufferBase[cur + 1]) << 8); + UInt32 hs = kBT2HashSize; - UInt32 curMatch = _hash[kFixHashSize + hashValue]; - if (HASH_ARRAY) - { - UInt32 curMatch2 = _hash[hash2Value]; - UInt32 curMatch3 = _hash[kHash3Offset + hash3Value]; - _hash[hash2Value] = _pos; - _hash[kHash3Offset + hash3Value] = _pos; - if (curMatch2 > matchMinPos) - if (_bufferBase[_bufferOffset + curMatch2] == _bufferBase[cur]) - { - distances[offset++] = maxLen = 2; - distances[offset++] = _pos - curMatch2 - 1; - } - if (curMatch3 > matchMinPos) - if (_bufferBase[_bufferOffset + curMatch3] == _bufferBase[cur]) - { - if (curMatch3 == curMatch2) - offset -= 2; - distances[offset++] = maxLen = 3; - distances[offset++] = _pos - curMatch3 - 1; - curMatch2 = curMatch3; - } - if (offset != 0 && curMatch2 == curMatch) - { - offset -= 2; - maxLen = kStartMaxLen; - } - } + if (HASH_ARRAY) + { + hs = historySize - 1; + hs |= (hs >> 1); + hs |= (hs >> 2); + hs |= (hs >> 4); + hs |= (hs >> 8); + hs >>= 1; + hs |= 0xFFFF; + if (hs > (1 << 24)) + hs >>= 1; + _hashMask = hs; + hs++; + hs += kFixHashSize; + } + if (hs != _hashSizeSum) + _hash = new UInt32[_hashSizeSum = hs]; + } - _hash[kFixHashSize + hashValue] = _pos; + public UInt32 GetMatches(UInt32[] distances) + { + UInt32 lenLimit; + if (_pos + _matchMaxLen <= _streamPos) + lenLimit = _matchMaxLen; + else + { + lenLimit = _streamPos - _pos; + if (lenLimit < kMinMatchCheck) + { + MovePos(); + return 0; + } + } - UInt32 ptr0 = (_cyclicBufferPos << 1) + 1; - UInt32 ptr1 = (_cyclicBufferPos << 1); + UInt32 offset = 0; + UInt32 matchMinPos = (_pos > _cyclicBufferSize) ? (_pos - _cyclicBufferSize) : 0; + UInt32 cur = _bufferOffset + _pos; + UInt32 maxLen = kStartMaxLen; // to avoid items for len < hashSize; + UInt32 hashValue, hash2Value = 0, hash3Value = 0; - UInt32 len0, len1; - len0 = len1 = kNumHashDirectBytes; - - if (kNumHashDirectBytes != 0) - { - if (curMatch > matchMinPos) - { - if (_bufferBase[_bufferOffset + curMatch + kNumHashDirectBytes] != - _bufferBase[cur + kNumHashDirectBytes]) - { - distances[offset++] = maxLen = kNumHashDirectBytes; - distances[offset++] = _pos - curMatch - 1; - } - } - } - - UInt32 count = _cutValue; - - while(true) - { - if(curMatch <= matchMinPos || count-- == 0) - { - _son[ptr0] = _son[ptr1] = kEmptyHashValue; - break; - } - UInt32 delta = _pos - curMatch; - UInt32 cyclicPos = ((delta <= _cyclicBufferPos) ? - (_cyclicBufferPos - delta) : - (_cyclicBufferPos - delta + _cyclicBufferSize)) << 1; + if (HASH_ARRAY) + { + UInt32 temp = CRC.Table[_bufferBase[cur]] ^ _bufferBase[cur + 1]; + hash2Value = temp & (kHash2Size - 1); + temp ^= ((UInt32)(_bufferBase[cur + 2]) << 8); + hash3Value = temp & (kHash3Size - 1); + hashValue = (temp ^ (CRC.Table[_bufferBase[cur + 3]] << 5)) & _hashMask; + } + else + hashValue = _bufferBase[cur] ^ ((UInt32)(_bufferBase[cur + 1]) << 8); - UInt32 pby1 = _bufferOffset + curMatch; - UInt32 len = Math.Min(len0, len1); - if (_bufferBase[pby1 + len] == _bufferBase[cur + len]) - { - while(++len != lenLimit) - if (_bufferBase[pby1 + len] != _bufferBase[cur + len]) - break; - if (maxLen < len) - { - distances[offset++] = maxLen = len; - distances[offset++] = delta - 1; - if (len == lenLimit) - { - _son[ptr1] = _son[cyclicPos]; - _son[ptr0] = _son[cyclicPos + 1]; - break; - } - } - } - if (_bufferBase[pby1 + len] < _bufferBase[cur + len]) - { - _son[ptr1] = curMatch; - ptr1 = cyclicPos + 1; - curMatch = _son[ptr1]; - len1 = len; - } - else - { - _son[ptr0] = curMatch; - ptr0 = cyclicPos; - curMatch = _son[ptr0]; - len0 = len; - } - } - MovePos(); - return offset; - } + UInt32 curMatch = _hash[kFixHashSize + hashValue]; + if (HASH_ARRAY) + { + UInt32 curMatch2 = _hash[hash2Value]; + UInt32 curMatch3 = _hash[kHash3Offset + hash3Value]; + _hash[hash2Value] = _pos; + _hash[kHash3Offset + hash3Value] = _pos; + if (curMatch2 > matchMinPos) + if (_bufferBase[_bufferOffset + curMatch2] == _bufferBase[cur]) + { + distances[offset++] = maxLen = 2; + distances[offset++] = _pos - curMatch2 - 1; + } + if (curMatch3 > matchMinPos) + if (_bufferBase[_bufferOffset + curMatch3] == _bufferBase[cur]) + { + if (curMatch3 == curMatch2) + offset -= 2; + distances[offset++] = maxLen = 3; + distances[offset++] = _pos - curMatch3 - 1; + curMatch2 = curMatch3; + } + if (offset != 0 && curMatch2 == curMatch) + { + offset -= 2; + maxLen = kStartMaxLen; + } + } - public void Skip(UInt32 num) - { - do - { - UInt32 lenLimit; - if (_pos + _matchMaxLen <= _streamPos) - lenLimit = _matchMaxLen; - else - { - lenLimit = _streamPos - _pos; - if (lenLimit < kMinMatchCheck) - { - MovePos(); - continue; - } - } + _hash[kFixHashSize + hashValue] = _pos; - UInt32 matchMinPos = (_pos > _cyclicBufferSize) ? (_pos - _cyclicBufferSize) : 0; - UInt32 cur = _bufferOffset + _pos; + UInt32 ptr0 = (_cyclicBufferPos << 1) + 1; + UInt32 ptr1 = (_cyclicBufferPos << 1); - UInt32 hashValue; + UInt32 len0, len1; + len0 = len1 = kNumHashDirectBytes; - if (HASH_ARRAY) - { - UInt32 temp = CRC.Table[_bufferBase[cur]] ^ _bufferBase[cur + 1]; - UInt32 hash2Value = temp & (kHash2Size - 1); - _hash[hash2Value] = _pos; - temp ^= ((UInt32)(_bufferBase[cur + 2]) << 8); - UInt32 hash3Value = temp & (kHash3Size - 1); - _hash[kHash3Offset + hash3Value] = _pos; - hashValue = (temp ^ (CRC.Table[_bufferBase[cur + 3]] << 5)) & _hashMask; - } - else - hashValue = _bufferBase[cur] ^ ((UInt32)(_bufferBase[cur + 1]) << 8); + if (kNumHashDirectBytes != 0) + { + if (curMatch > matchMinPos) + { + if (_bufferBase[_bufferOffset + curMatch + kNumHashDirectBytes] != + _bufferBase[cur + kNumHashDirectBytes]) + { + distances[offset++] = maxLen = kNumHashDirectBytes; + distances[offset++] = _pos - curMatch - 1; + } + } + } - UInt32 curMatch = _hash[kFixHashSize + hashValue]; - _hash[kFixHashSize + hashValue] = _pos; + UInt32 count = _cutValue; - UInt32 ptr0 = (_cyclicBufferPos << 1) + 1; - UInt32 ptr1 = (_cyclicBufferPos << 1); + while (true) + { + if (curMatch <= matchMinPos || count-- == 0) + { + _son[ptr0] = _son[ptr1] = kEmptyHashValue; + break; + } + UInt32 delta = _pos - curMatch; + UInt32 cyclicPos = ((delta <= _cyclicBufferPos) ? + (_cyclicBufferPos - delta) : + (_cyclicBufferPos - delta + _cyclicBufferSize)) << 1; - UInt32 len0, len1; - len0 = len1 = kNumHashDirectBytes; + UInt32 pby1 = _bufferOffset + curMatch; + UInt32 len = Math.Min(len0, len1); + if (_bufferBase[pby1 + len] == _bufferBase[cur + len]) + { + while (++len != lenLimit) + if (_bufferBase[pby1 + len] != _bufferBase[cur + len]) + break; + if (maxLen < len) + { + distances[offset++] = maxLen = len; + distances[offset++] = delta - 1; + if (len == lenLimit) + { + _son[ptr1] = _son[cyclicPos]; + _son[ptr0] = _son[cyclicPos + 1]; + break; + } + } + } + if (_bufferBase[pby1 + len] < _bufferBase[cur + len]) + { + _son[ptr1] = curMatch; + ptr1 = cyclicPos + 1; + curMatch = _son[ptr1]; + len1 = len; + } + else + { + _son[ptr0] = curMatch; + ptr0 = cyclicPos; + curMatch = _son[ptr0]; + len0 = len; + } + } + MovePos(); + return offset; + } - UInt32 count = _cutValue; - while (true) - { - if (curMatch <= matchMinPos || count-- == 0) - { - _son[ptr0] = _son[ptr1] = kEmptyHashValue; - break; - } + public void Skip(UInt32 num) + { + do + { + UInt32 lenLimit; + if (_pos + _matchMaxLen <= _streamPos) + lenLimit = _matchMaxLen; + else + { + lenLimit = _streamPos - _pos; + if (lenLimit < kMinMatchCheck) + { + MovePos(); + continue; + } + } - UInt32 delta = _pos - curMatch; - UInt32 cyclicPos = ((delta <= _cyclicBufferPos) ? - (_cyclicBufferPos - delta) : - (_cyclicBufferPos - delta + _cyclicBufferSize)) << 1; + UInt32 matchMinPos = (_pos > _cyclicBufferSize) ? (_pos - _cyclicBufferSize) : 0; + UInt32 cur = _bufferOffset + _pos; - UInt32 pby1 = _bufferOffset + curMatch; - UInt32 len = Math.Min(len0, len1); - if (_bufferBase[pby1 + len] == _bufferBase[cur + len]) - { - while (++len != lenLimit) - if (_bufferBase[pby1 + len] != _bufferBase[cur + len]) - break; - if (len == lenLimit) - { - _son[ptr1] = _son[cyclicPos]; - _son[ptr0] = _son[cyclicPos + 1]; - break; - } - } - if (_bufferBase[pby1 + len] < _bufferBase[cur + len]) - { - _son[ptr1] = curMatch; - ptr1 = cyclicPos + 1; - curMatch = _son[ptr1]; - len1 = len; - } - else - { - _son[ptr0] = curMatch; - ptr0 = cyclicPos; - curMatch = _son[ptr0]; - len0 = len; - } - } - MovePos(); - } - while (--num != 0); - } + UInt32 hashValue; - void NormalizeLinks(UInt32[] items, UInt32 numItems, UInt32 subValue) - { - for (UInt32 i = 0; i < numItems; i++) - { - UInt32 value = items[i]; - if (value <= subValue) - value = kEmptyHashValue; - else - value -= subValue; - items[i] = value; - } - } + if (HASH_ARRAY) + { + UInt32 temp = CRC.Table[_bufferBase[cur]] ^ _bufferBase[cur + 1]; + UInt32 hash2Value = temp & (kHash2Size - 1); + _hash[hash2Value] = _pos; + temp ^= ((UInt32)(_bufferBase[cur + 2]) << 8); + UInt32 hash3Value = temp & (kHash3Size - 1); + _hash[kHash3Offset + hash3Value] = _pos; + hashValue = (temp ^ (CRC.Table[_bufferBase[cur + 3]] << 5)) & _hashMask; + } + else + hashValue = _bufferBase[cur] ^ ((UInt32)(_bufferBase[cur + 1]) << 8); - void Normalize() - { - UInt32 subValue = _pos - _cyclicBufferSize; - NormalizeLinks(_son, _cyclicBufferSize * 2, subValue); - NormalizeLinks(_hash, _hashSizeSum, subValue); - ReduceOffsets((Int32)subValue); - } + UInt32 curMatch = _hash[kFixHashSize + hashValue]; + _hash[kFixHashSize + hashValue] = _pos; - public void SetCutValue(UInt32 cutValue) { _cutValue = cutValue; } - } + UInt32 ptr0 = (_cyclicBufferPos << 1) + 1; + UInt32 ptr1 = (_cyclicBufferPos << 1); + + UInt32 len0, len1; + len0 = len1 = kNumHashDirectBytes; + + UInt32 count = _cutValue; + while (true) + { + if (curMatch <= matchMinPos || count-- == 0) + { + _son[ptr0] = _son[ptr1] = kEmptyHashValue; + break; + } + + UInt32 delta = _pos - curMatch; + UInt32 cyclicPos = ((delta <= _cyclicBufferPos) ? + (_cyclicBufferPos - delta) : + (_cyclicBufferPos - delta + _cyclicBufferSize)) << 1; + + UInt32 pby1 = _bufferOffset + curMatch; + UInt32 len = Math.Min(len0, len1); + if (_bufferBase[pby1 + len] == _bufferBase[cur + len]) + { + while (++len != lenLimit) + if (_bufferBase[pby1 + len] != _bufferBase[cur + len]) + break; + if (len == lenLimit) + { + _son[ptr1] = _son[cyclicPos]; + _son[ptr0] = _son[cyclicPos + 1]; + break; + } + } + if (_bufferBase[pby1 + len] < _bufferBase[cur + len]) + { + _son[ptr1] = curMatch; + ptr1 = cyclicPos + 1; + curMatch = _son[ptr1]; + len1 = len; + } + else + { + _son[ptr0] = curMatch; + ptr0 = cyclicPos; + curMatch = _son[ptr0]; + len0 = len; + } + } + MovePos(); + } + while (--num != 0); + } + + void NormalizeLinks(UInt32[] items, UInt32 numItems, UInt32 subValue) + { + for (UInt32 i = 0; i < numItems; i++) + { + UInt32 value = items[i]; + if (value <= subValue) + value = kEmptyHashValue; + else + value -= subValue; + items[i] = value; + } + } + + void Normalize() + { + UInt32 subValue = _pos - _cyclicBufferSize; + NormalizeLinks(_son, _cyclicBufferSize * 2, subValue); + NormalizeLinks(_hash, _hashSizeSum, subValue); + ReduceOffsets((Int32)subValue); + } + + public void SetCutValue(UInt32 cutValue) { _cutValue = cutValue; } + } } diff --git a/7zip/Compress/LZ/LzInWindow.cs b/7zip/Compress/LZ/LzInWindow.cs index f1974ce..e444c9c 100644 --- a/7zip/Compress/LZ/LzInWindow.cs +++ b/7zip/Compress/LZ/LzInWindow.cs @@ -4,129 +4,129 @@ using System; namespace SevenZip.Compression.LZ { - public class InWindow - { - public Byte[] _bufferBase = null; // pointer to buffer with data - System.IO.Stream _stream; - UInt32 _posLimit; // offset (from _buffer) of first byte when new block reading must be done - bool _streamEndWasReached; // if (true) then _streamPos shows real end of stream + public class InWindow + { + public Byte[] _bufferBase = null; // pointer to buffer with data + System.IO.Stream _stream; + UInt32 _posLimit; // offset (from _buffer) of first byte when new block reading must be done + bool _streamEndWasReached; // if (true) then _streamPos shows real end of stream - UInt32 _pointerToLastSafePosition; + UInt32 _pointerToLastSafePosition; - public UInt32 _bufferOffset; + public UInt32 _bufferOffset; - public UInt32 _blockSize; // Size of Allocated memory block - public UInt32 _pos; // offset (from _buffer) of curent byte - UInt32 _keepSizeBefore; // how many BYTEs must be kept in buffer before _pos - UInt32 _keepSizeAfter; // how many BYTEs must be kept buffer after _pos - public UInt32 _streamPos; // offset (from _buffer) of first not read byte from Stream + public UInt32 _blockSize; // Size of Allocated memory block + public UInt32 _pos; // offset (from _buffer) of curent byte + UInt32 _keepSizeBefore; // how many BYTEs must be kept in buffer before _pos + UInt32 _keepSizeAfter; // how many BYTEs must be kept buffer after _pos + public UInt32 _streamPos; // offset (from _buffer) of first not read byte from Stream - public void MoveBlock() - { - UInt32 offset = (UInt32)(_bufferOffset) + _pos - _keepSizeBefore; - // we need one additional byte, since MovePos moves on 1 byte. - if (offset > 0) - offset--; - - UInt32 numBytes = (UInt32)(_bufferOffset) + _streamPos - offset; + public void MoveBlock() + { + UInt32 offset = (UInt32)(_bufferOffset) + _pos - _keepSizeBefore; + // we need one additional byte, since MovePos moves on 1 byte. + if (offset > 0) + offset--; - // check negative offset ???? - for (UInt32 i = 0; i < numBytes; i++) - _bufferBase[i] = _bufferBase[offset + i]; - _bufferOffset -= offset; - } + UInt32 numBytes = (UInt32)(_bufferOffset) + _streamPos - offset; - public virtual void ReadBlock() - { - if (_streamEndWasReached) - return; - while (true) - { - int size = (int)((0 - _bufferOffset) + _blockSize - _streamPos); - if (size == 0) - return; - int numReadBytes = _stream.Read(_bufferBase, (int)(_bufferOffset + _streamPos), size); - if (numReadBytes == 0) - { - _posLimit = _streamPos; - UInt32 pointerToPostion = _bufferOffset + _posLimit; - if (pointerToPostion > _pointerToLastSafePosition) - _posLimit = (UInt32)(_pointerToLastSafePosition - _bufferOffset); + // check negative offset ???? + for (UInt32 i = 0; i < numBytes; i++) + _bufferBase[i] = _bufferBase[offset + i]; + _bufferOffset -= offset; + } - _streamEndWasReached = true; - return; - } - _streamPos += (UInt32)numReadBytes; - if (_streamPos >= _pos + _keepSizeAfter) - _posLimit = _streamPos - _keepSizeAfter; - } - } + public virtual void ReadBlock() + { + if (_streamEndWasReached) + return; + while (true) + { + int size = (int)((0 - _bufferOffset) + _blockSize - _streamPos); + if (size == 0) + return; + int numReadBytes = _stream.Read(_bufferBase, (int)(_bufferOffset + _streamPos), size); + if (numReadBytes == 0) + { + _posLimit = _streamPos; + UInt32 pointerToPostion = _bufferOffset + _posLimit; + if (pointerToPostion > _pointerToLastSafePosition) + _posLimit = (UInt32)(_pointerToLastSafePosition - _bufferOffset); - void Free() { _bufferBase = null; } + _streamEndWasReached = true; + return; + } + _streamPos += (UInt32)numReadBytes; + if (_streamPos >= _pos + _keepSizeAfter) + _posLimit = _streamPos - _keepSizeAfter; + } + } - public void Create(UInt32 keepSizeBefore, UInt32 keepSizeAfter, UInt32 keepSizeReserv) - { - _keepSizeBefore = keepSizeBefore; - _keepSizeAfter = keepSizeAfter; - UInt32 blockSize = keepSizeBefore + keepSizeAfter + keepSizeReserv; - if (_bufferBase == null || _blockSize != blockSize) - { - Free(); - _blockSize = blockSize; - _bufferBase = new Byte[_blockSize]; - } - _pointerToLastSafePosition = _blockSize - keepSizeAfter; - } + void Free() { _bufferBase = null; } - public void SetStream(System.IO.Stream stream) { _stream = stream; } - public void ReleaseStream() { _stream = null; } + public void Create(UInt32 keepSizeBefore, UInt32 keepSizeAfter, UInt32 keepSizeReserv) + { + _keepSizeBefore = keepSizeBefore; + _keepSizeAfter = keepSizeAfter; + UInt32 blockSize = keepSizeBefore + keepSizeAfter + keepSizeReserv; + if (_bufferBase == null || _blockSize != blockSize) + { + Free(); + _blockSize = blockSize; + _bufferBase = new Byte[_blockSize]; + } + _pointerToLastSafePosition = _blockSize - keepSizeAfter; + } - public void Init() - { - _bufferOffset = 0; - _pos = 0; - _streamPos = 0; - _streamEndWasReached = false; - ReadBlock(); - } + public void SetStream(System.IO.Stream stream) { _stream = stream; } + public void ReleaseStream() { _stream = null; } - public void MovePos() - { - _pos++; - if (_pos > _posLimit) - { - UInt32 pointerToPostion = _bufferOffset + _pos; - if (pointerToPostion > _pointerToLastSafePosition) - MoveBlock(); - ReadBlock(); - } - } + public void Init() + { + _bufferOffset = 0; + _pos = 0; + _streamPos = 0; + _streamEndWasReached = false; + ReadBlock(); + } - public Byte GetIndexByte(Int32 index) { return _bufferBase[_bufferOffset + _pos + index]; } + public void MovePos() + { + _pos++; + if (_pos > _posLimit) + { + UInt32 pointerToPostion = _bufferOffset + _pos; + if (pointerToPostion > _pointerToLastSafePosition) + MoveBlock(); + ReadBlock(); + } + } - // index + limit have not to exceed _keepSizeAfter; - public UInt32 GetMatchLen(Int32 index, UInt32 distance, UInt32 limit) - { - if (_streamEndWasReached) - if ((_pos + index) + limit > _streamPos) - limit = _streamPos - (UInt32)(_pos + index); - distance++; - // Byte *pby = _buffer + (size_t)_pos + index; - UInt32 pby = _bufferOffset + _pos + (UInt32)index; + public Byte GetIndexByte(Int32 index) { return _bufferBase[_bufferOffset + _pos + index]; } - UInt32 i; - for (i = 0; i < limit && _bufferBase[pby + i] == _bufferBase[pby + i - distance]; i++); - return i; - } + // index + limit have not to exceed _keepSizeAfter; + public UInt32 GetMatchLen(Int32 index, UInt32 distance, UInt32 limit) + { + if (_streamEndWasReached) + if ((_pos + index) + limit > _streamPos) + limit = _streamPos - (UInt32)(_pos + index); + distance++; + // Byte *pby = _buffer + (size_t)_pos + index; + UInt32 pby = _bufferOffset + _pos + (UInt32)index; - public UInt32 GetNumAvailableBytes() { return _streamPos - _pos; } + UInt32 i; + for (i = 0; i < limit && _bufferBase[pby + i] == _bufferBase[pby + i - distance]; i++) ; + return i; + } - public void ReduceOffsets(Int32 subValue) - { - _bufferOffset += (UInt32)subValue; - _posLimit -= (UInt32)subValue; - _pos -= (UInt32)subValue; - _streamPos -= (UInt32)subValue; - } - } + public UInt32 GetNumAvailableBytes() { return _streamPos - _pos; } + + public void ReduceOffsets(Int32 subValue) + { + _bufferOffset += (UInt32)subValue; + _posLimit -= (UInt32)subValue; + _pos -= (UInt32)subValue; + _streamPos -= (UInt32)subValue; + } + } } diff --git a/7zip/Compress/LZ/LzOutWindow.cs b/7zip/Compress/LZ/LzOutWindow.cs index 84914f0..23e3b67 100644 --- a/7zip/Compress/LZ/LzOutWindow.cs +++ b/7zip/Compress/LZ/LzOutWindow.cs @@ -2,109 +2,109 @@ namespace SevenZip.Compression.LZ { - public class OutWindow - { - byte[] _buffer = null; - uint _pos; - uint _windowSize = 0; - uint _streamPos; - System.IO.Stream _stream; + public class OutWindow + { + byte[] _buffer = null; + uint _pos; + uint _windowSize = 0; + uint _streamPos; + System.IO.Stream _stream; - public uint TrainSize = 0; + public uint TrainSize = 0; - public void Create(uint windowSize) - { - if (_windowSize != windowSize) - { - // System.GC.Collect(); - _buffer = new byte[windowSize]; - } - _windowSize = windowSize; - _pos = 0; - _streamPos = 0; - } + public void Create(uint windowSize) + { + if (_windowSize != windowSize) + { + // System.GC.Collect(); + _buffer = new byte[windowSize]; + } + _windowSize = windowSize; + _pos = 0; + _streamPos = 0; + } - public void Init(System.IO.Stream stream, bool solid) - { - ReleaseStream(); - _stream = stream; - if (!solid) - { - _streamPos = 0; - _pos = 0; - TrainSize = 0; - } - } - - public bool Train(System.IO.Stream stream) - { - long len = stream.Length; - uint size = (len < _windowSize) ? (uint)len : _windowSize; - TrainSize = size; - stream.Position = len - size; - _streamPos = _pos = 0; - while (size > 0) - { - uint curSize = _windowSize - _pos; - if (size < curSize) - curSize = size; - int numReadBytes = stream.Read(_buffer, (int)_pos, (int)curSize); - if (numReadBytes == 0) - return false; - size -= (uint)numReadBytes; - _pos += (uint)numReadBytes; - _streamPos += (uint)numReadBytes; - if (_pos == _windowSize) - _streamPos = _pos = 0; - } - return true; - } + public void Init(System.IO.Stream stream, bool solid) + { + ReleaseStream(); + _stream = stream; + if (!solid) + { + _streamPos = 0; + _pos = 0; + TrainSize = 0; + } + } - public void ReleaseStream() - { - Flush(); - _stream = null; - } + public bool Train(System.IO.Stream stream) + { + long len = stream.Length; + uint size = (len < _windowSize) ? (uint)len : _windowSize; + TrainSize = size; + stream.Position = len - size; + _streamPos = _pos = 0; + while (size > 0) + { + uint curSize = _windowSize - _pos; + if (size < curSize) + curSize = size; + int numReadBytes = stream.Read(_buffer, (int)_pos, (int)curSize); + if (numReadBytes == 0) + return false; + size -= (uint)numReadBytes; + _pos += (uint)numReadBytes; + _streamPos += (uint)numReadBytes; + if (_pos == _windowSize) + _streamPos = _pos = 0; + } + return true; + } - public void Flush() - { - uint size = _pos - _streamPos; - if (size == 0) - return; - _stream.Write(_buffer, (int)_streamPos, (int)size); - if (_pos >= _windowSize) - _pos = 0; - _streamPos = _pos; - } + public void ReleaseStream() + { + Flush(); + _stream = null; + } - public void CopyBlock(uint distance, uint len) - { - uint pos = _pos - distance - 1; - if (pos >= _windowSize) - pos += _windowSize; - for (; len > 0; len--) - { - if (pos >= _windowSize) - pos = 0; - _buffer[_pos++] = _buffer[pos++]; - if (_pos >= _windowSize) - Flush(); - } - } + public void Flush() + { + uint size = _pos - _streamPos; + if (size == 0) + return; + _stream.Write(_buffer, (int)_streamPos, (int)size); + if (_pos >= _windowSize) + _pos = 0; + _streamPos = _pos; + } - public void PutByte(byte b) - { - _buffer[_pos++] = b; - if (_pos >= _windowSize) - Flush(); - } + public void CopyBlock(uint distance, uint len) + { + uint pos = _pos - distance - 1; + if (pos >= _windowSize) + pos += _windowSize; + for (; len > 0; len--) + { + if (pos >= _windowSize) + pos = 0; + _buffer[_pos++] = _buffer[pos++]; + if (_pos >= _windowSize) + Flush(); + } + } - public byte GetByte(uint distance) - { - uint pos = _pos - distance - 1; - if (pos >= _windowSize) - pos += _windowSize; - return _buffer[pos]; - } - } + public void PutByte(byte b) + { + _buffer[_pos++] = b; + if (_pos >= _windowSize) + Flush(); + } + + public byte GetByte(uint distance) + { + uint pos = _pos - distance - 1; + if (pos >= _windowSize) + pos += _windowSize; + return _buffer[pos]; + } + } } diff --git a/7zip/Compress/LZMA/LzmaBase.cs b/7zip/Compress/LZMA/LzmaBase.cs index 8447a2a..3692c21 100644 --- a/7zip/Compress/LZMA/LzmaBase.cs +++ b/7zip/Compress/LZMA/LzmaBase.cs @@ -2,75 +2,75 @@ namespace SevenZip.Compression.LZMA { - internal abstract class Base - { - public const uint kNumRepDistances = 4; - public const uint kNumStates = 12; + internal abstract class Base + { + public const uint kNumRepDistances = 4; + public const uint kNumStates = 12; - // static byte []kLiteralNextStates = {0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 4, 5}; - // static byte []kMatchNextStates = {7, 7, 7, 7, 7, 7, 7, 10, 10, 10, 10, 10}; - // static byte []kRepNextStates = {8, 8, 8, 8, 8, 8, 8, 11, 11, 11, 11, 11}; - // static byte []kShortRepNextStates = {9, 9, 9, 9, 9, 9, 9, 11, 11, 11, 11, 11}; + // static byte []kLiteralNextStates = {0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 4, 5}; + // static byte []kMatchNextStates = {7, 7, 7, 7, 7, 7, 7, 10, 10, 10, 10, 10}; + // static byte []kRepNextStates = {8, 8, 8, 8, 8, 8, 8, 11, 11, 11, 11, 11}; + // static byte []kShortRepNextStates = {9, 9, 9, 9, 9, 9, 9, 11, 11, 11, 11, 11}; - public struct State - { - public uint Index; - public void Init() { Index = 0; } - public void UpdateChar() - { - if (Index < 4) Index = 0; - else if (Index < 10) Index -= 3; - else Index -= 6; - } - public void UpdateMatch() { Index = (uint)(Index < 7 ? 7 : 10); } - public void UpdateRep() { Index = (uint)(Index < 7 ? 8 : 11); } - public void UpdateShortRep() { Index = (uint)(Index < 7 ? 9 : 11); } - public bool IsCharState() { return Index < 7; } - } + public struct State + { + public uint Index; + public void Init() { Index = 0; } + public void UpdateChar() + { + if (Index < 4) Index = 0; + else if (Index < 10) Index -= 3; + else Index -= 6; + } + public void UpdateMatch() { Index = (uint)(Index < 7 ? 7 : 10); } + public void UpdateRep() { Index = (uint)(Index < 7 ? 8 : 11); } + public void UpdateShortRep() { Index = (uint)(Index < 7 ? 9 : 11); } + public bool IsCharState() { return Index < 7; } + } - public const int kNumPosSlotBits = 6; - public const int kDicLogSizeMin = 0; - // public const int kDicLogSizeMax = 30; - // public const uint kDistTableSizeMax = kDicLogSizeMax * 2; + public const int kNumPosSlotBits = 6; + public const int kDicLogSizeMin = 0; + // public const int kDicLogSizeMax = 30; + // public const uint kDistTableSizeMax = kDicLogSizeMax * 2; - public const int kNumLenToPosStatesBits = 2; // it's for speed optimization - public const uint kNumLenToPosStates = 1 << kNumLenToPosStatesBits; + public const int kNumLenToPosStatesBits = 2; // it's for speed optimization + public const uint kNumLenToPosStates = 1 << kNumLenToPosStatesBits; - public const uint kMatchMinLen = 2; + public const uint kMatchMinLen = 2; - public static uint GetLenToPosState(uint len) - { - len -= kMatchMinLen; - if (len < kNumLenToPosStates) - return len; - return (uint)(kNumLenToPosStates - 1); - } + public static uint GetLenToPosState(uint len) + { + len -= kMatchMinLen; + if (len < kNumLenToPosStates) + return len; + return (uint)(kNumLenToPosStates - 1); + } - public const int kNumAlignBits = 4; - public const uint kAlignTableSize = 1 << kNumAlignBits; - public const uint kAlignMask = (kAlignTableSize - 1); + public const int kNumAlignBits = 4; + public const uint kAlignTableSize = 1 << kNumAlignBits; + public const uint kAlignMask = (kAlignTableSize - 1); - public const uint kStartPosModelIndex = 4; - public const uint kEndPosModelIndex = 14; - public const uint kNumPosModels = kEndPosModelIndex - kStartPosModelIndex; + public const uint kStartPosModelIndex = 4; + public const uint kEndPosModelIndex = 14; + public const uint kNumPosModels = kEndPosModelIndex - kStartPosModelIndex; - public const uint kNumFullDistances = 1 << ((int)kEndPosModelIndex / 2); + public const uint kNumFullDistances = 1 << ((int)kEndPosModelIndex / 2); - public const uint kNumLitPosStatesBitsEncodingMax = 4; - public const uint kNumLitContextBitsMax = 8; + public const uint kNumLitPosStatesBitsEncodingMax = 4; + public const uint kNumLitContextBitsMax = 8; - public const int kNumPosStatesBitsMax = 4; - public const uint kNumPosStatesMax = (1 << kNumPosStatesBitsMax); - public const int kNumPosStatesBitsEncodingMax = 4; - public const uint kNumPosStatesEncodingMax = (1 << kNumPosStatesBitsEncodingMax); + public const int kNumPosStatesBitsMax = 4; + public const uint kNumPosStatesMax = (1 << kNumPosStatesBitsMax); + public const int kNumPosStatesBitsEncodingMax = 4; + public const uint kNumPosStatesEncodingMax = (1 << kNumPosStatesBitsEncodingMax); - public const int kNumLowLenBits = 3; - public const int kNumMidLenBits = 3; - public const int kNumHighLenBits = 8; - public const uint kNumLowLenSymbols = 1 << kNumLowLenBits; - public const uint kNumMidLenSymbols = 1 << kNumMidLenBits; - public const uint kNumLenSymbols = kNumLowLenSymbols + kNumMidLenSymbols + - (1 << kNumHighLenBits); - public const uint kMatchMaxLen = kMatchMinLen + kNumLenSymbols - 1; - } + public const int kNumLowLenBits = 3; + public const int kNumMidLenBits = 3; + public const int kNumHighLenBits = 8; + public const uint kNumLowLenSymbols = 1 << kNumLowLenBits; + public const uint kNumMidLenSymbols = 1 << kNumMidLenBits; + public const uint kNumLenSymbols = kNumLowLenSymbols + kNumMidLenSymbols + + (1 << kNumHighLenBits); + public const uint kMatchMaxLen = kMatchMinLen + kNumLenSymbols - 1; + } } diff --git a/7zip/Compress/LZMA/LzmaDecoder.cs b/7zip/Compress/LZMA/LzmaDecoder.cs index 00bfe63..d60cc0c 100644 --- a/7zip/Compress/LZMA/LzmaDecoder.cs +++ b/7zip/Compress/LZMA/LzmaDecoder.cs @@ -4,373 +4,373 @@ using System; namespace SevenZip.Compression.LZMA { - using RangeCoder; + using RangeCoder; - public class Decoder : ICoder, ISetDecoderProperties // ,System.IO.Stream - { - class LenDecoder - { - BitDecoder m_Choice = new BitDecoder(); - BitDecoder m_Choice2 = new BitDecoder(); - BitTreeDecoder[] m_LowCoder = new BitTreeDecoder[Base.kNumPosStatesMax]; - BitTreeDecoder[] m_MidCoder = new BitTreeDecoder[Base.kNumPosStatesMax]; - BitTreeDecoder m_HighCoder = new BitTreeDecoder(Base.kNumHighLenBits); - uint m_NumPosStates = 0; + public class Decoder : ICoder, ISetDecoderProperties // ,System.IO.Stream + { + class LenDecoder + { + BitDecoder m_Choice = new BitDecoder(); + BitDecoder m_Choice2 = new BitDecoder(); + BitTreeDecoder[] m_LowCoder = new BitTreeDecoder[Base.kNumPosStatesMax]; + BitTreeDecoder[] m_MidCoder = new BitTreeDecoder[Base.kNumPosStatesMax]; + BitTreeDecoder m_HighCoder = new BitTreeDecoder(Base.kNumHighLenBits); + uint m_NumPosStates = 0; - public void Create(uint numPosStates) - { - for (uint posState = m_NumPosStates; posState < numPosStates; posState++) - { - m_LowCoder[posState] = new BitTreeDecoder(Base.kNumLowLenBits); - m_MidCoder[posState] = new BitTreeDecoder(Base.kNumMidLenBits); - } - m_NumPosStates = numPosStates; - } + public void Create(uint numPosStates) + { + for (uint posState = m_NumPosStates; posState < numPosStates; posState++) + { + m_LowCoder[posState] = new BitTreeDecoder(Base.kNumLowLenBits); + m_MidCoder[posState] = new BitTreeDecoder(Base.kNumMidLenBits); + } + m_NumPosStates = numPosStates; + } - public void Init() - { - m_Choice.Init(); - for (uint posState = 0; posState < m_NumPosStates; posState++) - { - m_LowCoder[posState].Init(); - m_MidCoder[posState].Init(); - } - m_Choice2.Init(); - m_HighCoder.Init(); - } + public void Init() + { + m_Choice.Init(); + for (uint posState = 0; posState < m_NumPosStates; posState++) + { + m_LowCoder[posState].Init(); + m_MidCoder[posState].Init(); + } + m_Choice2.Init(); + m_HighCoder.Init(); + } - public uint Decode(RangeCoder.Decoder rangeDecoder, uint posState) - { - if (m_Choice.Decode(rangeDecoder) == 0) - return m_LowCoder[posState].Decode(rangeDecoder); - else - { - uint symbol = Base.kNumLowLenSymbols; - if (m_Choice2.Decode(rangeDecoder) == 0) - symbol += m_MidCoder[posState].Decode(rangeDecoder); - else - { - symbol += Base.kNumMidLenSymbols; - symbol += m_HighCoder.Decode(rangeDecoder); - } - return symbol; - } - } - } + public uint Decode(RangeCoder.Decoder rangeDecoder, uint posState) + { + if (m_Choice.Decode(rangeDecoder) == 0) + return m_LowCoder[posState].Decode(rangeDecoder); + else + { + uint symbol = Base.kNumLowLenSymbols; + if (m_Choice2.Decode(rangeDecoder) == 0) + symbol += m_MidCoder[posState].Decode(rangeDecoder); + else + { + symbol += Base.kNumMidLenSymbols; + symbol += m_HighCoder.Decode(rangeDecoder); + } + return symbol; + } + } + } - class LiteralDecoder - { - struct Decoder2 - { - BitDecoder[] m_Decoders; - public void Create() { m_Decoders = new BitDecoder[0x300]; } - public void Init() { for (int i = 0; i < 0x300; i++) m_Decoders[i].Init(); } + class LiteralDecoder + { + struct Decoder2 + { + BitDecoder[] m_Decoders; + public void Create() { m_Decoders = new BitDecoder[0x300]; } + public void Init() { for (int i = 0; i < 0x300; i++) m_Decoders[i].Init(); } - public byte DecodeNormal(RangeCoder.Decoder rangeDecoder) - { - uint symbol = 1; - do - symbol = (symbol << 1) | m_Decoders[symbol].Decode(rangeDecoder); - while (symbol < 0x100); - return (byte)symbol; - } + public byte DecodeNormal(RangeCoder.Decoder rangeDecoder) + { + uint symbol = 1; + do + symbol = (symbol << 1) | m_Decoders[symbol].Decode(rangeDecoder); + while (symbol < 0x100); + return (byte)symbol; + } - public byte DecodeWithMatchByte(RangeCoder.Decoder rangeDecoder, byte matchByte) - { - uint symbol = 1; - do - { - uint matchBit = (uint)(matchByte >> 7) & 1; - matchByte <<= 1; - uint bit = m_Decoders[((1 + matchBit) << 8) + symbol].Decode(rangeDecoder); - symbol = (symbol << 1) | bit; - if (matchBit != bit) - { - while (symbol < 0x100) - symbol = (symbol << 1) | m_Decoders[symbol].Decode(rangeDecoder); - break; - } - } - while (symbol < 0x100); - return (byte)symbol; - } - } + public byte DecodeWithMatchByte(RangeCoder.Decoder rangeDecoder, byte matchByte) + { + uint symbol = 1; + do + { + uint matchBit = (uint)(matchByte >> 7) & 1; + matchByte <<= 1; + uint bit = m_Decoders[((1 + matchBit) << 8) + symbol].Decode(rangeDecoder); + symbol = (symbol << 1) | bit; + if (matchBit != bit) + { + while (symbol < 0x100) + symbol = (symbol << 1) | m_Decoders[symbol].Decode(rangeDecoder); + break; + } + } + while (symbol < 0x100); + return (byte)symbol; + } + } - Decoder2[] m_Coders; - int m_NumPrevBits; - int m_NumPosBits; - uint m_PosMask; + Decoder2[] m_Coders; + int m_NumPrevBits; + int m_NumPosBits; + uint m_PosMask; - public void Create(int numPosBits, int numPrevBits) - { - if (m_Coders != null && m_NumPrevBits == numPrevBits && - m_NumPosBits == numPosBits) - return; - m_NumPosBits = numPosBits; - m_PosMask = ((uint)1 << numPosBits) - 1; - m_NumPrevBits = numPrevBits; - uint numStates = (uint)1 << (m_NumPrevBits + m_NumPosBits); - m_Coders = new Decoder2[numStates]; - for (uint i = 0; i < numStates; i++) - m_Coders[i].Create(); - } + public void Create(int numPosBits, int numPrevBits) + { + if (m_Coders != null && m_NumPrevBits == numPrevBits && + m_NumPosBits == numPosBits) + return; + m_NumPosBits = numPosBits; + m_PosMask = ((uint)1 << numPosBits) - 1; + m_NumPrevBits = numPrevBits; + uint numStates = (uint)1 << (m_NumPrevBits + m_NumPosBits); + m_Coders = new Decoder2[numStates]; + for (uint i = 0; i < numStates; i++) + m_Coders[i].Create(); + } - public void Init() - { - uint numStates = (uint)1 << (m_NumPrevBits + m_NumPosBits); - for (uint i = 0; i < numStates; i++) - m_Coders[i].Init(); - } + public void Init() + { + uint numStates = (uint)1 << (m_NumPrevBits + m_NumPosBits); + for (uint i = 0; i < numStates; i++) + m_Coders[i].Init(); + } - uint GetState(uint pos, byte prevByte) - { return ((pos & m_PosMask) << m_NumPrevBits) + (uint)(prevByte >> (8 - m_NumPrevBits)); } + uint GetState(uint pos, byte prevByte) + { return ((pos & m_PosMask) << m_NumPrevBits) + (uint)(prevByte >> (8 - m_NumPrevBits)); } - public byte DecodeNormal(RangeCoder.Decoder rangeDecoder, uint pos, byte prevByte) - { return m_Coders[GetState(pos, prevByte)].DecodeNormal(rangeDecoder); } + public byte DecodeNormal(RangeCoder.Decoder rangeDecoder, uint pos, byte prevByte) + { return m_Coders[GetState(pos, prevByte)].DecodeNormal(rangeDecoder); } - public byte DecodeWithMatchByte(RangeCoder.Decoder rangeDecoder, uint pos, byte prevByte, byte matchByte) - { return m_Coders[GetState(pos, prevByte)].DecodeWithMatchByte(rangeDecoder, matchByte); } - }; + public byte DecodeWithMatchByte(RangeCoder.Decoder rangeDecoder, uint pos, byte prevByte, byte matchByte) + { return m_Coders[GetState(pos, prevByte)].DecodeWithMatchByte(rangeDecoder, matchByte); } + }; - LZ.OutWindow m_OutWindow = new LZ.OutWindow(); - RangeCoder.Decoder m_RangeDecoder = new RangeCoder.Decoder(); + LZ.OutWindow m_OutWindow = new LZ.OutWindow(); + RangeCoder.Decoder m_RangeDecoder = new RangeCoder.Decoder(); - BitDecoder[] m_IsMatchDecoders = new BitDecoder[Base.kNumStates << Base.kNumPosStatesBitsMax]; - BitDecoder[] m_IsRepDecoders = new BitDecoder[Base.kNumStates]; - BitDecoder[] m_IsRepG0Decoders = new BitDecoder[Base.kNumStates]; - BitDecoder[] m_IsRepG1Decoders = new BitDecoder[Base.kNumStates]; - BitDecoder[] m_IsRepG2Decoders = new BitDecoder[Base.kNumStates]; - BitDecoder[] m_IsRep0LongDecoders = new BitDecoder[Base.kNumStates << Base.kNumPosStatesBitsMax]; + BitDecoder[] m_IsMatchDecoders = new BitDecoder[Base.kNumStates << Base.kNumPosStatesBitsMax]; + BitDecoder[] m_IsRepDecoders = new BitDecoder[Base.kNumStates]; + BitDecoder[] m_IsRepG0Decoders = new BitDecoder[Base.kNumStates]; + BitDecoder[] m_IsRepG1Decoders = new BitDecoder[Base.kNumStates]; + BitDecoder[] m_IsRepG2Decoders = new BitDecoder[Base.kNumStates]; + BitDecoder[] m_IsRep0LongDecoders = new BitDecoder[Base.kNumStates << Base.kNumPosStatesBitsMax]; - BitTreeDecoder[] m_PosSlotDecoder = new BitTreeDecoder[Base.kNumLenToPosStates]; - BitDecoder[] m_PosDecoders = new BitDecoder[Base.kNumFullDistances - Base.kEndPosModelIndex]; + BitTreeDecoder[] m_PosSlotDecoder = new BitTreeDecoder[Base.kNumLenToPosStates]; + BitDecoder[] m_PosDecoders = new BitDecoder[Base.kNumFullDistances - Base.kEndPosModelIndex]; - BitTreeDecoder m_PosAlignDecoder = new BitTreeDecoder(Base.kNumAlignBits); + BitTreeDecoder m_PosAlignDecoder = new BitTreeDecoder(Base.kNumAlignBits); - LenDecoder m_LenDecoder = new LenDecoder(); - LenDecoder m_RepLenDecoder = new LenDecoder(); + LenDecoder m_LenDecoder = new LenDecoder(); + LenDecoder m_RepLenDecoder = new LenDecoder(); - LiteralDecoder m_LiteralDecoder = new LiteralDecoder(); + LiteralDecoder m_LiteralDecoder = new LiteralDecoder(); - uint m_DictionarySize; - uint m_DictionarySizeCheck; + uint m_DictionarySize; + uint m_DictionarySizeCheck; - uint m_PosStateMask; + uint m_PosStateMask; - public Decoder() - { - m_DictionarySize = 0xFFFFFFFF; - for (int i = 0; i < Base.kNumLenToPosStates; i++) - m_PosSlotDecoder[i] = new BitTreeDecoder(Base.kNumPosSlotBits); - } + public Decoder() + { + m_DictionarySize = 0xFFFFFFFF; + for (int i = 0; i < Base.kNumLenToPosStates; i++) + m_PosSlotDecoder[i] = new BitTreeDecoder(Base.kNumPosSlotBits); + } - void SetDictionarySize(uint dictionarySize) - { - if (m_DictionarySize != dictionarySize) - { - m_DictionarySize = dictionarySize; - m_DictionarySizeCheck = Math.Max(m_DictionarySize, 1); - uint blockSize = Math.Max(m_DictionarySizeCheck, (1 << 12)); - m_OutWindow.Create(blockSize); - } - } + void SetDictionarySize(uint dictionarySize) + { + if (m_DictionarySize != dictionarySize) + { + m_DictionarySize = dictionarySize; + m_DictionarySizeCheck = Math.Max(m_DictionarySize, 1); + uint blockSize = Math.Max(m_DictionarySizeCheck, (1 << 12)); + m_OutWindow.Create(blockSize); + } + } - void SetLiteralProperties(int lp, int lc) - { - if (lp > 8) - throw new InvalidParamException(); - if (lc > 8) - throw new InvalidParamException(); - m_LiteralDecoder.Create(lp, lc); - } + void SetLiteralProperties(int lp, int lc) + { + if (lp > 8) + throw new InvalidParamException(); + if (lc > 8) + throw new InvalidParamException(); + m_LiteralDecoder.Create(lp, lc); + } - void SetPosBitsProperties(int pb) - { - if (pb > Base.kNumPosStatesBitsMax) - throw new InvalidParamException(); - uint numPosStates = (uint)1 << pb; - m_LenDecoder.Create(numPosStates); - m_RepLenDecoder.Create(numPosStates); - m_PosStateMask = numPosStates - 1; - } + void SetPosBitsProperties(int pb) + { + if (pb > Base.kNumPosStatesBitsMax) + throw new InvalidParamException(); + uint numPosStates = (uint)1 << pb; + m_LenDecoder.Create(numPosStates); + m_RepLenDecoder.Create(numPosStates); + m_PosStateMask = numPosStates - 1; + } - bool _solid = false; - void Init(System.IO.Stream inStream, System.IO.Stream outStream) - { - m_RangeDecoder.Init(inStream); - m_OutWindow.Init(outStream, _solid); + bool _solid = false; + void Init(System.IO.Stream inStream, System.IO.Stream outStream) + { + m_RangeDecoder.Init(inStream); + m_OutWindow.Init(outStream, _solid); - uint i; - for (i = 0; i < Base.kNumStates; i++) - { - for (uint j = 0; j <= m_PosStateMask; j++) - { - uint index = (i << Base.kNumPosStatesBitsMax) + j; - m_IsMatchDecoders[index].Init(); - m_IsRep0LongDecoders[index].Init(); - } - m_IsRepDecoders[i].Init(); - m_IsRepG0Decoders[i].Init(); - m_IsRepG1Decoders[i].Init(); - m_IsRepG2Decoders[i].Init(); - } + uint i; + for (i = 0; i < Base.kNumStates; i++) + { + for (uint j = 0; j <= m_PosStateMask; j++) + { + uint index = (i << Base.kNumPosStatesBitsMax) + j; + m_IsMatchDecoders[index].Init(); + m_IsRep0LongDecoders[index].Init(); + } + m_IsRepDecoders[i].Init(); + m_IsRepG0Decoders[i].Init(); + m_IsRepG1Decoders[i].Init(); + m_IsRepG2Decoders[i].Init(); + } - m_LiteralDecoder.Init(); - for (i = 0; i < Base.kNumLenToPosStates; i++) - m_PosSlotDecoder[i].Init(); - // m_PosSpecDecoder.Init(); - for (i = 0; i < Base.kNumFullDistances - Base.kEndPosModelIndex; i++) - m_PosDecoders[i].Init(); + m_LiteralDecoder.Init(); + for (i = 0; i < Base.kNumLenToPosStates; i++) + m_PosSlotDecoder[i].Init(); + // m_PosSpecDecoder.Init(); + for (i = 0; i < Base.kNumFullDistances - Base.kEndPosModelIndex; i++) + m_PosDecoders[i].Init(); - m_LenDecoder.Init(); - m_RepLenDecoder.Init(); - m_PosAlignDecoder.Init(); - } + m_LenDecoder.Init(); + m_RepLenDecoder.Init(); + m_PosAlignDecoder.Init(); + } - public void Code(System.IO.Stream inStream, System.IO.Stream outStream, - Int64 inSize, Int64 outSize, ICodeProgress progress) - { - Init(inStream, outStream); + public void Code(System.IO.Stream inStream, System.IO.Stream outStream, + Int64 inSize, Int64 outSize, ICodeProgress progress) + { + Init(inStream, outStream); - Base.State state = new Base.State(); - state.Init(); - uint rep0 = 0, rep1 = 0, rep2 = 0, rep3 = 0; + Base.State state = new Base.State(); + state.Init(); + uint rep0 = 0, rep1 = 0, rep2 = 0, rep3 = 0; - UInt64 nowPos64 = 0; - UInt64 outSize64 = (UInt64)outSize; - if (nowPos64 < outSize64) - { - if (m_IsMatchDecoders[state.Index << Base.kNumPosStatesBitsMax].Decode(m_RangeDecoder) != 0) - throw new DataErrorException(); - state.UpdateChar(); - byte b = m_LiteralDecoder.DecodeNormal(m_RangeDecoder, 0, 0); - m_OutWindow.PutByte(b); - nowPos64++; - } - while (nowPos64 < outSize64) - { - // UInt64 next = Math.Min(nowPos64 + (1 << 18), outSize64); - // while(nowPos64 < next) - { - uint posState = (uint)nowPos64 & m_PosStateMask; - if (m_IsMatchDecoders[(state.Index << Base.kNumPosStatesBitsMax) + posState].Decode(m_RangeDecoder) == 0) - { - byte b; - byte prevByte = m_OutWindow.GetByte(0); - if (!state.IsCharState()) - b = m_LiteralDecoder.DecodeWithMatchByte(m_RangeDecoder, - (uint)nowPos64, prevByte, m_OutWindow.GetByte(rep0)); - else - b = m_LiteralDecoder.DecodeNormal(m_RangeDecoder, (uint)nowPos64, prevByte); - m_OutWindow.PutByte(b); - state.UpdateChar(); - nowPos64++; - } - else - { - uint len; - if (m_IsRepDecoders[state.Index].Decode(m_RangeDecoder) == 1) - { - if (m_IsRepG0Decoders[state.Index].Decode(m_RangeDecoder) == 0) - { - if (m_IsRep0LongDecoders[(state.Index << Base.kNumPosStatesBitsMax) + posState].Decode(m_RangeDecoder) == 0) - { - state.UpdateShortRep(); - m_OutWindow.PutByte(m_OutWindow.GetByte(rep0)); - nowPos64++; - continue; - } - } - else - { - UInt32 distance; - if (m_IsRepG1Decoders[state.Index].Decode(m_RangeDecoder) == 0) - { - distance = rep1; - } - else - { - if (m_IsRepG2Decoders[state.Index].Decode(m_RangeDecoder) == 0) - distance = rep2; - else - { - distance = rep3; - rep3 = rep2; - } - rep2 = rep1; - } - rep1 = rep0; - rep0 = distance; - } - len = m_RepLenDecoder.Decode(m_RangeDecoder, posState) + Base.kMatchMinLen; - state.UpdateRep(); - } - else - { - rep3 = rep2; - rep2 = rep1; - rep1 = rep0; - len = Base.kMatchMinLen + m_LenDecoder.Decode(m_RangeDecoder, posState); - state.UpdateMatch(); - uint posSlot = m_PosSlotDecoder[Base.GetLenToPosState(len)].Decode(m_RangeDecoder); - if (posSlot >= Base.kStartPosModelIndex) - { - int numDirectBits = (int)((posSlot >> 1) - 1); - rep0 = ((2 | (posSlot & 1)) << numDirectBits); - if (posSlot < Base.kEndPosModelIndex) - rep0 += BitTreeDecoder.ReverseDecode(m_PosDecoders, - rep0 - posSlot - 1, m_RangeDecoder, numDirectBits); - else - { - rep0 += (m_RangeDecoder.DecodeDirectBits( - numDirectBits - Base.kNumAlignBits) << Base.kNumAlignBits); - rep0 += m_PosAlignDecoder.ReverseDecode(m_RangeDecoder); - } - } - else - rep0 = posSlot; - } - if (rep0 >= m_OutWindow.TrainSize + nowPos64 || rep0 >= m_DictionarySizeCheck) - { - if (rep0 == 0xFFFFFFFF) - break; - throw new DataErrorException(); - } - m_OutWindow.CopyBlock(rep0, len); - nowPos64 += len; - } - } - } - m_OutWindow.Flush(); - m_OutWindow.ReleaseStream(); - m_RangeDecoder.ReleaseStream(); - } + UInt64 nowPos64 = 0; + UInt64 outSize64 = (UInt64)outSize; + if (nowPos64 < outSize64) + { + if (m_IsMatchDecoders[state.Index << Base.kNumPosStatesBitsMax].Decode(m_RangeDecoder) != 0) + throw new DataErrorException(); + state.UpdateChar(); + byte b = m_LiteralDecoder.DecodeNormal(m_RangeDecoder, 0, 0); + m_OutWindow.PutByte(b); + nowPos64++; + } + while (nowPos64 < outSize64) + { + // UInt64 next = Math.Min(nowPos64 + (1 << 18), outSize64); + // while(nowPos64 < next) + { + uint posState = (uint)nowPos64 & m_PosStateMask; + if (m_IsMatchDecoders[(state.Index << Base.kNumPosStatesBitsMax) + posState].Decode(m_RangeDecoder) == 0) + { + byte b; + byte prevByte = m_OutWindow.GetByte(0); + if (!state.IsCharState()) + b = m_LiteralDecoder.DecodeWithMatchByte(m_RangeDecoder, + (uint)nowPos64, prevByte, m_OutWindow.GetByte(rep0)); + else + b = m_LiteralDecoder.DecodeNormal(m_RangeDecoder, (uint)nowPos64, prevByte); + m_OutWindow.PutByte(b); + state.UpdateChar(); + nowPos64++; + } + else + { + uint len; + if (m_IsRepDecoders[state.Index].Decode(m_RangeDecoder) == 1) + { + if (m_IsRepG0Decoders[state.Index].Decode(m_RangeDecoder) == 0) + { + if (m_IsRep0LongDecoders[(state.Index << Base.kNumPosStatesBitsMax) + posState].Decode(m_RangeDecoder) == 0) + { + state.UpdateShortRep(); + m_OutWindow.PutByte(m_OutWindow.GetByte(rep0)); + nowPos64++; + continue; + } + } + else + { + UInt32 distance; + if (m_IsRepG1Decoders[state.Index].Decode(m_RangeDecoder) == 0) + { + distance = rep1; + } + else + { + if (m_IsRepG2Decoders[state.Index].Decode(m_RangeDecoder) == 0) + distance = rep2; + else + { + distance = rep3; + rep3 = rep2; + } + rep2 = rep1; + } + rep1 = rep0; + rep0 = distance; + } + len = m_RepLenDecoder.Decode(m_RangeDecoder, posState) + Base.kMatchMinLen; + state.UpdateRep(); + } + else + { + rep3 = rep2; + rep2 = rep1; + rep1 = rep0; + len = Base.kMatchMinLen + m_LenDecoder.Decode(m_RangeDecoder, posState); + state.UpdateMatch(); + uint posSlot = m_PosSlotDecoder[Base.GetLenToPosState(len)].Decode(m_RangeDecoder); + if (posSlot >= Base.kStartPosModelIndex) + { + int numDirectBits = (int)((posSlot >> 1) - 1); + rep0 = ((2 | (posSlot & 1)) << numDirectBits); + if (posSlot < Base.kEndPosModelIndex) + rep0 += BitTreeDecoder.ReverseDecode(m_PosDecoders, + rep0 - posSlot - 1, m_RangeDecoder, numDirectBits); + else + { + rep0 += (m_RangeDecoder.DecodeDirectBits( + numDirectBits - Base.kNumAlignBits) << Base.kNumAlignBits); + rep0 += m_PosAlignDecoder.ReverseDecode(m_RangeDecoder); + } + } + else + rep0 = posSlot; + } + if (rep0 >= m_OutWindow.TrainSize + nowPos64 || rep0 >= m_DictionarySizeCheck) + { + if (rep0 == 0xFFFFFFFF) + break; + throw new DataErrorException(); + } + m_OutWindow.CopyBlock(rep0, len); + nowPos64 += len; + } + } + } + m_OutWindow.Flush(); + m_OutWindow.ReleaseStream(); + m_RangeDecoder.ReleaseStream(); + } - public void SetDecoderProperties(byte[] properties) - { - if (properties.Length < 5) - throw new InvalidParamException(); - int lc = properties[0] % 9; - int remainder = properties[0] / 9; - int lp = remainder % 5; - int pb = remainder / 5; - if (pb > Base.kNumPosStatesBitsMax) - throw new InvalidParamException(); - UInt32 dictionarySize = 0; - for (int i = 0; i < 4; i++) - dictionarySize += ((UInt32)(properties[1 + i])) << (i * 8); - SetDictionarySize(dictionarySize); - SetLiteralProperties(lp, lc); - SetPosBitsProperties(pb); - } + public void SetDecoderProperties(byte[] properties) + { + if (properties.Length < 5) + throw new InvalidParamException(); + int lc = properties[0] % 9; + int remainder = properties[0] / 9; + int lp = remainder % 5; + int pb = remainder / 5; + if (pb > Base.kNumPosStatesBitsMax) + throw new InvalidParamException(); + UInt32 dictionarySize = 0; + for (int i = 0; i < 4; i++) + dictionarySize += ((UInt32)(properties[1 + i])) << (i * 8); + SetDictionarySize(dictionarySize); + SetLiteralProperties(lp, lc); + SetPosBitsProperties(pb); + } - public bool Train(System.IO.Stream stream) - { - _solid = true; - return m_OutWindow.Train(stream); - } + public bool Train(System.IO.Stream stream) + { + _solid = true; + return m_OutWindow.Train(stream); + } - /* + /* public override bool CanRead { get { return true; }} public override bool CanWrite { get { return true; }} public override bool CanSeek { get { return true; }} @@ -394,5 +394,5 @@ namespace SevenZip.Compression.LZMA } public override void SetLength(long value) {} */ - } + } } diff --git a/7zip/Compress/LZMA/LzmaEncoder.cs b/7zip/Compress/LZMA/LzmaEncoder.cs index 6dc2708..3589d45 100644 --- a/7zip/Compress/LZMA/LzmaEncoder.cs +++ b/7zip/Compress/LZMA/LzmaEncoder.cs @@ -4,1477 +4,1477 @@ using System; namespace SevenZip.Compression.LZMA { - using RangeCoder; - - public class Encoder : ICoder, ISetCoderProperties, IWriteCoderProperties - { - enum EMatchFinderType - { - BT2, - BT4, - }; - - const UInt32 kIfinityPrice = 0xFFFFFFF; - - static Byte[] g_FastPos = new Byte[1 << 11]; - - static Encoder() - { - const Byte kFastSlots = 22; - int c = 2; - g_FastPos[0] = 0; - g_FastPos[1] = 1; - for (Byte slotFast = 2; slotFast < kFastSlots; slotFast++) - { - UInt32 k = ((UInt32)1 << ((slotFast >> 1) - 1)); - for (UInt32 j = 0; j < k; j++, c++) - g_FastPos[c] = slotFast; - } - } - - static UInt32 GetPosSlot(UInt32 pos) - { - if (pos < (1 << 11)) - return g_FastPos[pos]; - if (pos < (1 << 21)) - return (UInt32)(g_FastPos[pos >> 10] + 20); - return (UInt32)(g_FastPos[pos >> 20] + 40); - } - - static UInt32 GetPosSlot2(UInt32 pos) - { - if (pos < (1 << 17)) - return (UInt32)(g_FastPos[pos >> 6] + 12); - if (pos < (1 << 27)) - return (UInt32)(g_FastPos[pos >> 16] + 32); - return (UInt32)(g_FastPos[pos >> 26] + 52); - } - - Base.State _state = new Base.State(); - Byte _previousByte; - UInt32[] _repDistances = new UInt32[Base.kNumRepDistances]; - - void BaseInit() - { - _state.Init(); - _previousByte = 0; - for (UInt32 i = 0; i < Base.kNumRepDistances; i++) - _repDistances[i] = 0; - } - - const int kDefaultDictionaryLogSize = 22; - const UInt32 kNumFastBytesDefault = 0x20; - - class LiteralEncoder - { - public struct Encoder2 - { - BitEncoder[] m_Encoders; - - public void Create() { m_Encoders = new BitEncoder[0x300]; } - - public void Init() { for (int i = 0; i < 0x300; i++) m_Encoders[i].Init(); } - - public void Encode(RangeCoder.Encoder rangeEncoder, byte symbol) - { - uint context = 1; - for (int i = 7; i >= 0; i--) - { - uint bit = (uint)((symbol >> i) & 1); - m_Encoders[context].Encode(rangeEncoder, bit); - context = (context << 1) | bit; - } - } - - public void EncodeMatched(RangeCoder.Encoder rangeEncoder, byte matchByte, byte symbol) - { - uint context = 1; - bool same = true; - for (int i = 7; i >= 0; i--) - { - uint bit = (uint)((symbol >> i) & 1); - uint state = context; - if (same) - { - uint matchBit = (uint)((matchByte >> i) & 1); - state += ((1 + matchBit) << 8); - same = (matchBit == bit); - } - m_Encoders[state].Encode(rangeEncoder, bit); - context = (context << 1) | bit; - } - } - - public uint GetPrice(bool matchMode, byte matchByte, byte symbol) - { - uint price = 0; - uint context = 1; - int i = 7; - if (matchMode) - { - for (; i >= 0; i--) - { - uint matchBit = (uint)(matchByte >> i) & 1; - uint bit = (uint)(symbol >> i) & 1; - price += m_Encoders[((1 + matchBit) << 8) + context].GetPrice(bit); - context = (context << 1) | bit; - if (matchBit != bit) - { - i--; - break; - } - } - } - for (; i >= 0; i--) - { - uint bit = (uint)(symbol >> i) & 1; - price += m_Encoders[context].GetPrice(bit); - context = (context << 1) | bit; - } - return price; - } - } - - Encoder2[] m_Coders; - int m_NumPrevBits; - int m_NumPosBits; - uint m_PosMask; - - public void Create(int numPosBits, int numPrevBits) - { - if (m_Coders != null && m_NumPrevBits == numPrevBits && m_NumPosBits == numPosBits) - return; - m_NumPosBits = numPosBits; - m_PosMask = ((uint)1 << numPosBits) - 1; - m_NumPrevBits = numPrevBits; - uint numStates = (uint)1 << (m_NumPrevBits + m_NumPosBits); - m_Coders = new Encoder2[numStates]; - for (uint i = 0; i < numStates; i++) - m_Coders[i].Create(); - } - - public void Init() - { - uint numStates = (uint)1 << (m_NumPrevBits + m_NumPosBits); - for (uint i = 0; i < numStates; i++) - m_Coders[i].Init(); - } - - public Encoder2 GetSubCoder(UInt32 pos, Byte prevByte) - { return m_Coders[((pos & m_PosMask) << m_NumPrevBits) + (uint)(prevByte >> (8 - m_NumPrevBits))]; } - } - - class LenEncoder - { - RangeCoder.BitEncoder _choice = new RangeCoder.BitEncoder(); - RangeCoder.BitEncoder _choice2 = new RangeCoder.BitEncoder(); - RangeCoder.BitTreeEncoder[] _lowCoder = new RangeCoder.BitTreeEncoder[Base.kNumPosStatesEncodingMax]; - RangeCoder.BitTreeEncoder[] _midCoder = new RangeCoder.BitTreeEncoder[Base.kNumPosStatesEncodingMax]; - RangeCoder.BitTreeEncoder _highCoder = new RangeCoder.BitTreeEncoder(Base.kNumHighLenBits); - - public LenEncoder() - { - for (UInt32 posState = 0; posState < Base.kNumPosStatesEncodingMax; posState++) - { - _lowCoder[posState] = new RangeCoder.BitTreeEncoder(Base.kNumLowLenBits); - _midCoder[posState] = new RangeCoder.BitTreeEncoder(Base.kNumMidLenBits); - } - } - - public void Init(UInt32 numPosStates) - { - _choice.Init(); - _choice2.Init(); - for (UInt32 posState = 0; posState < numPosStates; posState++) - { - _lowCoder[posState].Init(); - _midCoder[posState].Init(); - } - _highCoder.Init(); - } - - public void Encode(RangeCoder.Encoder rangeEncoder, UInt32 symbol, UInt32 posState) - { - if (symbol < Base.kNumLowLenSymbols) - { - _choice.Encode(rangeEncoder, 0); - _lowCoder[posState].Encode(rangeEncoder, symbol); - } - else - { - symbol -= Base.kNumLowLenSymbols; - _choice.Encode(rangeEncoder, 1); - if (symbol < Base.kNumMidLenSymbols) - { - _choice2.Encode(rangeEncoder, 0); - _midCoder[posState].Encode(rangeEncoder, symbol); - } - else - { - _choice2.Encode(rangeEncoder, 1); - _highCoder.Encode(rangeEncoder, symbol - Base.kNumMidLenSymbols); - } - } - } - - public void SetPrices(UInt32 posState, UInt32 numSymbols, UInt32[] prices, UInt32 st) - { - UInt32 a0 = _choice.GetPrice0(); - UInt32 a1 = _choice.GetPrice1(); - UInt32 b0 = a1 + _choice2.GetPrice0(); - UInt32 b1 = a1 + _choice2.GetPrice1(); - UInt32 i = 0; - for (i = 0; i < Base.kNumLowLenSymbols; i++) - { - if (i >= numSymbols) - return; - prices[st + i] = a0 + _lowCoder[posState].GetPrice(i); - } - for (; i < Base.kNumLowLenSymbols + Base.kNumMidLenSymbols; i++) - { - if (i >= numSymbols) - return; - prices[st + i] = b0 + _midCoder[posState].GetPrice(i - Base.kNumLowLenSymbols); - } - for (; i < numSymbols; i++) - prices[st + i] = b1 + _highCoder.GetPrice(i - Base.kNumLowLenSymbols - Base.kNumMidLenSymbols); - } - }; - - const UInt32 kNumLenSpecSymbols = Base.kNumLowLenSymbols + Base.kNumMidLenSymbols; - - class LenPriceTableEncoder : LenEncoder - { - UInt32[] _prices = new UInt32[Base.kNumLenSymbols << Base.kNumPosStatesBitsEncodingMax]; - UInt32 _tableSize; - UInt32[] _counters = new UInt32[Base.kNumPosStatesEncodingMax]; - - public void SetTableSize(UInt32 tableSize) { _tableSize = tableSize; } - - public UInt32 GetPrice(UInt32 symbol, UInt32 posState) - { - return _prices[posState * Base.kNumLenSymbols + symbol]; - } - - void UpdateTable(UInt32 posState) - { - SetPrices(posState, _tableSize, _prices, posState * Base.kNumLenSymbols); - _counters[posState] = _tableSize; - } - - public void UpdateTables(UInt32 numPosStates) - { - for (UInt32 posState = 0; posState < numPosStates; posState++) - UpdateTable(posState); - } - - public new void Encode(RangeCoder.Encoder rangeEncoder, UInt32 symbol, UInt32 posState) - { - base.Encode(rangeEncoder, symbol, posState); - if (--_counters[posState] == 0) - UpdateTable(posState); - } - } - - const UInt32 kNumOpts = 1 << 12; - class Optimal - { - public Base.State State; - - public bool Prev1IsChar; - public bool Prev2; - - public UInt32 PosPrev2; - public UInt32 BackPrev2; - - public UInt32 Price; - public UInt32 PosPrev; - public UInt32 BackPrev; - - public UInt32 Backs0; - public UInt32 Backs1; - public UInt32 Backs2; - public UInt32 Backs3; - - public void MakeAsChar() { BackPrev = 0xFFFFFFFF; Prev1IsChar = false; } - public void MakeAsShortRep() { BackPrev = 0; ; Prev1IsChar = false; } - public bool IsShortRep() { return (BackPrev == 0); } - }; - Optimal[] _optimum = new Optimal[kNumOpts]; - LZ.IMatchFinder _matchFinder = null; - RangeCoder.Encoder _rangeEncoder = new RangeCoder.Encoder(); - - RangeCoder.BitEncoder[] _isMatch = new RangeCoder.BitEncoder[Base.kNumStates << Base.kNumPosStatesBitsMax]; - RangeCoder.BitEncoder[] _isRep = new RangeCoder.BitEncoder[Base.kNumStates]; - RangeCoder.BitEncoder[] _isRepG0 = new RangeCoder.BitEncoder[Base.kNumStates]; - RangeCoder.BitEncoder[] _isRepG1 = new RangeCoder.BitEncoder[Base.kNumStates]; - RangeCoder.BitEncoder[] _isRepG2 = new RangeCoder.BitEncoder[Base.kNumStates]; - RangeCoder.BitEncoder[] _isRep0Long = new RangeCoder.BitEncoder[Base.kNumStates << Base.kNumPosStatesBitsMax]; - - RangeCoder.BitTreeEncoder[] _posSlotEncoder = new RangeCoder.BitTreeEncoder[Base.kNumLenToPosStates]; - - RangeCoder.BitEncoder[] _posEncoders = new RangeCoder.BitEncoder[Base.kNumFullDistances - Base.kEndPosModelIndex]; - RangeCoder.BitTreeEncoder _posAlignEncoder = new RangeCoder.BitTreeEncoder(Base.kNumAlignBits); - - LenPriceTableEncoder _lenEncoder = new LenPriceTableEncoder(); - LenPriceTableEncoder _repMatchLenEncoder = new LenPriceTableEncoder(); - - LiteralEncoder _literalEncoder = new LiteralEncoder(); - - UInt32[] _matchDistances = new UInt32[Base.kMatchMaxLen * 2 + 2]; - - UInt32 _numFastBytes = kNumFastBytesDefault; - UInt32 _longestMatchLength; - UInt32 _numDistancePairs; - - UInt32 _additionalOffset; - - UInt32 _optimumEndIndex; - UInt32 _optimumCurrentIndex; - - bool _longestMatchWasFound; - - UInt32[] _posSlotPrices = new UInt32[1 << (Base.kNumPosSlotBits + Base.kNumLenToPosStatesBits)]; - UInt32[] _distancesPrices = new UInt32[Base.kNumFullDistances << Base.kNumLenToPosStatesBits]; - UInt32[] _alignPrices = new UInt32[Base.kAlignTableSize]; - UInt32 _alignPriceCount; - - UInt32 _distTableSize = (kDefaultDictionaryLogSize * 2); - - int _posStateBits = 2; - UInt32 _posStateMask = (4 - 1); - int _numLiteralPosStateBits = 0; - int _numLiteralContextBits = 3; - - UInt32 _dictionarySize = (1 << kDefaultDictionaryLogSize); - UInt32 _dictionarySizePrev = 0xFFFFFFFF; - UInt32 _numFastBytesPrev = 0xFFFFFFFF; - - Int64 nowPos64; - bool _finished; - System.IO.Stream _inStream; - - EMatchFinderType _matchFinderType = EMatchFinderType.BT4; - bool _writeEndMark = false; - - bool _needReleaseMFStream; - - void Create() - { - if (_matchFinder == null) - { - LZ.BinTree bt = new LZ.BinTree(); - int numHashBytes = 4; - if (_matchFinderType == EMatchFinderType.BT2) - numHashBytes = 2; - bt.SetType(numHashBytes); - _matchFinder = bt; - } - _literalEncoder.Create(_numLiteralPosStateBits, _numLiteralContextBits); - - if (_dictionarySize == _dictionarySizePrev && _numFastBytesPrev == _numFastBytes) - return; - _matchFinder.Create(_dictionarySize, kNumOpts, _numFastBytes, Base.kMatchMaxLen + 1); - _dictionarySizePrev = _dictionarySize; - _numFastBytesPrev = _numFastBytes; - } - - public Encoder() - { - for (int i = 0; i < kNumOpts; i++) - _optimum[i] = new Optimal(); - for (int i = 0; i < Base.kNumLenToPosStates; i++) - _posSlotEncoder[i] = new RangeCoder.BitTreeEncoder(Base.kNumPosSlotBits); - } - - void SetWriteEndMarkerMode(bool writeEndMarker) - { - _writeEndMark = writeEndMarker; - } - - void Init() - { - BaseInit(); - _rangeEncoder.Init(); - - uint i; - for (i = 0; i < Base.kNumStates; i++) - { - for (uint j = 0; j <= _posStateMask; j++) - { - uint complexState = (i << Base.kNumPosStatesBitsMax) + j; - _isMatch[complexState].Init(); - _isRep0Long[complexState].Init(); - } - _isRep[i].Init(); - _isRepG0[i].Init(); - _isRepG1[i].Init(); - _isRepG2[i].Init(); - } - _literalEncoder.Init(); - for (i = 0; i < Base.kNumLenToPosStates; i++) - _posSlotEncoder[i].Init(); - for (i = 0; i < Base.kNumFullDistances - Base.kEndPosModelIndex; i++) - _posEncoders[i].Init(); - - _lenEncoder.Init((UInt32)1 << _posStateBits); - _repMatchLenEncoder.Init((UInt32)1 << _posStateBits); - - _posAlignEncoder.Init(); - - _longestMatchWasFound = false; - _optimumEndIndex = 0; - _optimumCurrentIndex = 0; - _additionalOffset = 0; - } - - void ReadMatchDistances(out UInt32 lenRes, out UInt32 numDistancePairs) - { - lenRes = 0; - numDistancePairs = _matchFinder.GetMatches(_matchDistances); - if (numDistancePairs > 0) - { - lenRes = _matchDistances[numDistancePairs - 2]; - if (lenRes == _numFastBytes) - lenRes += _matchFinder.GetMatchLen((int)lenRes - 1, _matchDistances[numDistancePairs - 1], - Base.kMatchMaxLen - lenRes); - } - _additionalOffset++; - } - - - void MovePos(UInt32 num) - { - if (num > 0) - { - _matchFinder.Skip(num); - _additionalOffset += num; - } - } - - UInt32 GetRepLen1Price(Base.State state, UInt32 posState) - { - return _isRepG0[state.Index].GetPrice0() + - _isRep0Long[(state.Index << Base.kNumPosStatesBitsMax) + posState].GetPrice0(); - } - - UInt32 GetPureRepPrice(UInt32 repIndex, Base.State state, UInt32 posState) - { - UInt32 price; - if (repIndex == 0) - { - price = _isRepG0[state.Index].GetPrice0(); - price += _isRep0Long[(state.Index << Base.kNumPosStatesBitsMax) + posState].GetPrice1(); - } - else - { - price = _isRepG0[state.Index].GetPrice1(); - if (repIndex == 1) - price += _isRepG1[state.Index].GetPrice0(); - else - { - price += _isRepG1[state.Index].GetPrice1(); - price += _isRepG2[state.Index].GetPrice(repIndex - 2); - } - } - return price; - } - - UInt32 GetRepPrice(UInt32 repIndex, UInt32 len, Base.State state, UInt32 posState) - { - UInt32 price = _repMatchLenEncoder.GetPrice(len - Base.kMatchMinLen, posState); - return price + GetPureRepPrice(repIndex, state, posState); - } - - UInt32 GetPosLenPrice(UInt32 pos, UInt32 len, UInt32 posState) - { - UInt32 price; - UInt32 lenToPosState = Base.GetLenToPosState(len); - if (pos < Base.kNumFullDistances) - price = _distancesPrices[(lenToPosState * Base.kNumFullDistances) + pos]; - else - price = _posSlotPrices[(lenToPosState << Base.kNumPosSlotBits) + GetPosSlot2(pos)] + - _alignPrices[pos & Base.kAlignMask]; - return price + _lenEncoder.GetPrice(len - Base.kMatchMinLen, posState); - } - - UInt32 Backward(out UInt32 backRes, UInt32 cur) - { - _optimumEndIndex = cur; - UInt32 posMem = _optimum[cur].PosPrev; - UInt32 backMem = _optimum[cur].BackPrev; - do - { - if (_optimum[cur].Prev1IsChar) - { - _optimum[posMem].MakeAsChar(); - _optimum[posMem].PosPrev = posMem - 1; - if (_optimum[cur].Prev2) - { - _optimum[posMem - 1].Prev1IsChar = false; - _optimum[posMem - 1].PosPrev = _optimum[cur].PosPrev2; - _optimum[posMem - 1].BackPrev = _optimum[cur].BackPrev2; - } - } - UInt32 posPrev = posMem; - UInt32 backCur = backMem; - - backMem = _optimum[posPrev].BackPrev; - posMem = _optimum[posPrev].PosPrev; - - _optimum[posPrev].BackPrev = backCur; - _optimum[posPrev].PosPrev = cur; - cur = posPrev; - } - while (cur > 0); - backRes = _optimum[0].BackPrev; - _optimumCurrentIndex = _optimum[0].PosPrev; - return _optimumCurrentIndex; - } - - UInt32[] reps = new UInt32[Base.kNumRepDistances]; - UInt32[] repLens = new UInt32[Base.kNumRepDistances]; - - - UInt32 GetOptimum(UInt32 position, out UInt32 backRes) - { - if (_optimumEndIndex != _optimumCurrentIndex) - { - UInt32 lenRes = _optimum[_optimumCurrentIndex].PosPrev - _optimumCurrentIndex; - backRes = _optimum[_optimumCurrentIndex].BackPrev; - _optimumCurrentIndex = _optimum[_optimumCurrentIndex].PosPrev; - return lenRes; - } - _optimumCurrentIndex = _optimumEndIndex = 0; - - UInt32 lenMain, numDistancePairs; - if (!_longestMatchWasFound) - { - ReadMatchDistances(out lenMain, out numDistancePairs); - } - else - { - lenMain = _longestMatchLength; - numDistancePairs = _numDistancePairs; - _longestMatchWasFound = false; - } - - UInt32 numAvailableBytes = _matchFinder.GetNumAvailableBytes() + 1; - if (numAvailableBytes < 2) - { - backRes = 0xFFFFFFFF; - return 1; - } - if (numAvailableBytes > Base.kMatchMaxLen) - numAvailableBytes = Base.kMatchMaxLen; - - UInt32 repMaxIndex = 0; - UInt32 i; - for (i = 0; i < Base.kNumRepDistances; i++) - { - reps[i] = _repDistances[i]; - repLens[i] = _matchFinder.GetMatchLen(0 - 1, reps[i], Base.kMatchMaxLen); - if (repLens[i] > repLens[repMaxIndex]) - repMaxIndex = i; - } - if (repLens[repMaxIndex] >= _numFastBytes) - { - backRes = repMaxIndex; - UInt32 lenRes = repLens[repMaxIndex]; - MovePos(lenRes - 1); - return lenRes; - } - - if (lenMain >= _numFastBytes) - { - backRes = _matchDistances[numDistancePairs - 1] + Base.kNumRepDistances; - MovePos(lenMain - 1); - return lenMain; - } - - Byte currentByte = _matchFinder.GetIndexByte(0 - 1); - Byte matchByte = _matchFinder.GetIndexByte((Int32)(0 - _repDistances[0] - 1 - 1)); - - if (lenMain < 2 && currentByte != matchByte && repLens[repMaxIndex] < 2) - { - backRes = (UInt32)0xFFFFFFFF; - return 1; - } - - _optimum[0].State = _state; - - UInt32 posState = (position & _posStateMask); - - _optimum[1].Price = _isMatch[(_state.Index << Base.kNumPosStatesBitsMax) + posState].GetPrice0() + - _literalEncoder.GetSubCoder(position, _previousByte).GetPrice(!_state.IsCharState(), matchByte, currentByte); - _optimum[1].MakeAsChar(); - - UInt32 matchPrice = _isMatch[(_state.Index << Base.kNumPosStatesBitsMax) + posState].GetPrice1(); - UInt32 repMatchPrice = matchPrice + _isRep[_state.Index].GetPrice1(); - - if (matchByte == currentByte) - { - UInt32 shortRepPrice = repMatchPrice + GetRepLen1Price(_state, posState); - if (shortRepPrice < _optimum[1].Price) - { - _optimum[1].Price = shortRepPrice; - _optimum[1].MakeAsShortRep(); - } - } - - UInt32 lenEnd = ((lenMain >= repLens[repMaxIndex]) ? lenMain : repLens[repMaxIndex]); - - if(lenEnd < 2) - { - backRes = _optimum[1].BackPrev; - return 1; - } - - _optimum[1].PosPrev = 0; - - _optimum[0].Backs0 = reps[0]; - _optimum[0].Backs1 = reps[1]; - _optimum[0].Backs2 = reps[2]; - _optimum[0].Backs3 = reps[3]; - - UInt32 len = lenEnd; - do - _optimum[len--].Price = kIfinityPrice; - while (len >= 2); - - for (i = 0; i < Base.kNumRepDistances; i++) - { - UInt32 repLen = repLens[i]; - if (repLen < 2) - continue; - UInt32 price = repMatchPrice + GetPureRepPrice(i, _state, posState); - do - { - UInt32 curAndLenPrice = price + _repMatchLenEncoder.GetPrice(repLen - 2, posState); - Optimal optimum = _optimum[repLen]; - if (curAndLenPrice < optimum.Price) - { - optimum.Price = curAndLenPrice; - optimum.PosPrev = 0; - optimum.BackPrev = i; - optimum.Prev1IsChar = false; - } - } - while (--repLen >= 2); - } - - UInt32 normalMatchPrice = matchPrice + _isRep[_state.Index].GetPrice0(); - - len = ((repLens[0] >= 2) ? repLens[0] + 1 : 2); - if (len <= lenMain) - { - UInt32 offs = 0; - while (len > _matchDistances[offs]) - offs += 2; - for (; ; len++) - { - UInt32 distance = _matchDistances[offs + 1]; - UInt32 curAndLenPrice = normalMatchPrice + GetPosLenPrice(distance, len, posState); - Optimal optimum = _optimum[len]; - if (curAndLenPrice < optimum.Price) - { - optimum.Price = curAndLenPrice; - optimum.PosPrev = 0; - optimum.BackPrev = distance + Base.kNumRepDistances; - optimum.Prev1IsChar = false; - } - if (len == _matchDistances[offs]) - { - offs += 2; - if (offs == numDistancePairs) - break; - } - } - } - - UInt32 cur = 0; - - while (true) - { - cur++; - if (cur == lenEnd) - return Backward(out backRes, cur); - UInt32 newLen; - ReadMatchDistances(out newLen, out numDistancePairs); - if (newLen >= _numFastBytes) - { - _numDistancePairs = numDistancePairs; - _longestMatchLength = newLen; - _longestMatchWasFound = true; - return Backward(out backRes, cur); - } - position++; - UInt32 posPrev = _optimum[cur].PosPrev; - Base.State state; - if (_optimum[cur].Prev1IsChar) - { - posPrev--; - if (_optimum[cur].Prev2) - { - state = _optimum[_optimum[cur].PosPrev2].State; - if (_optimum[cur].BackPrev2 < Base.kNumRepDistances) - state.UpdateRep(); - else - state.UpdateMatch(); - } - else - state = _optimum[posPrev].State; - state.UpdateChar(); - } - else - state = _optimum[posPrev].State; - if (posPrev == cur - 1) - { - if (_optimum[cur].IsShortRep()) - state.UpdateShortRep(); - else - state.UpdateChar(); - } - else - { - UInt32 pos; - if (_optimum[cur].Prev1IsChar && _optimum[cur].Prev2) - { - posPrev = _optimum[cur].PosPrev2; - pos = _optimum[cur].BackPrev2; - state.UpdateRep(); - } - else - { - pos = _optimum[cur].BackPrev; - if (pos < Base.kNumRepDistances) - state.UpdateRep(); - else - state.UpdateMatch(); - } - Optimal opt = _optimum[posPrev]; - if (pos < Base.kNumRepDistances) - { - if (pos == 0) - { - reps[0] = opt.Backs0; - reps[1] = opt.Backs1; - reps[2] = opt.Backs2; - reps[3] = opt.Backs3; - } - else if (pos == 1) - { - reps[0] = opt.Backs1; - reps[1] = opt.Backs0; - reps[2] = opt.Backs2; - reps[3] = opt.Backs3; - } - else if (pos == 2) - { - reps[0] = opt.Backs2; - reps[1] = opt.Backs0; - reps[2] = opt.Backs1; - reps[3] = opt.Backs3; - } - else - { - reps[0] = opt.Backs3; - reps[1] = opt.Backs0; - reps[2] = opt.Backs1; - reps[3] = opt.Backs2; - } - } - else - { - reps[0] = (pos - Base.kNumRepDistances); - reps[1] = opt.Backs0; - reps[2] = opt.Backs1; - reps[3] = opt.Backs2; - } - } - _optimum[cur].State = state; - _optimum[cur].Backs0 = reps[0]; - _optimum[cur].Backs1 = reps[1]; - _optimum[cur].Backs2 = reps[2]; - _optimum[cur].Backs3 = reps[3]; - UInt32 curPrice = _optimum[cur].Price; - - currentByte = _matchFinder.GetIndexByte(0 - 1); - matchByte = _matchFinder.GetIndexByte((Int32)(0 - reps[0] - 1 - 1)); - - posState = (position & _posStateMask); - - UInt32 curAnd1Price = curPrice + - _isMatch[(state.Index << Base.kNumPosStatesBitsMax) + posState].GetPrice0() + - _literalEncoder.GetSubCoder(position, _matchFinder.GetIndexByte(0 - 2)). - GetPrice(!state.IsCharState(), matchByte, currentByte); - - Optimal nextOptimum = _optimum[cur + 1]; - - bool nextIsChar = false; - if (curAnd1Price < nextOptimum.Price) - { - nextOptimum.Price = curAnd1Price; - nextOptimum.PosPrev = cur; - nextOptimum.MakeAsChar(); - nextIsChar = true; - } - - matchPrice = curPrice + _isMatch[(state.Index << Base.kNumPosStatesBitsMax) + posState].GetPrice1(); - repMatchPrice = matchPrice + _isRep[state.Index].GetPrice1(); - - if (matchByte == currentByte && - !(nextOptimum.PosPrev < cur && nextOptimum.BackPrev == 0)) - { - UInt32 shortRepPrice = repMatchPrice + GetRepLen1Price(state, posState); - if (shortRepPrice <= nextOptimum.Price) - { - nextOptimum.Price = shortRepPrice; - nextOptimum.PosPrev = cur; - nextOptimum.MakeAsShortRep(); - nextIsChar = true; - } - } - - UInt32 numAvailableBytesFull = _matchFinder.GetNumAvailableBytes() + 1; - numAvailableBytesFull = Math.Min(kNumOpts - 1 - cur, numAvailableBytesFull); - numAvailableBytes = numAvailableBytesFull; - - if (numAvailableBytes < 2) - continue; - if (numAvailableBytes > _numFastBytes) - numAvailableBytes = _numFastBytes; - if (!nextIsChar && matchByte != currentByte) - { - // try Literal + rep0 - UInt32 t = Math.Min(numAvailableBytesFull - 1, _numFastBytes); - UInt32 lenTest2 = _matchFinder.GetMatchLen(0, reps[0], t); - if (lenTest2 >= 2) - { - Base.State state2 = state; - state2.UpdateChar(); - UInt32 posStateNext = (position + 1) & _posStateMask; - UInt32 nextRepMatchPrice = curAnd1Price + - _isMatch[(state2.Index << Base.kNumPosStatesBitsMax) + posStateNext].GetPrice1() + - _isRep[state2.Index].GetPrice1(); - { - UInt32 offset = cur + 1 + lenTest2; - while (lenEnd < offset) - _optimum[++lenEnd].Price = kIfinityPrice; - UInt32 curAndLenPrice = nextRepMatchPrice + GetRepPrice( - 0, lenTest2, state2, posStateNext); - Optimal optimum = _optimum[offset]; - if (curAndLenPrice < optimum.Price) - { - optimum.Price = curAndLenPrice; - optimum.PosPrev = cur + 1; - optimum.BackPrev = 0; - optimum.Prev1IsChar = true; - optimum.Prev2 = false; - } - } - } - } - - UInt32 startLen = 2; // speed optimization - - for (UInt32 repIndex = 0; repIndex < Base.kNumRepDistances; repIndex++) - { - UInt32 lenTest = _matchFinder.GetMatchLen(0 - 1, reps[repIndex], numAvailableBytes); - if (lenTest < 2) - continue; - UInt32 lenTestTemp = lenTest; - do - { - while (lenEnd < cur + lenTest) - _optimum[++lenEnd].Price = kIfinityPrice; - UInt32 curAndLenPrice = repMatchPrice + GetRepPrice(repIndex, lenTest, state, posState); - Optimal optimum = _optimum[cur + lenTest]; - if (curAndLenPrice < optimum.Price) - { - optimum.Price = curAndLenPrice; - optimum.PosPrev = cur; - optimum.BackPrev = repIndex; - optimum.Prev1IsChar = false; - } - } - while(--lenTest >= 2); - lenTest = lenTestTemp; - - if (repIndex == 0) - startLen = lenTest + 1; - - // if (_maxMode) - if (lenTest < numAvailableBytesFull) - { - UInt32 t = Math.Min(numAvailableBytesFull - 1 - lenTest, _numFastBytes); - UInt32 lenTest2 = _matchFinder.GetMatchLen((Int32)lenTest, reps[repIndex], t); - if (lenTest2 >= 2) - { - Base.State state2 = state; - state2.UpdateRep(); - UInt32 posStateNext = (position + lenTest) & _posStateMask; - UInt32 curAndLenCharPrice = - repMatchPrice + GetRepPrice(repIndex, lenTest, state, posState) + - _isMatch[(state2.Index << Base.kNumPosStatesBitsMax) + posStateNext].GetPrice0() + - _literalEncoder.GetSubCoder(position + lenTest, - _matchFinder.GetIndexByte((Int32)lenTest - 1 - 1)).GetPrice(true, - _matchFinder.GetIndexByte((Int32)((Int32)lenTest - 1 - (Int32)(reps[repIndex] + 1))), - _matchFinder.GetIndexByte((Int32)lenTest - 1)); - state2.UpdateChar(); - posStateNext = (position + lenTest + 1) & _posStateMask; - UInt32 nextMatchPrice = curAndLenCharPrice + _isMatch[(state2.Index << Base.kNumPosStatesBitsMax) + posStateNext].GetPrice1(); - UInt32 nextRepMatchPrice = nextMatchPrice + _isRep[state2.Index].GetPrice1(); - - // for(; lenTest2 >= 2; lenTest2--) - { - UInt32 offset = lenTest + 1 + lenTest2; - while(lenEnd < cur + offset) - _optimum[++lenEnd].Price = kIfinityPrice; - UInt32 curAndLenPrice = nextRepMatchPrice + GetRepPrice(0, lenTest2, state2, posStateNext); - Optimal optimum = _optimum[cur + offset]; - if (curAndLenPrice < optimum.Price) - { - optimum.Price = curAndLenPrice; - optimum.PosPrev = cur + lenTest + 1; - optimum.BackPrev = 0; - optimum.Prev1IsChar = true; - optimum.Prev2 = true; - optimum.PosPrev2 = cur; - optimum.BackPrev2 = repIndex; - } - } - } - } - } - - if (newLen > numAvailableBytes) - { - newLen = numAvailableBytes; - for (numDistancePairs = 0; newLen > _matchDistances[numDistancePairs]; numDistancePairs += 2) ; - _matchDistances[numDistancePairs] = newLen; - numDistancePairs += 2; - } - if (newLen >= startLen) - { - normalMatchPrice = matchPrice + _isRep[state.Index].GetPrice0(); - while (lenEnd < cur + newLen) - _optimum[++lenEnd].Price = kIfinityPrice; - - UInt32 offs = 0; - while (startLen > _matchDistances[offs]) - offs += 2; - - for (UInt32 lenTest = startLen; ; lenTest++) - { - UInt32 curBack = _matchDistances[offs + 1]; - UInt32 curAndLenPrice = normalMatchPrice + GetPosLenPrice(curBack, lenTest, posState); - Optimal optimum = _optimum[cur + lenTest]; - if (curAndLenPrice < optimum.Price) - { - optimum.Price = curAndLenPrice; - optimum.PosPrev = cur; - optimum.BackPrev = curBack + Base.kNumRepDistances; - optimum.Prev1IsChar = false; - } - - if (lenTest == _matchDistances[offs]) - { - if (lenTest < numAvailableBytesFull) - { - UInt32 t = Math.Min(numAvailableBytesFull - 1 - lenTest, _numFastBytes); - UInt32 lenTest2 = _matchFinder.GetMatchLen((Int32)lenTest, curBack, t); - if (lenTest2 >= 2) - { - Base.State state2 = state; - state2.UpdateMatch(); - UInt32 posStateNext = (position + lenTest) & _posStateMask; - UInt32 curAndLenCharPrice = curAndLenPrice + - _isMatch[(state2.Index << Base.kNumPosStatesBitsMax) + posStateNext].GetPrice0() + - _literalEncoder.GetSubCoder(position + lenTest, - _matchFinder.GetIndexByte((Int32)lenTest - 1 - 1)). - GetPrice(true, - _matchFinder.GetIndexByte((Int32)lenTest - (Int32)(curBack + 1) - 1), - _matchFinder.GetIndexByte((Int32)lenTest - 1)); - state2.UpdateChar(); - posStateNext = (position + lenTest + 1) & _posStateMask; - UInt32 nextMatchPrice = curAndLenCharPrice + _isMatch[(state2.Index << Base.kNumPosStatesBitsMax) + posStateNext].GetPrice1(); - UInt32 nextRepMatchPrice = nextMatchPrice + _isRep[state2.Index].GetPrice1(); - - UInt32 offset = lenTest + 1 + lenTest2; - while (lenEnd < cur + offset) - _optimum[++lenEnd].Price = kIfinityPrice; - curAndLenPrice = nextRepMatchPrice + GetRepPrice(0, lenTest2, state2, posStateNext); - optimum = _optimum[cur + offset]; - if (curAndLenPrice < optimum.Price) - { - optimum.Price = curAndLenPrice; - optimum.PosPrev = cur + lenTest + 1; - optimum.BackPrev = 0; - optimum.Prev1IsChar = true; - optimum.Prev2 = true; - optimum.PosPrev2 = cur; - optimum.BackPrev2 = curBack + Base.kNumRepDistances; - } - } - } - offs += 2; - if (offs == numDistancePairs) - break; - } - } - } - } - } - - bool ChangePair(UInt32 smallDist, UInt32 bigDist) - { - const int kDif = 7; - return (smallDist < ((UInt32)(1) << (32 - kDif)) && bigDist >= (smallDist << kDif)); - } - - void WriteEndMarker(UInt32 posState) - { - if (!_writeEndMark) - return; - - _isMatch[(_state.Index << Base.kNumPosStatesBitsMax) + posState].Encode(_rangeEncoder, 1); - _isRep[_state.Index].Encode(_rangeEncoder, 0); - _state.UpdateMatch(); - UInt32 len = Base.kMatchMinLen; - _lenEncoder.Encode(_rangeEncoder, len - Base.kMatchMinLen, posState); - UInt32 posSlot = (1 << Base.kNumPosSlotBits) - 1; - UInt32 lenToPosState = Base.GetLenToPosState(len); - _posSlotEncoder[lenToPosState].Encode(_rangeEncoder, posSlot); - int footerBits = 30; - UInt32 posReduced = (((UInt32)1) << footerBits) - 1; - _rangeEncoder.EncodeDirectBits(posReduced >> Base.kNumAlignBits, footerBits - Base.kNumAlignBits); - _posAlignEncoder.ReverseEncode(_rangeEncoder, posReduced & Base.kAlignMask); - } - - void Flush(UInt32 nowPos) - { - ReleaseMFStream(); - WriteEndMarker(nowPos & _posStateMask); - _rangeEncoder.FlushData(); - _rangeEncoder.FlushStream(); - } - - public void CodeOneBlock(out Int64 inSize, out Int64 outSize, out bool finished) - { - inSize = 0; - outSize = 0; - finished = true; - - if (_inStream != null) - { - _matchFinder.SetStream(_inStream); - _matchFinder.Init(); - _needReleaseMFStream = true; - _inStream = null; - if (_trainSize > 0) - _matchFinder.Skip(_trainSize); - } - - if (_finished) - return; - _finished = true; - - - Int64 progressPosValuePrev = nowPos64; - if (nowPos64 == 0) - { - if (_matchFinder.GetNumAvailableBytes() == 0) - { - Flush((UInt32)nowPos64); - return; - } - UInt32 len, numDistancePairs; // it's not used - ReadMatchDistances(out len, out numDistancePairs); - UInt32 posState = (UInt32)(nowPos64) & _posStateMask; - _isMatch[(_state.Index << Base.kNumPosStatesBitsMax) + posState].Encode(_rangeEncoder, 0); - _state.UpdateChar(); - Byte curByte = _matchFinder.GetIndexByte((Int32)(0 - _additionalOffset)); - _literalEncoder.GetSubCoder((UInt32)(nowPos64), _previousByte).Encode(_rangeEncoder, curByte); - _previousByte = curByte; - _additionalOffset--; - nowPos64++; - } - if (_matchFinder.GetNumAvailableBytes() == 0) - { - Flush((UInt32)nowPos64); - return; - } - while (true) - { - UInt32 pos; - UInt32 len = GetOptimum((UInt32)nowPos64, out pos); - - UInt32 posState = ((UInt32)nowPos64) & _posStateMask; - UInt32 complexState = (_state.Index << Base.kNumPosStatesBitsMax) + posState; - if (len == 1 && pos == 0xFFFFFFFF) - { - _isMatch[complexState].Encode(_rangeEncoder, 0); - Byte curByte = _matchFinder.GetIndexByte((Int32)(0 - _additionalOffset)); - LiteralEncoder.Encoder2 subCoder = _literalEncoder.GetSubCoder((UInt32)nowPos64, _previousByte); - if (!_state.IsCharState()) - { - Byte matchByte = _matchFinder.GetIndexByte((Int32)(0 - _repDistances[0] - 1 - _additionalOffset)); - subCoder.EncodeMatched(_rangeEncoder, matchByte, curByte); - } - else - subCoder.Encode(_rangeEncoder, curByte); - _previousByte = curByte; - _state.UpdateChar(); - } - else - { - _isMatch[complexState].Encode(_rangeEncoder, 1); - if (pos < Base.kNumRepDistances) - { - _isRep[_state.Index].Encode(_rangeEncoder, 1); - if (pos == 0) - { - _isRepG0[_state.Index].Encode(_rangeEncoder, 0); - if (len == 1) - _isRep0Long[complexState].Encode(_rangeEncoder, 0); - else - _isRep0Long[complexState].Encode(_rangeEncoder, 1); - } - else - { - _isRepG0[_state.Index].Encode(_rangeEncoder, 1); - if (pos == 1) - _isRepG1[_state.Index].Encode(_rangeEncoder, 0); - else - { - _isRepG1[_state.Index].Encode(_rangeEncoder, 1); - _isRepG2[_state.Index].Encode(_rangeEncoder, pos - 2); - } - } - if (len == 1) - _state.UpdateShortRep(); - else - { - _repMatchLenEncoder.Encode(_rangeEncoder, len - Base.kMatchMinLen, posState); - _state.UpdateRep(); - } - UInt32 distance = _repDistances[pos]; - if (pos != 0) - { - for (UInt32 i = pos; i >= 1; i--) - _repDistances[i] = _repDistances[i - 1]; - _repDistances[0] = distance; - } - } - else - { - _isRep[_state.Index].Encode(_rangeEncoder, 0); - _state.UpdateMatch(); - _lenEncoder.Encode(_rangeEncoder, len - Base.kMatchMinLen, posState); - pos -= Base.kNumRepDistances; - UInt32 posSlot = GetPosSlot(pos); - UInt32 lenToPosState = Base.GetLenToPosState(len); - _posSlotEncoder[lenToPosState].Encode(_rangeEncoder, posSlot); - - if (posSlot >= Base.kStartPosModelIndex) - { - int footerBits = (int)((posSlot >> 1) - 1); - UInt32 baseVal = ((2 | (posSlot & 1)) << footerBits); - UInt32 posReduced = pos - baseVal; - - if (posSlot < Base.kEndPosModelIndex) - RangeCoder.BitTreeEncoder.ReverseEncode(_posEncoders, - baseVal - posSlot - 1, _rangeEncoder, footerBits, posReduced); - else - { - _rangeEncoder.EncodeDirectBits(posReduced >> Base.kNumAlignBits, footerBits - Base.kNumAlignBits); - _posAlignEncoder.ReverseEncode(_rangeEncoder, posReduced & Base.kAlignMask); - _alignPriceCount++; - } - } - UInt32 distance = pos; - for (UInt32 i = Base.kNumRepDistances - 1; i >= 1; i--) - _repDistances[i] = _repDistances[i - 1]; - _repDistances[0] = distance; - _matchPriceCount++; - } - _previousByte = _matchFinder.GetIndexByte((Int32)(len - 1 - _additionalOffset)); - } - _additionalOffset -= len; - nowPos64 += len; - if (_additionalOffset == 0) - { - // if (!_fastMode) - if (_matchPriceCount >= (1 << 7)) - FillDistancesPrices(); - if (_alignPriceCount >= Base.kAlignTableSize) - FillAlignPrices(); - inSize = nowPos64; - outSize = _rangeEncoder.GetProcessedSizeAdd(); - if (_matchFinder.GetNumAvailableBytes() == 0) - { - Flush((UInt32)nowPos64); - return; - } - - if (nowPos64 - progressPosValuePrev >= (1 << 12)) - { - _finished = false; - finished = false; - return; - } - } - } - } - - void ReleaseMFStream() - { - if (_matchFinder != null && _needReleaseMFStream) - { - _matchFinder.ReleaseStream(); - _needReleaseMFStream = false; - } - } - - void SetOutStream(System.IO.Stream outStream) { _rangeEncoder.SetStream(outStream); } - void ReleaseOutStream() { _rangeEncoder.ReleaseStream(); } - - void ReleaseStreams() - { - ReleaseMFStream(); - ReleaseOutStream(); - } - - void SetStreams(System.IO.Stream inStream, System.IO.Stream outStream, - Int64 inSize, Int64 outSize) - { - _inStream = inStream; - _finished = false; - Create(); - SetOutStream(outStream); - Init(); - - // if (!_fastMode) - { - FillDistancesPrices(); - FillAlignPrices(); - } - - _lenEncoder.SetTableSize(_numFastBytes + 1 - Base.kMatchMinLen); - _lenEncoder.UpdateTables((UInt32)1 << _posStateBits); - _repMatchLenEncoder.SetTableSize(_numFastBytes + 1 - Base.kMatchMinLen); - _repMatchLenEncoder.UpdateTables((UInt32)1 << _posStateBits); - - nowPos64 = 0; - } - - - public void Code(System.IO.Stream inStream, System.IO.Stream outStream, - Int64 inSize, Int64 outSize, ICodeProgress progress) - { - _needReleaseMFStream = false; - try - { - SetStreams(inStream, outStream, inSize, outSize); - while (true) - { - Int64 processedInSize; - Int64 processedOutSize; - bool finished; - CodeOneBlock(out processedInSize, out processedOutSize, out finished); - if (finished) - return; - if (progress != null) - { - progress.SetProgress(processedInSize, processedOutSize); - } - } - } - finally - { - ReleaseStreams(); - } - } - - const int kPropSize = 5; - Byte[] properties = new Byte[kPropSize]; - - public void WriteCoderProperties(System.IO.Stream outStream) - { - properties[0] = (Byte)((_posStateBits * 5 + _numLiteralPosStateBits) * 9 + _numLiteralContextBits); - for (int i = 0; i < 4; i++) - properties[1 + i] = (Byte)((_dictionarySize >> (8 * i)) & 0xFF); - outStream.Write(properties, 0, kPropSize); - } - - UInt32[] tempPrices = new UInt32[Base.kNumFullDistances]; - UInt32 _matchPriceCount; - - void FillDistancesPrices() - { - for (UInt32 i = Base.kStartPosModelIndex; i < Base.kNumFullDistances; i++) - { - UInt32 posSlot = GetPosSlot(i); - int footerBits = (int)((posSlot >> 1) - 1); - UInt32 baseVal = ((2 | (posSlot & 1)) << footerBits); - tempPrices[i] = BitTreeEncoder.ReverseGetPrice(_posEncoders, - baseVal - posSlot - 1, footerBits, i - baseVal); - } - - for (UInt32 lenToPosState = 0; lenToPosState < Base.kNumLenToPosStates; lenToPosState++) - { - UInt32 posSlot; - RangeCoder.BitTreeEncoder encoder = _posSlotEncoder[lenToPosState]; - - UInt32 st = (lenToPosState << Base.kNumPosSlotBits); - for (posSlot = 0; posSlot < _distTableSize; posSlot++) - _posSlotPrices[st + posSlot] = encoder.GetPrice(posSlot); - for (posSlot = Base.kEndPosModelIndex; posSlot < _distTableSize; posSlot++) - _posSlotPrices[st + posSlot] += ((((posSlot >> 1) - 1) - Base.kNumAlignBits) << RangeCoder.BitEncoder.kNumBitPriceShiftBits); - - UInt32 st2 = lenToPosState * Base.kNumFullDistances; - UInt32 i; - for (i = 0; i < Base.kStartPosModelIndex; i++) - _distancesPrices[st2 + i] = _posSlotPrices[st + i]; - for (; i < Base.kNumFullDistances; i++) - _distancesPrices[st2 + i] = _posSlotPrices[st + GetPosSlot(i)] + tempPrices[i]; - } - _matchPriceCount = 0; - } - - void FillAlignPrices() - { - for (UInt32 i = 0; i < Base.kAlignTableSize; i++) - _alignPrices[i] = _posAlignEncoder.ReverseGetPrice(i); - _alignPriceCount = 0; - } - - - static string[] kMatchFinderIDs = - { - "BT2", - "BT4", - }; - - static int FindMatchFinder(string s) - { - for (int m = 0; m < kMatchFinderIDs.Length; m++) - if (s == kMatchFinderIDs[m]) - return m; - return -1; - } - - public void SetCoderProperties(CoderPropID[] propIDs, object[] properties) - { - for (UInt32 i = 0; i < properties.Length; i++) - { - object prop = properties[i]; - switch (propIDs[i]) - { - case CoderPropID.NumFastBytes: - { - if (!(prop is Int32)) - throw new InvalidParamException(); - Int32 numFastBytes = (Int32)prop; - if (numFastBytes < 5 || numFastBytes > Base.kMatchMaxLen) - throw new InvalidParamException(); - _numFastBytes = (UInt32)numFastBytes; - break; - } - case CoderPropID.Algorithm: - { - /* - if (!(prop is Int32)) - throw new InvalidParamException(); - Int32 maximize = (Int32)prop; - _fastMode = (maximize == 0); - _maxMode = (maximize >= 2); - */ - break; - } - case CoderPropID.MatchFinder: - { - if (!(prop is String)) - throw new InvalidParamException(); - EMatchFinderType matchFinderIndexPrev = _matchFinderType; - int m = FindMatchFinder(((string)prop).ToUpper()); - if (m < 0) - throw new InvalidParamException(); - _matchFinderType = (EMatchFinderType)m; - if (_matchFinder != null && matchFinderIndexPrev != _matchFinderType) - { - _dictionarySizePrev = 0xFFFFFFFF; - _matchFinder = null; - } - break; - } - case CoderPropID.DictionarySize: - { - const int kDicLogSizeMaxCompress = 30; - if (!(prop is Int32)) - throw new InvalidParamException(); ; - Int32 dictionarySize = (Int32)prop; - if (dictionarySize < (UInt32)(1 << Base.kDicLogSizeMin) || - dictionarySize > (UInt32)(1 << kDicLogSizeMaxCompress)) - throw new InvalidParamException(); - _dictionarySize = (UInt32)dictionarySize; - int dicLogSize; - for (dicLogSize = 0; dicLogSize < (UInt32)kDicLogSizeMaxCompress; dicLogSize++) - if (dictionarySize <= ((UInt32)(1) << dicLogSize)) - break; - _distTableSize = (UInt32)dicLogSize * 2; - break; - } - case CoderPropID.PosStateBits: - { - if (!(prop is Int32)) - throw new InvalidParamException(); - Int32 v = (Int32)prop; - if (v < 0 || v > (UInt32)Base.kNumPosStatesBitsEncodingMax) - throw new InvalidParamException(); - _posStateBits = (int)v; - _posStateMask = (((UInt32)1) << (int)_posStateBits) - 1; - break; - } - case CoderPropID.LitPosBits: - { - if (!(prop is Int32)) - throw new InvalidParamException(); - Int32 v = (Int32)prop; - if (v < 0 || v > (UInt32)Base.kNumLitPosStatesBitsEncodingMax) - throw new InvalidParamException(); - _numLiteralPosStateBits = (int)v; - break; - } - case CoderPropID.LitContextBits: - { - if (!(prop is Int32)) - throw new InvalidParamException(); - Int32 v = (Int32)prop; - if (v < 0 || v > (UInt32)Base.kNumLitContextBitsMax) - throw new InvalidParamException(); ; - _numLiteralContextBits = (int)v; - break; - } - case CoderPropID.EndMarker: - { - if (!(prop is Boolean)) - throw new InvalidParamException(); - SetWriteEndMarkerMode((Boolean)prop); - break; - } - default: - throw new InvalidParamException(); - } - } - } - - uint _trainSize = 0; - public void SetTrainSize(uint trainSize) - { - _trainSize = trainSize; - } - - } + using RangeCoder; + + public class Encoder : ICoder, ISetCoderProperties, IWriteCoderProperties + { + enum EMatchFinderType + { + BT2, + BT4, + }; + + const UInt32 kIfinityPrice = 0xFFFFFFF; + + static Byte[] g_FastPos = new Byte[1 << 11]; + + static Encoder() + { + const Byte kFastSlots = 22; + int c = 2; + g_FastPos[0] = 0; + g_FastPos[1] = 1; + for (Byte slotFast = 2; slotFast < kFastSlots; slotFast++) + { + UInt32 k = ((UInt32)1 << ((slotFast >> 1) - 1)); + for (UInt32 j = 0; j < k; j++, c++) + g_FastPos[c] = slotFast; + } + } + + static UInt32 GetPosSlot(UInt32 pos) + { + if (pos < (1 << 11)) + return g_FastPos[pos]; + if (pos < (1 << 21)) + return (UInt32)(g_FastPos[pos >> 10] + 20); + return (UInt32)(g_FastPos[pos >> 20] + 40); + } + + static UInt32 GetPosSlot2(UInt32 pos) + { + if (pos < (1 << 17)) + return (UInt32)(g_FastPos[pos >> 6] + 12); + if (pos < (1 << 27)) + return (UInt32)(g_FastPos[pos >> 16] + 32); + return (UInt32)(g_FastPos[pos >> 26] + 52); + } + + Base.State _state = new Base.State(); + Byte _previousByte; + UInt32[] _repDistances = new UInt32[Base.kNumRepDistances]; + + void BaseInit() + { + _state.Init(); + _previousByte = 0; + for (UInt32 i = 0; i < Base.kNumRepDistances; i++) + _repDistances[i] = 0; + } + + const int kDefaultDictionaryLogSize = 22; + const UInt32 kNumFastBytesDefault = 0x20; + + class LiteralEncoder + { + public struct Encoder2 + { + BitEncoder[] m_Encoders; + + public void Create() { m_Encoders = new BitEncoder[0x300]; } + + public void Init() { for (int i = 0; i < 0x300; i++) m_Encoders[i].Init(); } + + public void Encode(RangeCoder.Encoder rangeEncoder, byte symbol) + { + uint context = 1; + for (int i = 7; i >= 0; i--) + { + uint bit = (uint)((symbol >> i) & 1); + m_Encoders[context].Encode(rangeEncoder, bit); + context = (context << 1) | bit; + } + } + + public void EncodeMatched(RangeCoder.Encoder rangeEncoder, byte matchByte, byte symbol) + { + uint context = 1; + bool same = true; + for (int i = 7; i >= 0; i--) + { + uint bit = (uint)((symbol >> i) & 1); + uint state = context; + if (same) + { + uint matchBit = (uint)((matchByte >> i) & 1); + state += ((1 + matchBit) << 8); + same = (matchBit == bit); + } + m_Encoders[state].Encode(rangeEncoder, bit); + context = (context << 1) | bit; + } + } + + public uint GetPrice(bool matchMode, byte matchByte, byte symbol) + { + uint price = 0; + uint context = 1; + int i = 7; + if (matchMode) + { + for (; i >= 0; i--) + { + uint matchBit = (uint)(matchByte >> i) & 1; + uint bit = (uint)(symbol >> i) & 1; + price += m_Encoders[((1 + matchBit) << 8) + context].GetPrice(bit); + context = (context << 1) | bit; + if (matchBit != bit) + { + i--; + break; + } + } + } + for (; i >= 0; i--) + { + uint bit = (uint)(symbol >> i) & 1; + price += m_Encoders[context].GetPrice(bit); + context = (context << 1) | bit; + } + return price; + } + } + + Encoder2[] m_Coders; + int m_NumPrevBits; + int m_NumPosBits; + uint m_PosMask; + + public void Create(int numPosBits, int numPrevBits) + { + if (m_Coders != null && m_NumPrevBits == numPrevBits && m_NumPosBits == numPosBits) + return; + m_NumPosBits = numPosBits; + m_PosMask = ((uint)1 << numPosBits) - 1; + m_NumPrevBits = numPrevBits; + uint numStates = (uint)1 << (m_NumPrevBits + m_NumPosBits); + m_Coders = new Encoder2[numStates]; + for (uint i = 0; i < numStates; i++) + m_Coders[i].Create(); + } + + public void Init() + { + uint numStates = (uint)1 << (m_NumPrevBits + m_NumPosBits); + for (uint i = 0; i < numStates; i++) + m_Coders[i].Init(); + } + + public Encoder2 GetSubCoder(UInt32 pos, Byte prevByte) + { return m_Coders[((pos & m_PosMask) << m_NumPrevBits) + (uint)(prevByte >> (8 - m_NumPrevBits))]; } + } + + class LenEncoder + { + RangeCoder.BitEncoder _choice = new RangeCoder.BitEncoder(); + RangeCoder.BitEncoder _choice2 = new RangeCoder.BitEncoder(); + RangeCoder.BitTreeEncoder[] _lowCoder = new RangeCoder.BitTreeEncoder[Base.kNumPosStatesEncodingMax]; + RangeCoder.BitTreeEncoder[] _midCoder = new RangeCoder.BitTreeEncoder[Base.kNumPosStatesEncodingMax]; + RangeCoder.BitTreeEncoder _highCoder = new RangeCoder.BitTreeEncoder(Base.kNumHighLenBits); + + public LenEncoder() + { + for (UInt32 posState = 0; posState < Base.kNumPosStatesEncodingMax; posState++) + { + _lowCoder[posState] = new RangeCoder.BitTreeEncoder(Base.kNumLowLenBits); + _midCoder[posState] = new RangeCoder.BitTreeEncoder(Base.kNumMidLenBits); + } + } + + public void Init(UInt32 numPosStates) + { + _choice.Init(); + _choice2.Init(); + for (UInt32 posState = 0; posState < numPosStates; posState++) + { + _lowCoder[posState].Init(); + _midCoder[posState].Init(); + } + _highCoder.Init(); + } + + public void Encode(RangeCoder.Encoder rangeEncoder, UInt32 symbol, UInt32 posState) + { + if (symbol < Base.kNumLowLenSymbols) + { + _choice.Encode(rangeEncoder, 0); + _lowCoder[posState].Encode(rangeEncoder, symbol); + } + else + { + symbol -= Base.kNumLowLenSymbols; + _choice.Encode(rangeEncoder, 1); + if (symbol < Base.kNumMidLenSymbols) + { + _choice2.Encode(rangeEncoder, 0); + _midCoder[posState].Encode(rangeEncoder, symbol); + } + else + { + _choice2.Encode(rangeEncoder, 1); + _highCoder.Encode(rangeEncoder, symbol - Base.kNumMidLenSymbols); + } + } + } + + public void SetPrices(UInt32 posState, UInt32 numSymbols, UInt32[] prices, UInt32 st) + { + UInt32 a0 = _choice.GetPrice0(); + UInt32 a1 = _choice.GetPrice1(); + UInt32 b0 = a1 + _choice2.GetPrice0(); + UInt32 b1 = a1 + _choice2.GetPrice1(); + UInt32 i = 0; + for (i = 0; i < Base.kNumLowLenSymbols; i++) + { + if (i >= numSymbols) + return; + prices[st + i] = a0 + _lowCoder[posState].GetPrice(i); + } + for (; i < Base.kNumLowLenSymbols + Base.kNumMidLenSymbols; i++) + { + if (i >= numSymbols) + return; + prices[st + i] = b0 + _midCoder[posState].GetPrice(i - Base.kNumLowLenSymbols); + } + for (; i < numSymbols; i++) + prices[st + i] = b1 + _highCoder.GetPrice(i - Base.kNumLowLenSymbols - Base.kNumMidLenSymbols); + } + }; + + const UInt32 kNumLenSpecSymbols = Base.kNumLowLenSymbols + Base.kNumMidLenSymbols; + + class LenPriceTableEncoder : LenEncoder + { + UInt32[] _prices = new UInt32[Base.kNumLenSymbols << Base.kNumPosStatesBitsEncodingMax]; + UInt32 _tableSize; + UInt32[] _counters = new UInt32[Base.kNumPosStatesEncodingMax]; + + public void SetTableSize(UInt32 tableSize) { _tableSize = tableSize; } + + public UInt32 GetPrice(UInt32 symbol, UInt32 posState) + { + return _prices[posState * Base.kNumLenSymbols + symbol]; + } + + void UpdateTable(UInt32 posState) + { + SetPrices(posState, _tableSize, _prices, posState * Base.kNumLenSymbols); + _counters[posState] = _tableSize; + } + + public void UpdateTables(UInt32 numPosStates) + { + for (UInt32 posState = 0; posState < numPosStates; posState++) + UpdateTable(posState); + } + + public new void Encode(RangeCoder.Encoder rangeEncoder, UInt32 symbol, UInt32 posState) + { + base.Encode(rangeEncoder, symbol, posState); + if (--_counters[posState] == 0) + UpdateTable(posState); + } + } + + const UInt32 kNumOpts = 1 << 12; + class Optimal + { + public Base.State State; + + public bool Prev1IsChar; + public bool Prev2; + + public UInt32 PosPrev2; + public UInt32 BackPrev2; + + public UInt32 Price; + public UInt32 PosPrev; + public UInt32 BackPrev; + + public UInt32 Backs0; + public UInt32 Backs1; + public UInt32 Backs2; + public UInt32 Backs3; + + public void MakeAsChar() { BackPrev = 0xFFFFFFFF; Prev1IsChar = false; } + public void MakeAsShortRep() { BackPrev = 0; ; Prev1IsChar = false; } + public bool IsShortRep() { return (BackPrev == 0); } + }; + Optimal[] _optimum = new Optimal[kNumOpts]; + LZ.IMatchFinder _matchFinder = null; + RangeCoder.Encoder _rangeEncoder = new RangeCoder.Encoder(); + + RangeCoder.BitEncoder[] _isMatch = new RangeCoder.BitEncoder[Base.kNumStates << Base.kNumPosStatesBitsMax]; + RangeCoder.BitEncoder[] _isRep = new RangeCoder.BitEncoder[Base.kNumStates]; + RangeCoder.BitEncoder[] _isRepG0 = new RangeCoder.BitEncoder[Base.kNumStates]; + RangeCoder.BitEncoder[] _isRepG1 = new RangeCoder.BitEncoder[Base.kNumStates]; + RangeCoder.BitEncoder[] _isRepG2 = new RangeCoder.BitEncoder[Base.kNumStates]; + RangeCoder.BitEncoder[] _isRep0Long = new RangeCoder.BitEncoder[Base.kNumStates << Base.kNumPosStatesBitsMax]; + + RangeCoder.BitTreeEncoder[] _posSlotEncoder = new RangeCoder.BitTreeEncoder[Base.kNumLenToPosStates]; + + RangeCoder.BitEncoder[] _posEncoders = new RangeCoder.BitEncoder[Base.kNumFullDistances - Base.kEndPosModelIndex]; + RangeCoder.BitTreeEncoder _posAlignEncoder = new RangeCoder.BitTreeEncoder(Base.kNumAlignBits); + + LenPriceTableEncoder _lenEncoder = new LenPriceTableEncoder(); + LenPriceTableEncoder _repMatchLenEncoder = new LenPriceTableEncoder(); + + LiteralEncoder _literalEncoder = new LiteralEncoder(); + + UInt32[] _matchDistances = new UInt32[Base.kMatchMaxLen * 2 + 2]; + + UInt32 _numFastBytes = kNumFastBytesDefault; + UInt32 _longestMatchLength; + UInt32 _numDistancePairs; + + UInt32 _additionalOffset; + + UInt32 _optimumEndIndex; + UInt32 _optimumCurrentIndex; + + bool _longestMatchWasFound; + + UInt32[] _posSlotPrices = new UInt32[1 << (Base.kNumPosSlotBits + Base.kNumLenToPosStatesBits)]; + UInt32[] _distancesPrices = new UInt32[Base.kNumFullDistances << Base.kNumLenToPosStatesBits]; + UInt32[] _alignPrices = new UInt32[Base.kAlignTableSize]; + UInt32 _alignPriceCount; + + UInt32 _distTableSize = (kDefaultDictionaryLogSize * 2); + + int _posStateBits = 2; + UInt32 _posStateMask = (4 - 1); + int _numLiteralPosStateBits = 0; + int _numLiteralContextBits = 3; + + UInt32 _dictionarySize = (1 << kDefaultDictionaryLogSize); + UInt32 _dictionarySizePrev = 0xFFFFFFFF; + UInt32 _numFastBytesPrev = 0xFFFFFFFF; + + Int64 nowPos64; + bool _finished; + System.IO.Stream _inStream; + + EMatchFinderType _matchFinderType = EMatchFinderType.BT4; + bool _writeEndMark = false; + + bool _needReleaseMFStream; + + void Create() + { + if (_matchFinder == null) + { + LZ.BinTree bt = new LZ.BinTree(); + int numHashBytes = 4; + if (_matchFinderType == EMatchFinderType.BT2) + numHashBytes = 2; + bt.SetType(numHashBytes); + _matchFinder = bt; + } + _literalEncoder.Create(_numLiteralPosStateBits, _numLiteralContextBits); + + if (_dictionarySize == _dictionarySizePrev && _numFastBytesPrev == _numFastBytes) + return; + _matchFinder.Create(_dictionarySize, kNumOpts, _numFastBytes, Base.kMatchMaxLen + 1); + _dictionarySizePrev = _dictionarySize; + _numFastBytesPrev = _numFastBytes; + } + + public Encoder() + { + for (int i = 0; i < kNumOpts; i++) + _optimum[i] = new Optimal(); + for (int i = 0; i < Base.kNumLenToPosStates; i++) + _posSlotEncoder[i] = new RangeCoder.BitTreeEncoder(Base.kNumPosSlotBits); + } + + void SetWriteEndMarkerMode(bool writeEndMarker) + { + _writeEndMark = writeEndMarker; + } + + void Init() + { + BaseInit(); + _rangeEncoder.Init(); + + uint i; + for (i = 0; i < Base.kNumStates; i++) + { + for (uint j = 0; j <= _posStateMask; j++) + { + uint complexState = (i << Base.kNumPosStatesBitsMax) + j; + _isMatch[complexState].Init(); + _isRep0Long[complexState].Init(); + } + _isRep[i].Init(); + _isRepG0[i].Init(); + _isRepG1[i].Init(); + _isRepG2[i].Init(); + } + _literalEncoder.Init(); + for (i = 0; i < Base.kNumLenToPosStates; i++) + _posSlotEncoder[i].Init(); + for (i = 0; i < Base.kNumFullDistances - Base.kEndPosModelIndex; i++) + _posEncoders[i].Init(); + + _lenEncoder.Init((UInt32)1 << _posStateBits); + _repMatchLenEncoder.Init((UInt32)1 << _posStateBits); + + _posAlignEncoder.Init(); + + _longestMatchWasFound = false; + _optimumEndIndex = 0; + _optimumCurrentIndex = 0; + _additionalOffset = 0; + } + + void ReadMatchDistances(out UInt32 lenRes, out UInt32 numDistancePairs) + { + lenRes = 0; + numDistancePairs = _matchFinder.GetMatches(_matchDistances); + if (numDistancePairs > 0) + { + lenRes = _matchDistances[numDistancePairs - 2]; + if (lenRes == _numFastBytes) + lenRes += _matchFinder.GetMatchLen((int)lenRes - 1, _matchDistances[numDistancePairs - 1], + Base.kMatchMaxLen - lenRes); + } + _additionalOffset++; + } + + + void MovePos(UInt32 num) + { + if (num > 0) + { + _matchFinder.Skip(num); + _additionalOffset += num; + } + } + + UInt32 GetRepLen1Price(Base.State state, UInt32 posState) + { + return _isRepG0[state.Index].GetPrice0() + + _isRep0Long[(state.Index << Base.kNumPosStatesBitsMax) + posState].GetPrice0(); + } + + UInt32 GetPureRepPrice(UInt32 repIndex, Base.State state, UInt32 posState) + { + UInt32 price; + if (repIndex == 0) + { + price = _isRepG0[state.Index].GetPrice0(); + price += _isRep0Long[(state.Index << Base.kNumPosStatesBitsMax) + posState].GetPrice1(); + } + else + { + price = _isRepG0[state.Index].GetPrice1(); + if (repIndex == 1) + price += _isRepG1[state.Index].GetPrice0(); + else + { + price += _isRepG1[state.Index].GetPrice1(); + price += _isRepG2[state.Index].GetPrice(repIndex - 2); + } + } + return price; + } + + UInt32 GetRepPrice(UInt32 repIndex, UInt32 len, Base.State state, UInt32 posState) + { + UInt32 price = _repMatchLenEncoder.GetPrice(len - Base.kMatchMinLen, posState); + return price + GetPureRepPrice(repIndex, state, posState); + } + + UInt32 GetPosLenPrice(UInt32 pos, UInt32 len, UInt32 posState) + { + UInt32 price; + UInt32 lenToPosState = Base.GetLenToPosState(len); + if (pos < Base.kNumFullDistances) + price = _distancesPrices[(lenToPosState * Base.kNumFullDistances) + pos]; + else + price = _posSlotPrices[(lenToPosState << Base.kNumPosSlotBits) + GetPosSlot2(pos)] + + _alignPrices[pos & Base.kAlignMask]; + return price + _lenEncoder.GetPrice(len - Base.kMatchMinLen, posState); + } + + UInt32 Backward(out UInt32 backRes, UInt32 cur) + { + _optimumEndIndex = cur; + UInt32 posMem = _optimum[cur].PosPrev; + UInt32 backMem = _optimum[cur].BackPrev; + do + { + if (_optimum[cur].Prev1IsChar) + { + _optimum[posMem].MakeAsChar(); + _optimum[posMem].PosPrev = posMem - 1; + if (_optimum[cur].Prev2) + { + _optimum[posMem - 1].Prev1IsChar = false; + _optimum[posMem - 1].PosPrev = _optimum[cur].PosPrev2; + _optimum[posMem - 1].BackPrev = _optimum[cur].BackPrev2; + } + } + UInt32 posPrev = posMem; + UInt32 backCur = backMem; + + backMem = _optimum[posPrev].BackPrev; + posMem = _optimum[posPrev].PosPrev; + + _optimum[posPrev].BackPrev = backCur; + _optimum[posPrev].PosPrev = cur; + cur = posPrev; + } + while (cur > 0); + backRes = _optimum[0].BackPrev; + _optimumCurrentIndex = _optimum[0].PosPrev; + return _optimumCurrentIndex; + } + + UInt32[] reps = new UInt32[Base.kNumRepDistances]; + UInt32[] repLens = new UInt32[Base.kNumRepDistances]; + + + UInt32 GetOptimum(UInt32 position, out UInt32 backRes) + { + if (_optimumEndIndex != _optimumCurrentIndex) + { + UInt32 lenRes = _optimum[_optimumCurrentIndex].PosPrev - _optimumCurrentIndex; + backRes = _optimum[_optimumCurrentIndex].BackPrev; + _optimumCurrentIndex = _optimum[_optimumCurrentIndex].PosPrev; + return lenRes; + } + _optimumCurrentIndex = _optimumEndIndex = 0; + + UInt32 lenMain, numDistancePairs; + if (!_longestMatchWasFound) + { + ReadMatchDistances(out lenMain, out numDistancePairs); + } + else + { + lenMain = _longestMatchLength; + numDistancePairs = _numDistancePairs; + _longestMatchWasFound = false; + } + + UInt32 numAvailableBytes = _matchFinder.GetNumAvailableBytes() + 1; + if (numAvailableBytes < 2) + { + backRes = 0xFFFFFFFF; + return 1; + } + if (numAvailableBytes > Base.kMatchMaxLen) + numAvailableBytes = Base.kMatchMaxLen; + + UInt32 repMaxIndex = 0; + UInt32 i; + for (i = 0; i < Base.kNumRepDistances; i++) + { + reps[i] = _repDistances[i]; + repLens[i] = _matchFinder.GetMatchLen(0 - 1, reps[i], Base.kMatchMaxLen); + if (repLens[i] > repLens[repMaxIndex]) + repMaxIndex = i; + } + if (repLens[repMaxIndex] >= _numFastBytes) + { + backRes = repMaxIndex; + UInt32 lenRes = repLens[repMaxIndex]; + MovePos(lenRes - 1); + return lenRes; + } + + if (lenMain >= _numFastBytes) + { + backRes = _matchDistances[numDistancePairs - 1] + Base.kNumRepDistances; + MovePos(lenMain - 1); + return lenMain; + } + + Byte currentByte = _matchFinder.GetIndexByte(0 - 1); + Byte matchByte = _matchFinder.GetIndexByte((Int32)(0 - _repDistances[0] - 1 - 1)); + + if (lenMain < 2 && currentByte != matchByte && repLens[repMaxIndex] < 2) + { + backRes = (UInt32)0xFFFFFFFF; + return 1; + } + + _optimum[0].State = _state; + + UInt32 posState = (position & _posStateMask); + + _optimum[1].Price = _isMatch[(_state.Index << Base.kNumPosStatesBitsMax) + posState].GetPrice0() + + _literalEncoder.GetSubCoder(position, _previousByte).GetPrice(!_state.IsCharState(), matchByte, currentByte); + _optimum[1].MakeAsChar(); + + UInt32 matchPrice = _isMatch[(_state.Index << Base.kNumPosStatesBitsMax) + posState].GetPrice1(); + UInt32 repMatchPrice = matchPrice + _isRep[_state.Index].GetPrice1(); + + if (matchByte == currentByte) + { + UInt32 shortRepPrice = repMatchPrice + GetRepLen1Price(_state, posState); + if (shortRepPrice < _optimum[1].Price) + { + _optimum[1].Price = shortRepPrice; + _optimum[1].MakeAsShortRep(); + } + } + + UInt32 lenEnd = ((lenMain >= repLens[repMaxIndex]) ? lenMain : repLens[repMaxIndex]); + + if (lenEnd < 2) + { + backRes = _optimum[1].BackPrev; + return 1; + } + + _optimum[1].PosPrev = 0; + + _optimum[0].Backs0 = reps[0]; + _optimum[0].Backs1 = reps[1]; + _optimum[0].Backs2 = reps[2]; + _optimum[0].Backs3 = reps[3]; + + UInt32 len = lenEnd; + do + _optimum[len--].Price = kIfinityPrice; + while (len >= 2); + + for (i = 0; i < Base.kNumRepDistances; i++) + { + UInt32 repLen = repLens[i]; + if (repLen < 2) + continue; + UInt32 price = repMatchPrice + GetPureRepPrice(i, _state, posState); + do + { + UInt32 curAndLenPrice = price + _repMatchLenEncoder.GetPrice(repLen - 2, posState); + Optimal optimum = _optimum[repLen]; + if (curAndLenPrice < optimum.Price) + { + optimum.Price = curAndLenPrice; + optimum.PosPrev = 0; + optimum.BackPrev = i; + optimum.Prev1IsChar = false; + } + } + while (--repLen >= 2); + } + + UInt32 normalMatchPrice = matchPrice + _isRep[_state.Index].GetPrice0(); + + len = ((repLens[0] >= 2) ? repLens[0] + 1 : 2); + if (len <= lenMain) + { + UInt32 offs = 0; + while (len > _matchDistances[offs]) + offs += 2; + for (; ; len++) + { + UInt32 distance = _matchDistances[offs + 1]; + UInt32 curAndLenPrice = normalMatchPrice + GetPosLenPrice(distance, len, posState); + Optimal optimum = _optimum[len]; + if (curAndLenPrice < optimum.Price) + { + optimum.Price = curAndLenPrice; + optimum.PosPrev = 0; + optimum.BackPrev = distance + Base.kNumRepDistances; + optimum.Prev1IsChar = false; + } + if (len == _matchDistances[offs]) + { + offs += 2; + if (offs == numDistancePairs) + break; + } + } + } + + UInt32 cur = 0; + + while (true) + { + cur++; + if (cur == lenEnd) + return Backward(out backRes, cur); + UInt32 newLen; + ReadMatchDistances(out newLen, out numDistancePairs); + if (newLen >= _numFastBytes) + { + _numDistancePairs = numDistancePairs; + _longestMatchLength = newLen; + _longestMatchWasFound = true; + return Backward(out backRes, cur); + } + position++; + UInt32 posPrev = _optimum[cur].PosPrev; + Base.State state; + if (_optimum[cur].Prev1IsChar) + { + posPrev--; + if (_optimum[cur].Prev2) + { + state = _optimum[_optimum[cur].PosPrev2].State; + if (_optimum[cur].BackPrev2 < Base.kNumRepDistances) + state.UpdateRep(); + else + state.UpdateMatch(); + } + else + state = _optimum[posPrev].State; + state.UpdateChar(); + } + else + state = _optimum[posPrev].State; + if (posPrev == cur - 1) + { + if (_optimum[cur].IsShortRep()) + state.UpdateShortRep(); + else + state.UpdateChar(); + } + else + { + UInt32 pos; + if (_optimum[cur].Prev1IsChar && _optimum[cur].Prev2) + { + posPrev = _optimum[cur].PosPrev2; + pos = _optimum[cur].BackPrev2; + state.UpdateRep(); + } + else + { + pos = _optimum[cur].BackPrev; + if (pos < Base.kNumRepDistances) + state.UpdateRep(); + else + state.UpdateMatch(); + } + Optimal opt = _optimum[posPrev]; + if (pos < Base.kNumRepDistances) + { + if (pos == 0) + { + reps[0] = opt.Backs0; + reps[1] = opt.Backs1; + reps[2] = opt.Backs2; + reps[3] = opt.Backs3; + } + else if (pos == 1) + { + reps[0] = opt.Backs1; + reps[1] = opt.Backs0; + reps[2] = opt.Backs2; + reps[3] = opt.Backs3; + } + else if (pos == 2) + { + reps[0] = opt.Backs2; + reps[1] = opt.Backs0; + reps[2] = opt.Backs1; + reps[3] = opt.Backs3; + } + else + { + reps[0] = opt.Backs3; + reps[1] = opt.Backs0; + reps[2] = opt.Backs1; + reps[3] = opt.Backs2; + } + } + else + { + reps[0] = (pos - Base.kNumRepDistances); + reps[1] = opt.Backs0; + reps[2] = opt.Backs1; + reps[3] = opt.Backs2; + } + } + _optimum[cur].State = state; + _optimum[cur].Backs0 = reps[0]; + _optimum[cur].Backs1 = reps[1]; + _optimum[cur].Backs2 = reps[2]; + _optimum[cur].Backs3 = reps[3]; + UInt32 curPrice = _optimum[cur].Price; + + currentByte = _matchFinder.GetIndexByte(0 - 1); + matchByte = _matchFinder.GetIndexByte((Int32)(0 - reps[0] - 1 - 1)); + + posState = (position & _posStateMask); + + UInt32 curAnd1Price = curPrice + + _isMatch[(state.Index << Base.kNumPosStatesBitsMax) + posState].GetPrice0() + + _literalEncoder.GetSubCoder(position, _matchFinder.GetIndexByte(0 - 2)). + GetPrice(!state.IsCharState(), matchByte, currentByte); + + Optimal nextOptimum = _optimum[cur + 1]; + + bool nextIsChar = false; + if (curAnd1Price < nextOptimum.Price) + { + nextOptimum.Price = curAnd1Price; + nextOptimum.PosPrev = cur; + nextOptimum.MakeAsChar(); + nextIsChar = true; + } + + matchPrice = curPrice + _isMatch[(state.Index << Base.kNumPosStatesBitsMax) + posState].GetPrice1(); + repMatchPrice = matchPrice + _isRep[state.Index].GetPrice1(); + + if (matchByte == currentByte && + !(nextOptimum.PosPrev < cur && nextOptimum.BackPrev == 0)) + { + UInt32 shortRepPrice = repMatchPrice + GetRepLen1Price(state, posState); + if (shortRepPrice <= nextOptimum.Price) + { + nextOptimum.Price = shortRepPrice; + nextOptimum.PosPrev = cur; + nextOptimum.MakeAsShortRep(); + nextIsChar = true; + } + } + + UInt32 numAvailableBytesFull = _matchFinder.GetNumAvailableBytes() + 1; + numAvailableBytesFull = Math.Min(kNumOpts - 1 - cur, numAvailableBytesFull); + numAvailableBytes = numAvailableBytesFull; + + if (numAvailableBytes < 2) + continue; + if (numAvailableBytes > _numFastBytes) + numAvailableBytes = _numFastBytes; + if (!nextIsChar && matchByte != currentByte) + { + // try Literal + rep0 + UInt32 t = Math.Min(numAvailableBytesFull - 1, _numFastBytes); + UInt32 lenTest2 = _matchFinder.GetMatchLen(0, reps[0], t); + if (lenTest2 >= 2) + { + Base.State state2 = state; + state2.UpdateChar(); + UInt32 posStateNext = (position + 1) & _posStateMask; + UInt32 nextRepMatchPrice = curAnd1Price + + _isMatch[(state2.Index << Base.kNumPosStatesBitsMax) + posStateNext].GetPrice1() + + _isRep[state2.Index].GetPrice1(); + { + UInt32 offset = cur + 1 + lenTest2; + while (lenEnd < offset) + _optimum[++lenEnd].Price = kIfinityPrice; + UInt32 curAndLenPrice = nextRepMatchPrice + GetRepPrice( + 0, lenTest2, state2, posStateNext); + Optimal optimum = _optimum[offset]; + if (curAndLenPrice < optimum.Price) + { + optimum.Price = curAndLenPrice; + optimum.PosPrev = cur + 1; + optimum.BackPrev = 0; + optimum.Prev1IsChar = true; + optimum.Prev2 = false; + } + } + } + } + + UInt32 startLen = 2; // speed optimization + + for (UInt32 repIndex = 0; repIndex < Base.kNumRepDistances; repIndex++) + { + UInt32 lenTest = _matchFinder.GetMatchLen(0 - 1, reps[repIndex], numAvailableBytes); + if (lenTest < 2) + continue; + UInt32 lenTestTemp = lenTest; + do + { + while (lenEnd < cur + lenTest) + _optimum[++lenEnd].Price = kIfinityPrice; + UInt32 curAndLenPrice = repMatchPrice + GetRepPrice(repIndex, lenTest, state, posState); + Optimal optimum = _optimum[cur + lenTest]; + if (curAndLenPrice < optimum.Price) + { + optimum.Price = curAndLenPrice; + optimum.PosPrev = cur; + optimum.BackPrev = repIndex; + optimum.Prev1IsChar = false; + } + } + while (--lenTest >= 2); + lenTest = lenTestTemp; + + if (repIndex == 0) + startLen = lenTest + 1; + + // if (_maxMode) + if (lenTest < numAvailableBytesFull) + { + UInt32 t = Math.Min(numAvailableBytesFull - 1 - lenTest, _numFastBytes); + UInt32 lenTest2 = _matchFinder.GetMatchLen((Int32)lenTest, reps[repIndex], t); + if (lenTest2 >= 2) + { + Base.State state2 = state; + state2.UpdateRep(); + UInt32 posStateNext = (position + lenTest) & _posStateMask; + UInt32 curAndLenCharPrice = + repMatchPrice + GetRepPrice(repIndex, lenTest, state, posState) + + _isMatch[(state2.Index << Base.kNumPosStatesBitsMax) + posStateNext].GetPrice0() + + _literalEncoder.GetSubCoder(position + lenTest, + _matchFinder.GetIndexByte((Int32)lenTest - 1 - 1)).GetPrice(true, + _matchFinder.GetIndexByte((Int32)((Int32)lenTest - 1 - (Int32)(reps[repIndex] + 1))), + _matchFinder.GetIndexByte((Int32)lenTest - 1)); + state2.UpdateChar(); + posStateNext = (position + lenTest + 1) & _posStateMask; + UInt32 nextMatchPrice = curAndLenCharPrice + _isMatch[(state2.Index << Base.kNumPosStatesBitsMax) + posStateNext].GetPrice1(); + UInt32 nextRepMatchPrice = nextMatchPrice + _isRep[state2.Index].GetPrice1(); + + // for(; lenTest2 >= 2; lenTest2--) + { + UInt32 offset = lenTest + 1 + lenTest2; + while (lenEnd < cur + offset) + _optimum[++lenEnd].Price = kIfinityPrice; + UInt32 curAndLenPrice = nextRepMatchPrice + GetRepPrice(0, lenTest2, state2, posStateNext); + Optimal optimum = _optimum[cur + offset]; + if (curAndLenPrice < optimum.Price) + { + optimum.Price = curAndLenPrice; + optimum.PosPrev = cur + lenTest + 1; + optimum.BackPrev = 0; + optimum.Prev1IsChar = true; + optimum.Prev2 = true; + optimum.PosPrev2 = cur; + optimum.BackPrev2 = repIndex; + } + } + } + } + } + + if (newLen > numAvailableBytes) + { + newLen = numAvailableBytes; + for (numDistancePairs = 0; newLen > _matchDistances[numDistancePairs]; numDistancePairs += 2) ; + _matchDistances[numDistancePairs] = newLen; + numDistancePairs += 2; + } + if (newLen >= startLen) + { + normalMatchPrice = matchPrice + _isRep[state.Index].GetPrice0(); + while (lenEnd < cur + newLen) + _optimum[++lenEnd].Price = kIfinityPrice; + + UInt32 offs = 0; + while (startLen > _matchDistances[offs]) + offs += 2; + + for (UInt32 lenTest = startLen; ; lenTest++) + { + UInt32 curBack = _matchDistances[offs + 1]; + UInt32 curAndLenPrice = normalMatchPrice + GetPosLenPrice(curBack, lenTest, posState); + Optimal optimum = _optimum[cur + lenTest]; + if (curAndLenPrice < optimum.Price) + { + optimum.Price = curAndLenPrice; + optimum.PosPrev = cur; + optimum.BackPrev = curBack + Base.kNumRepDistances; + optimum.Prev1IsChar = false; + } + + if (lenTest == _matchDistances[offs]) + { + if (lenTest < numAvailableBytesFull) + { + UInt32 t = Math.Min(numAvailableBytesFull - 1 - lenTest, _numFastBytes); + UInt32 lenTest2 = _matchFinder.GetMatchLen((Int32)lenTest, curBack, t); + if (lenTest2 >= 2) + { + Base.State state2 = state; + state2.UpdateMatch(); + UInt32 posStateNext = (position + lenTest) & _posStateMask; + UInt32 curAndLenCharPrice = curAndLenPrice + + _isMatch[(state2.Index << Base.kNumPosStatesBitsMax) + posStateNext].GetPrice0() + + _literalEncoder.GetSubCoder(position + lenTest, + _matchFinder.GetIndexByte((Int32)lenTest - 1 - 1)). + GetPrice(true, + _matchFinder.GetIndexByte((Int32)lenTest - (Int32)(curBack + 1) - 1), + _matchFinder.GetIndexByte((Int32)lenTest - 1)); + state2.UpdateChar(); + posStateNext = (position + lenTest + 1) & _posStateMask; + UInt32 nextMatchPrice = curAndLenCharPrice + _isMatch[(state2.Index << Base.kNumPosStatesBitsMax) + posStateNext].GetPrice1(); + UInt32 nextRepMatchPrice = nextMatchPrice + _isRep[state2.Index].GetPrice1(); + + UInt32 offset = lenTest + 1 + lenTest2; + while (lenEnd < cur + offset) + _optimum[++lenEnd].Price = kIfinityPrice; + curAndLenPrice = nextRepMatchPrice + GetRepPrice(0, lenTest2, state2, posStateNext); + optimum = _optimum[cur + offset]; + if (curAndLenPrice < optimum.Price) + { + optimum.Price = curAndLenPrice; + optimum.PosPrev = cur + lenTest + 1; + optimum.BackPrev = 0; + optimum.Prev1IsChar = true; + optimum.Prev2 = true; + optimum.PosPrev2 = cur; + optimum.BackPrev2 = curBack + Base.kNumRepDistances; + } + } + } + offs += 2; + if (offs == numDistancePairs) + break; + } + } + } + } + } + + bool ChangePair(UInt32 smallDist, UInt32 bigDist) + { + const int kDif = 7; + return (smallDist < ((UInt32)(1) << (32 - kDif)) && bigDist >= (smallDist << kDif)); + } + + void WriteEndMarker(UInt32 posState) + { + if (!_writeEndMark) + return; + + _isMatch[(_state.Index << Base.kNumPosStatesBitsMax) + posState].Encode(_rangeEncoder, 1); + _isRep[_state.Index].Encode(_rangeEncoder, 0); + _state.UpdateMatch(); + UInt32 len = Base.kMatchMinLen; + _lenEncoder.Encode(_rangeEncoder, len - Base.kMatchMinLen, posState); + UInt32 posSlot = (1 << Base.kNumPosSlotBits) - 1; + UInt32 lenToPosState = Base.GetLenToPosState(len); + _posSlotEncoder[lenToPosState].Encode(_rangeEncoder, posSlot); + int footerBits = 30; + UInt32 posReduced = (((UInt32)1) << footerBits) - 1; + _rangeEncoder.EncodeDirectBits(posReduced >> Base.kNumAlignBits, footerBits - Base.kNumAlignBits); + _posAlignEncoder.ReverseEncode(_rangeEncoder, posReduced & Base.kAlignMask); + } + + void Flush(UInt32 nowPos) + { + ReleaseMFStream(); + WriteEndMarker(nowPos & _posStateMask); + _rangeEncoder.FlushData(); + _rangeEncoder.FlushStream(); + } + + public void CodeOneBlock(out Int64 inSize, out Int64 outSize, out bool finished) + { + inSize = 0; + outSize = 0; + finished = true; + + if (_inStream != null) + { + _matchFinder.SetStream(_inStream); + _matchFinder.Init(); + _needReleaseMFStream = true; + _inStream = null; + if (_trainSize > 0) + _matchFinder.Skip(_trainSize); + } + + if (_finished) + return; + _finished = true; + + + Int64 progressPosValuePrev = nowPos64; + if (nowPos64 == 0) + { + if (_matchFinder.GetNumAvailableBytes() == 0) + { + Flush((UInt32)nowPos64); + return; + } + UInt32 len, numDistancePairs; // it's not used + ReadMatchDistances(out len, out numDistancePairs); + UInt32 posState = (UInt32)(nowPos64) & _posStateMask; + _isMatch[(_state.Index << Base.kNumPosStatesBitsMax) + posState].Encode(_rangeEncoder, 0); + _state.UpdateChar(); + Byte curByte = _matchFinder.GetIndexByte((Int32)(0 - _additionalOffset)); + _literalEncoder.GetSubCoder((UInt32)(nowPos64), _previousByte).Encode(_rangeEncoder, curByte); + _previousByte = curByte; + _additionalOffset--; + nowPos64++; + } + if (_matchFinder.GetNumAvailableBytes() == 0) + { + Flush((UInt32)nowPos64); + return; + } + while (true) + { + UInt32 pos; + UInt32 len = GetOptimum((UInt32)nowPos64, out pos); + + UInt32 posState = ((UInt32)nowPos64) & _posStateMask; + UInt32 complexState = (_state.Index << Base.kNumPosStatesBitsMax) + posState; + if (len == 1 && pos == 0xFFFFFFFF) + { + _isMatch[complexState].Encode(_rangeEncoder, 0); + Byte curByte = _matchFinder.GetIndexByte((Int32)(0 - _additionalOffset)); + LiteralEncoder.Encoder2 subCoder = _literalEncoder.GetSubCoder((UInt32)nowPos64, _previousByte); + if (!_state.IsCharState()) + { + Byte matchByte = _matchFinder.GetIndexByte((Int32)(0 - _repDistances[0] - 1 - _additionalOffset)); + subCoder.EncodeMatched(_rangeEncoder, matchByte, curByte); + } + else + subCoder.Encode(_rangeEncoder, curByte); + _previousByte = curByte; + _state.UpdateChar(); + } + else + { + _isMatch[complexState].Encode(_rangeEncoder, 1); + if (pos < Base.kNumRepDistances) + { + _isRep[_state.Index].Encode(_rangeEncoder, 1); + if (pos == 0) + { + _isRepG0[_state.Index].Encode(_rangeEncoder, 0); + if (len == 1) + _isRep0Long[complexState].Encode(_rangeEncoder, 0); + else + _isRep0Long[complexState].Encode(_rangeEncoder, 1); + } + else + { + _isRepG0[_state.Index].Encode(_rangeEncoder, 1); + if (pos == 1) + _isRepG1[_state.Index].Encode(_rangeEncoder, 0); + else + { + _isRepG1[_state.Index].Encode(_rangeEncoder, 1); + _isRepG2[_state.Index].Encode(_rangeEncoder, pos - 2); + } + } + if (len == 1) + _state.UpdateShortRep(); + else + { + _repMatchLenEncoder.Encode(_rangeEncoder, len - Base.kMatchMinLen, posState); + _state.UpdateRep(); + } + UInt32 distance = _repDistances[pos]; + if (pos != 0) + { + for (UInt32 i = pos; i >= 1; i--) + _repDistances[i] = _repDistances[i - 1]; + _repDistances[0] = distance; + } + } + else + { + _isRep[_state.Index].Encode(_rangeEncoder, 0); + _state.UpdateMatch(); + _lenEncoder.Encode(_rangeEncoder, len - Base.kMatchMinLen, posState); + pos -= Base.kNumRepDistances; + UInt32 posSlot = GetPosSlot(pos); + UInt32 lenToPosState = Base.GetLenToPosState(len); + _posSlotEncoder[lenToPosState].Encode(_rangeEncoder, posSlot); + + if (posSlot >= Base.kStartPosModelIndex) + { + int footerBits = (int)((posSlot >> 1) - 1); + UInt32 baseVal = ((2 | (posSlot & 1)) << footerBits); + UInt32 posReduced = pos - baseVal; + + if (posSlot < Base.kEndPosModelIndex) + RangeCoder.BitTreeEncoder.ReverseEncode(_posEncoders, + baseVal - posSlot - 1, _rangeEncoder, footerBits, posReduced); + else + { + _rangeEncoder.EncodeDirectBits(posReduced >> Base.kNumAlignBits, footerBits - Base.kNumAlignBits); + _posAlignEncoder.ReverseEncode(_rangeEncoder, posReduced & Base.kAlignMask); + _alignPriceCount++; + } + } + UInt32 distance = pos; + for (UInt32 i = Base.kNumRepDistances - 1; i >= 1; i--) + _repDistances[i] = _repDistances[i - 1]; + _repDistances[0] = distance; + _matchPriceCount++; + } + _previousByte = _matchFinder.GetIndexByte((Int32)(len - 1 - _additionalOffset)); + } + _additionalOffset -= len; + nowPos64 += len; + if (_additionalOffset == 0) + { + // if (!_fastMode) + if (_matchPriceCount >= (1 << 7)) + FillDistancesPrices(); + if (_alignPriceCount >= Base.kAlignTableSize) + FillAlignPrices(); + inSize = nowPos64; + outSize = _rangeEncoder.GetProcessedSizeAdd(); + if (_matchFinder.GetNumAvailableBytes() == 0) + { + Flush((UInt32)nowPos64); + return; + } + + if (nowPos64 - progressPosValuePrev >= (1 << 12)) + { + _finished = false; + finished = false; + return; + } + } + } + } + + void ReleaseMFStream() + { + if (_matchFinder != null && _needReleaseMFStream) + { + _matchFinder.ReleaseStream(); + _needReleaseMFStream = false; + } + } + + void SetOutStream(System.IO.Stream outStream) { _rangeEncoder.SetStream(outStream); } + void ReleaseOutStream() { _rangeEncoder.ReleaseStream(); } + + void ReleaseStreams() + { + ReleaseMFStream(); + ReleaseOutStream(); + } + + void SetStreams(System.IO.Stream inStream, System.IO.Stream outStream, + Int64 inSize, Int64 outSize) + { + _inStream = inStream; + _finished = false; + Create(); + SetOutStream(outStream); + Init(); + + // if (!_fastMode) + { + FillDistancesPrices(); + FillAlignPrices(); + } + + _lenEncoder.SetTableSize(_numFastBytes + 1 - Base.kMatchMinLen); + _lenEncoder.UpdateTables((UInt32)1 << _posStateBits); + _repMatchLenEncoder.SetTableSize(_numFastBytes + 1 - Base.kMatchMinLen); + _repMatchLenEncoder.UpdateTables((UInt32)1 << _posStateBits); + + nowPos64 = 0; + } + + + public void Code(System.IO.Stream inStream, System.IO.Stream outStream, + Int64 inSize, Int64 outSize, ICodeProgress progress) + { + _needReleaseMFStream = false; + try + { + SetStreams(inStream, outStream, inSize, outSize); + while (true) + { + Int64 processedInSize; + Int64 processedOutSize; + bool finished; + CodeOneBlock(out processedInSize, out processedOutSize, out finished); + if (finished) + return; + if (progress != null) + { + progress.SetProgress(processedInSize, processedOutSize); + } + } + } + finally + { + ReleaseStreams(); + } + } + + const int kPropSize = 5; + Byte[] properties = new Byte[kPropSize]; + + public void WriteCoderProperties(System.IO.Stream outStream) + { + properties[0] = (Byte)((_posStateBits * 5 + _numLiteralPosStateBits) * 9 + _numLiteralContextBits); + for (int i = 0; i < 4; i++) + properties[1 + i] = (Byte)((_dictionarySize >> (8 * i)) & 0xFF); + outStream.Write(properties, 0, kPropSize); + } + + UInt32[] tempPrices = new UInt32[Base.kNumFullDistances]; + UInt32 _matchPriceCount; + + void FillDistancesPrices() + { + for (UInt32 i = Base.kStartPosModelIndex; i < Base.kNumFullDistances; i++) + { + UInt32 posSlot = GetPosSlot(i); + int footerBits = (int)((posSlot >> 1) - 1); + UInt32 baseVal = ((2 | (posSlot & 1)) << footerBits); + tempPrices[i] = BitTreeEncoder.ReverseGetPrice(_posEncoders, + baseVal - posSlot - 1, footerBits, i - baseVal); + } + + for (UInt32 lenToPosState = 0; lenToPosState < Base.kNumLenToPosStates; lenToPosState++) + { + UInt32 posSlot; + RangeCoder.BitTreeEncoder encoder = _posSlotEncoder[lenToPosState]; + + UInt32 st = (lenToPosState << Base.kNumPosSlotBits); + for (posSlot = 0; posSlot < _distTableSize; posSlot++) + _posSlotPrices[st + posSlot] = encoder.GetPrice(posSlot); + for (posSlot = Base.kEndPosModelIndex; posSlot < _distTableSize; posSlot++) + _posSlotPrices[st + posSlot] += ((((posSlot >> 1) - 1) - Base.kNumAlignBits) << RangeCoder.BitEncoder.kNumBitPriceShiftBits); + + UInt32 st2 = lenToPosState * Base.kNumFullDistances; + UInt32 i; + for (i = 0; i < Base.kStartPosModelIndex; i++) + _distancesPrices[st2 + i] = _posSlotPrices[st + i]; + for (; i < Base.kNumFullDistances; i++) + _distancesPrices[st2 + i] = _posSlotPrices[st + GetPosSlot(i)] + tempPrices[i]; + } + _matchPriceCount = 0; + } + + void FillAlignPrices() + { + for (UInt32 i = 0; i < Base.kAlignTableSize; i++) + _alignPrices[i] = _posAlignEncoder.ReverseGetPrice(i); + _alignPriceCount = 0; + } + + + static string[] kMatchFinderIDs = + { + "BT2", + "BT4", + }; + + static int FindMatchFinder(string s) + { + for (int m = 0; m < kMatchFinderIDs.Length; m++) + if (s == kMatchFinderIDs[m]) + return m; + return -1; + } + + public void SetCoderProperties(CoderPropID[] propIDs, object[] properties) + { + for (UInt32 i = 0; i < properties.Length; i++) + { + object prop = properties[i]; + switch (propIDs[i]) + { + case CoderPropID.NumFastBytes: + { + if (!(prop is Int32)) + throw new InvalidParamException(); + Int32 numFastBytes = (Int32)prop; + if (numFastBytes < 5 || numFastBytes > Base.kMatchMaxLen) + throw new InvalidParamException(); + _numFastBytes = (UInt32)numFastBytes; + break; + } + case CoderPropID.Algorithm: + { + /* + if (!(prop is Int32)) + throw new InvalidParamException(); + Int32 maximize = (Int32)prop; + _fastMode = (maximize == 0); + _maxMode = (maximize >= 2); + */ + break; + } + case CoderPropID.MatchFinder: + { + if (!(prop is String)) + throw new InvalidParamException(); + EMatchFinderType matchFinderIndexPrev = _matchFinderType; + int m = FindMatchFinder(((string)prop).ToUpper()); + if (m < 0) + throw new InvalidParamException(); + _matchFinderType = (EMatchFinderType)m; + if (_matchFinder != null && matchFinderIndexPrev != _matchFinderType) + { + _dictionarySizePrev = 0xFFFFFFFF; + _matchFinder = null; + } + break; + } + case CoderPropID.DictionarySize: + { + const int kDicLogSizeMaxCompress = 30; + if (!(prop is Int32)) + throw new InvalidParamException(); ; + Int32 dictionarySize = (Int32)prop; + if (dictionarySize < (UInt32)(1 << Base.kDicLogSizeMin) || + dictionarySize > (UInt32)(1 << kDicLogSizeMaxCompress)) + throw new InvalidParamException(); + _dictionarySize = (UInt32)dictionarySize; + int dicLogSize; + for (dicLogSize = 0; dicLogSize < (UInt32)kDicLogSizeMaxCompress; dicLogSize++) + if (dictionarySize <= ((UInt32)(1) << dicLogSize)) + break; + _distTableSize = (UInt32)dicLogSize * 2; + break; + } + case CoderPropID.PosStateBits: + { + if (!(prop is Int32)) + throw new InvalidParamException(); + Int32 v = (Int32)prop; + if (v < 0 || v > (UInt32)Base.kNumPosStatesBitsEncodingMax) + throw new InvalidParamException(); + _posStateBits = (int)v; + _posStateMask = (((UInt32)1) << (int)_posStateBits) - 1; + break; + } + case CoderPropID.LitPosBits: + { + if (!(prop is Int32)) + throw new InvalidParamException(); + Int32 v = (Int32)prop; + if (v < 0 || v > (UInt32)Base.kNumLitPosStatesBitsEncodingMax) + throw new InvalidParamException(); + _numLiteralPosStateBits = (int)v; + break; + } + case CoderPropID.LitContextBits: + { + if (!(prop is Int32)) + throw new InvalidParamException(); + Int32 v = (Int32)prop; + if (v < 0 || v > (UInt32)Base.kNumLitContextBitsMax) + throw new InvalidParamException(); ; + _numLiteralContextBits = (int)v; + break; + } + case CoderPropID.EndMarker: + { + if (!(prop is Boolean)) + throw new InvalidParamException(); + SetWriteEndMarkerMode((Boolean)prop); + break; + } + default: + throw new InvalidParamException(); + } + } + } + + uint _trainSize = 0; + public void SetTrainSize(uint trainSize) + { + _trainSize = trainSize; + } + + } } diff --git a/7zip/Compress/RangeCoder/RangeCoder.cs b/7zip/Compress/RangeCoder/RangeCoder.cs index 4ced247..bf78c3b 100644 --- a/7zip/Compress/RangeCoder/RangeCoder.cs +++ b/7zip/Compress/RangeCoder/RangeCoder.cs @@ -2,192 +2,192 @@ using System; namespace SevenZip.Compression.RangeCoder { - class Encoder - { - public const uint kTopValue = (1 << 24); + class Encoder + { + public const uint kTopValue = (1 << 24); - System.IO.Stream Stream; + System.IO.Stream Stream; - public UInt64 Low; - public uint Range; - uint _cacheSize; - byte _cache; + public UInt64 Low; + public uint Range; + uint _cacheSize; + byte _cache; - long StartPosition; + long StartPosition; - public void SetStream(System.IO.Stream stream) - { - Stream = stream; - } + public void SetStream(System.IO.Stream stream) + { + Stream = stream; + } - public void ReleaseStream() - { - Stream = null; - } + public void ReleaseStream() + { + Stream = null; + } - public void Init() - { - StartPosition = Stream.Position; + public void Init() + { + StartPosition = Stream.Position; - Low = 0; - Range = 0xFFFFFFFF; - _cacheSize = 1; - _cache = 0; - } + Low = 0; + Range = 0xFFFFFFFF; + _cacheSize = 1; + _cache = 0; + } - public void FlushData() - { - for (int i = 0; i < 5; i++) - ShiftLow(); - } + public void FlushData() + { + for (int i = 0; i < 5; i++) + ShiftLow(); + } - public void FlushStream() - { - Stream.Flush(); - } + public void FlushStream() + { + Stream.Flush(); + } - public void CloseStream() - { - Stream.Close(); - } + public void CloseStream() + { + Stream.Close(); + } - public void Encode(uint start, uint size, uint total) - { - Low += start * (Range /= total); - Range *= size; - while (Range < kTopValue) - { - Range <<= 8; - ShiftLow(); - } - } + public void Encode(uint start, uint size, uint total) + { + Low += start * (Range /= total); + Range *= size; + while (Range < kTopValue) + { + Range <<= 8; + ShiftLow(); + } + } - public void ShiftLow() - { - if ((uint)Low < (uint)0xFF000000 || (uint)(Low >> 32) == 1) - { - byte temp = _cache; - do - { - Stream.WriteByte((byte)(temp + (Low >> 32))); - temp = 0xFF; - } - while (--_cacheSize != 0); - _cache = (byte)(((uint)Low) >> 24); - } - _cacheSize++; - Low = ((uint)Low) << 8; - } + public void ShiftLow() + { + if ((uint)Low < (uint)0xFF000000 || (uint)(Low >> 32) == 1) + { + byte temp = _cache; + do + { + Stream.WriteByte((byte)(temp + (Low >> 32))); + temp = 0xFF; + } + while (--_cacheSize != 0); + _cache = (byte)(((uint)Low) >> 24); + } + _cacheSize++; + Low = ((uint)Low) << 8; + } - public void EncodeDirectBits(uint v, int numTotalBits) - { - for (int i = numTotalBits - 1; i >= 0; i--) - { - Range >>= 1; - if (((v >> i) & 1) == 1) - Low += Range; - if (Range < kTopValue) - { - Range <<= 8; - ShiftLow(); - } - } - } + public void EncodeDirectBits(uint v, int numTotalBits) + { + for (int i = numTotalBits - 1; i >= 0; i--) + { + Range >>= 1; + if (((v >> i) & 1) == 1) + Low += Range; + if (Range < kTopValue) + { + Range <<= 8; + ShiftLow(); + } + } + } - public void EncodeBit(uint size0, int numTotalBits, uint symbol) - { - uint newBound = (Range >> numTotalBits) * size0; - if (symbol == 0) - Range = newBound; - else - { - Low += newBound; - Range -= newBound; - } - while (Range < kTopValue) - { - Range <<= 8; - ShiftLow(); - } - } + public void EncodeBit(uint size0, int numTotalBits, uint symbol) + { + uint newBound = (Range >> numTotalBits) * size0; + if (symbol == 0) + Range = newBound; + else + { + Low += newBound; + Range -= newBound; + } + while (Range < kTopValue) + { + Range <<= 8; + ShiftLow(); + } + } - public long GetProcessedSizeAdd() - { - return _cacheSize + - Stream.Position - StartPosition + 4; - // (long)Stream.GetProcessedSize(); - } - } + public long GetProcessedSizeAdd() + { + return _cacheSize + + Stream.Position - StartPosition + 4; + // (long)Stream.GetProcessedSize(); + } + } - class Decoder - { - public const uint kTopValue = (1 << 24); - public uint Range; - public uint Code; - // public Buffer.InBuffer Stream = new Buffer.InBuffer(1 << 16); - public System.IO.Stream Stream; + class Decoder + { + public const uint kTopValue = (1 << 24); + public uint Range; + public uint Code; + // public Buffer.InBuffer Stream = new Buffer.InBuffer(1 << 16); + public System.IO.Stream Stream; - public void Init(System.IO.Stream stream) - { - // Stream.Init(stream); - Stream = stream; + public void Init(System.IO.Stream stream) + { + // Stream.Init(stream); + Stream = stream; - Code = 0; - Range = 0xFFFFFFFF; - for (int i = 0; i < 5; i++) - Code = (Code << 8) | (byte)Stream.ReadByte(); - } + Code = 0; + Range = 0xFFFFFFFF; + for (int i = 0; i < 5; i++) + Code = (Code << 8) | (byte)Stream.ReadByte(); + } - public void ReleaseStream() - { - // Stream.ReleaseStream(); - Stream = null; - } + public void ReleaseStream() + { + // Stream.ReleaseStream(); + Stream = null; + } - public void CloseStream() - { - Stream.Close(); - } + public void CloseStream() + { + Stream.Close(); + } - public void Normalize() - { - while (Range < kTopValue) - { - Code = (Code << 8) | (byte)Stream.ReadByte(); - Range <<= 8; - } - } + public void Normalize() + { + while (Range < kTopValue) + { + Code = (Code << 8) | (byte)Stream.ReadByte(); + Range <<= 8; + } + } - public void Normalize2() - { - if (Range < kTopValue) - { - Code = (Code << 8) | (byte)Stream.ReadByte(); - Range <<= 8; - } - } + public void Normalize2() + { + if (Range < kTopValue) + { + Code = (Code << 8) | (byte)Stream.ReadByte(); + Range <<= 8; + } + } - public uint GetThreshold(uint total) - { - return Code / (Range /= total); - } + public uint GetThreshold(uint total) + { + return Code / (Range /= total); + } - public void Decode(uint start, uint size, uint total) - { - Code -= start * Range; - Range *= size; - Normalize(); - } + public void Decode(uint start, uint size, uint total) + { + Code -= start * Range; + Range *= size; + Normalize(); + } - public uint DecodeDirectBits(int numTotalBits) - { - uint range = Range; - uint code = Code; - uint result = 0; - for (int i = numTotalBits; i > 0; i--) - { - range >>= 1; - /* + public uint DecodeDirectBits(int numTotalBits) + { + uint range = Range; + uint code = Code; + uint result = 0; + for (int i = numTotalBits; i > 0; i--) + { + range >>= 1; + /* result <<= 1; if (code >= range) { @@ -195,40 +195,40 @@ namespace SevenZip.Compression.RangeCoder result |= 1; } */ - uint t = (code - range) >> 31; - code -= range & (t - 1); - result = (result << 1) | (1 - t); + uint t = (code - range) >> 31; + code -= range & (t - 1); + result = (result << 1) | (1 - t); - if (range < kTopValue) - { - code = (code << 8) | (byte)Stream.ReadByte(); - range <<= 8; - } - } - Range = range; - Code = code; - return result; - } + if (range < kTopValue) + { + code = (code << 8) | (byte)Stream.ReadByte(); + range <<= 8; + } + } + Range = range; + Code = code; + return result; + } - public uint DecodeBit(uint size0, int numTotalBits) - { - uint newBound = (Range >> numTotalBits) * size0; - uint symbol; - if (Code < newBound) - { - symbol = 0; - Range = newBound; - } - else - { - symbol = 1; - Code -= newBound; - Range -= newBound; - } - Normalize(); - return symbol; - } + public uint DecodeBit(uint size0, int numTotalBits) + { + uint newBound = (Range >> numTotalBits) * size0; + uint symbol; + if (Code < newBound) + { + symbol = 0; + Range = newBound; + } + else + { + symbol = 1; + Code -= newBound; + Range -= newBound; + } + Normalize(); + return symbol; + } - // ulong GetProcessedSize() {return Stream.GetProcessedSize(); } - } + // ulong GetProcessedSize() {return Stream.GetProcessedSize(); } + } } diff --git a/7zip/Compress/RangeCoder/RangeCoderBit.cs b/7zip/Compress/RangeCoder/RangeCoderBit.cs index 000a5a0..05a486e 100644 --- a/7zip/Compress/RangeCoder/RangeCoderBit.cs +++ b/7zip/Compress/RangeCoder/RangeCoderBit.cs @@ -2,116 +2,116 @@ using System; namespace SevenZip.Compression.RangeCoder { - struct BitEncoder - { - public const int kNumBitModelTotalBits = 11; - public const uint kBitModelTotal = (1 << kNumBitModelTotalBits); - const int kNumMoveBits = 5; - const int kNumMoveReducingBits = 2; - public const int kNumBitPriceShiftBits = 6; + struct BitEncoder + { + public const int kNumBitModelTotalBits = 11; + public const uint kBitModelTotal = (1 << kNumBitModelTotalBits); + const int kNumMoveBits = 5; + const int kNumMoveReducingBits = 2; + public const int kNumBitPriceShiftBits = 6; - uint Prob; + uint Prob; - public void Init() { Prob = kBitModelTotal >> 1; } + public void Init() { Prob = kBitModelTotal >> 1; } - public void UpdateModel(uint symbol) - { - if (symbol == 0) - Prob += (kBitModelTotal - Prob) >> kNumMoveBits; - else - Prob -= (Prob) >> kNumMoveBits; - } + public void UpdateModel(uint symbol) + { + if (symbol == 0) + Prob += (kBitModelTotal - Prob) >> kNumMoveBits; + else + Prob -= (Prob) >> kNumMoveBits; + } - public void Encode(Encoder encoder, uint symbol) - { - // encoder.EncodeBit(Prob, kNumBitModelTotalBits, symbol); - // UpdateModel(symbol); - uint newBound = (encoder.Range >> kNumBitModelTotalBits) * Prob; - if (symbol == 0) - { - encoder.Range = newBound; - Prob += (kBitModelTotal - Prob) >> kNumMoveBits; - } - else - { - encoder.Low += newBound; - encoder.Range -= newBound; - Prob -= (Prob) >> kNumMoveBits; - } - if (encoder.Range < Encoder.kTopValue) - { - encoder.Range <<= 8; - encoder.ShiftLow(); - } - } + public void Encode(Encoder encoder, uint symbol) + { + // encoder.EncodeBit(Prob, kNumBitModelTotalBits, symbol); + // UpdateModel(symbol); + uint newBound = (encoder.Range >> kNumBitModelTotalBits) * Prob; + if (symbol == 0) + { + encoder.Range = newBound; + Prob += (kBitModelTotal - Prob) >> kNumMoveBits; + } + else + { + encoder.Low += newBound; + encoder.Range -= newBound; + Prob -= (Prob) >> kNumMoveBits; + } + if (encoder.Range < Encoder.kTopValue) + { + encoder.Range <<= 8; + encoder.ShiftLow(); + } + } - private static UInt32[] ProbPrices = new UInt32[kBitModelTotal >> kNumMoveReducingBits]; + private static UInt32[] ProbPrices = new UInt32[kBitModelTotal >> kNumMoveReducingBits]; - static BitEncoder() - { - const int kNumBits = (kNumBitModelTotalBits - kNumMoveReducingBits); - for (int i = kNumBits - 1; i >= 0; i--) - { - UInt32 start = (UInt32)1 << (kNumBits - i - 1); - UInt32 end = (UInt32)1 << (kNumBits - i); - for (UInt32 j = start; j < end; j++) - ProbPrices[j] = ((UInt32)i << kNumBitPriceShiftBits) + - (((end - j) << kNumBitPriceShiftBits) >> (kNumBits - i - 1)); - } - } + static BitEncoder() + { + const int kNumBits = (kNumBitModelTotalBits - kNumMoveReducingBits); + for (int i = kNumBits - 1; i >= 0; i--) + { + UInt32 start = (UInt32)1 << (kNumBits - i - 1); + UInt32 end = (UInt32)1 << (kNumBits - i); + for (UInt32 j = start; j < end; j++) + ProbPrices[j] = ((UInt32)i << kNumBitPriceShiftBits) + + (((end - j) << kNumBitPriceShiftBits) >> (kNumBits - i - 1)); + } + } - public uint GetPrice(uint symbol) - { - return ProbPrices[(((Prob - symbol) ^ ((-(int)symbol))) & (kBitModelTotal - 1)) >> kNumMoveReducingBits]; - } - public uint GetPrice0() { return ProbPrices[Prob >> kNumMoveReducingBits]; } - public uint GetPrice1() { return ProbPrices[(kBitModelTotal - Prob) >> kNumMoveReducingBits]; } - } + public uint GetPrice(uint symbol) + { + return ProbPrices[(((Prob - symbol) ^ ((-(int)symbol))) & (kBitModelTotal - 1)) >> kNumMoveReducingBits]; + } + public uint GetPrice0() { return ProbPrices[Prob >> kNumMoveReducingBits]; } + public uint GetPrice1() { return ProbPrices[(kBitModelTotal - Prob) >> kNumMoveReducingBits]; } + } - struct BitDecoder - { - public const int kNumBitModelTotalBits = 11; - public const uint kBitModelTotal = (1 << kNumBitModelTotalBits); - const int kNumMoveBits = 5; + struct BitDecoder + { + public const int kNumBitModelTotalBits = 11; + public const uint kBitModelTotal = (1 << kNumBitModelTotalBits); + const int kNumMoveBits = 5; - uint Prob; + uint Prob; - public void UpdateModel(int numMoveBits, uint symbol) - { - if (symbol == 0) - Prob += (kBitModelTotal - Prob) >> numMoveBits; - else - Prob -= (Prob) >> numMoveBits; - } + public void UpdateModel(int numMoveBits, uint symbol) + { + if (symbol == 0) + Prob += (kBitModelTotal - Prob) >> numMoveBits; + else + Prob -= (Prob) >> numMoveBits; + } - public void Init() { Prob = kBitModelTotal >> 1; } + public void Init() { Prob = kBitModelTotal >> 1; } - public uint Decode(RangeCoder.Decoder rangeDecoder) - { - uint newBound = (uint)(rangeDecoder.Range >> kNumBitModelTotalBits) * (uint)Prob; - if (rangeDecoder.Code < newBound) - { - rangeDecoder.Range = newBound; - Prob += (kBitModelTotal - Prob) >> kNumMoveBits; - if (rangeDecoder.Range < Decoder.kTopValue) - { - rangeDecoder.Code = (rangeDecoder.Code << 8) | (byte)rangeDecoder.Stream.ReadByte(); - rangeDecoder.Range <<= 8; - } - return 0; - } - else - { - rangeDecoder.Range -= newBound; - rangeDecoder.Code -= newBound; - Prob -= (Prob) >> kNumMoveBits; - if (rangeDecoder.Range < Decoder.kTopValue) - { - rangeDecoder.Code = (rangeDecoder.Code << 8) | (byte)rangeDecoder.Stream.ReadByte(); - rangeDecoder.Range <<= 8; - } - return 1; - } - } - } + public uint Decode(RangeCoder.Decoder rangeDecoder) + { + uint newBound = (uint)(rangeDecoder.Range >> kNumBitModelTotalBits) * (uint)Prob; + if (rangeDecoder.Code < newBound) + { + rangeDecoder.Range = newBound; + Prob += (kBitModelTotal - Prob) >> kNumMoveBits; + if (rangeDecoder.Range < Decoder.kTopValue) + { + rangeDecoder.Code = (rangeDecoder.Code << 8) | (byte)rangeDecoder.Stream.ReadByte(); + rangeDecoder.Range <<= 8; + } + return 0; + } + else + { + rangeDecoder.Range -= newBound; + rangeDecoder.Code -= newBound; + Prob -= (Prob) >> kNumMoveBits; + if (rangeDecoder.Range < Decoder.kTopValue) + { + rangeDecoder.Code = (rangeDecoder.Code << 8) | (byte)rangeDecoder.Stream.ReadByte(); + rangeDecoder.Range <<= 8; + } + return 1; + } + } + } } diff --git a/7zip/Compress/RangeCoder/RangeCoderBitTree.cs b/7zip/Compress/RangeCoder/RangeCoderBitTree.cs index 3309c14..0defdc8 100644 --- a/7zip/Compress/RangeCoder/RangeCoderBitTree.cs +++ b/7zip/Compress/RangeCoder/RangeCoderBitTree.cs @@ -2,156 +2,156 @@ using System; namespace SevenZip.Compression.RangeCoder { - struct BitTreeEncoder - { - BitEncoder[] Models; - int NumBitLevels; + struct BitTreeEncoder + { + BitEncoder[] Models; + int NumBitLevels; - public BitTreeEncoder(int numBitLevels) - { - NumBitLevels = numBitLevels; - Models = new BitEncoder[1 << numBitLevels]; - } + public BitTreeEncoder(int numBitLevels) + { + NumBitLevels = numBitLevels; + Models = new BitEncoder[1 << numBitLevels]; + } - public void Init() - { - for (uint i = 1; i < (1 << NumBitLevels); i++) - Models[i].Init(); - } + public void Init() + { + for (uint i = 1; i < (1 << NumBitLevels); i++) + Models[i].Init(); + } - public void Encode(Encoder rangeEncoder, UInt32 symbol) - { - UInt32 m = 1; - for (int bitIndex = NumBitLevels; bitIndex > 0; ) - { - bitIndex--; - UInt32 bit = (symbol >> bitIndex) & 1; - Models[m].Encode(rangeEncoder, bit); - m = (m << 1) | bit; - } - } + public void Encode(Encoder rangeEncoder, UInt32 symbol) + { + UInt32 m = 1; + for (int bitIndex = NumBitLevels; bitIndex > 0;) + { + bitIndex--; + UInt32 bit = (symbol >> bitIndex) & 1; + Models[m].Encode(rangeEncoder, bit); + m = (m << 1) | bit; + } + } - public void ReverseEncode(Encoder rangeEncoder, UInt32 symbol) - { - UInt32 m = 1; - for (UInt32 i = 0; i < NumBitLevels; i++) - { - UInt32 bit = symbol & 1; - Models[m].Encode(rangeEncoder, bit); - m = (m << 1) | bit; - symbol >>= 1; - } - } + public void ReverseEncode(Encoder rangeEncoder, UInt32 symbol) + { + UInt32 m = 1; + for (UInt32 i = 0; i < NumBitLevels; i++) + { + UInt32 bit = symbol & 1; + Models[m].Encode(rangeEncoder, bit); + m = (m << 1) | bit; + symbol >>= 1; + } + } - public UInt32 GetPrice(UInt32 symbol) - { - UInt32 price = 0; - UInt32 m = 1; - for (int bitIndex = NumBitLevels; bitIndex > 0; ) - { - bitIndex--; - UInt32 bit = (symbol >> bitIndex) & 1; - price += Models[m].GetPrice(bit); - m = (m << 1) + bit; - } - return price; - } + public UInt32 GetPrice(UInt32 symbol) + { + UInt32 price = 0; + UInt32 m = 1; + for (int bitIndex = NumBitLevels; bitIndex > 0;) + { + bitIndex--; + UInt32 bit = (symbol >> bitIndex) & 1; + price += Models[m].GetPrice(bit); + m = (m << 1) + bit; + } + return price; + } - public UInt32 ReverseGetPrice(UInt32 symbol) - { - UInt32 price = 0; - UInt32 m = 1; - for (int i = NumBitLevels; i > 0; i--) - { - UInt32 bit = symbol & 1; - symbol >>= 1; - price += Models[m].GetPrice(bit); - m = (m << 1) | bit; - } - return price; - } + public UInt32 ReverseGetPrice(UInt32 symbol) + { + UInt32 price = 0; + UInt32 m = 1; + for (int i = NumBitLevels; i > 0; i--) + { + UInt32 bit = symbol & 1; + symbol >>= 1; + price += Models[m].GetPrice(bit); + m = (m << 1) | bit; + } + return price; + } - public static UInt32 ReverseGetPrice(BitEncoder[] Models, UInt32 startIndex, - int NumBitLevels, UInt32 symbol) - { - UInt32 price = 0; - UInt32 m = 1; - for (int i = NumBitLevels; i > 0; i--) - { - UInt32 bit = symbol & 1; - symbol >>= 1; - price += Models[startIndex + m].GetPrice(bit); - m = (m << 1) | bit; - } - return price; - } + public static UInt32 ReverseGetPrice(BitEncoder[] Models, UInt32 startIndex, + int NumBitLevels, UInt32 symbol) + { + UInt32 price = 0; + UInt32 m = 1; + for (int i = NumBitLevels; i > 0; i--) + { + UInt32 bit = symbol & 1; + symbol >>= 1; + price += Models[startIndex + m].GetPrice(bit); + m = (m << 1) | bit; + } + return price; + } - public static void ReverseEncode(BitEncoder[] Models, UInt32 startIndex, - Encoder rangeEncoder, int NumBitLevels, UInt32 symbol) - { - UInt32 m = 1; - for (int i = 0; i < NumBitLevels; i++) - { - UInt32 bit = symbol & 1; - Models[startIndex + m].Encode(rangeEncoder, bit); - m = (m << 1) | bit; - symbol >>= 1; - } - } - } + public static void ReverseEncode(BitEncoder[] Models, UInt32 startIndex, + Encoder rangeEncoder, int NumBitLevels, UInt32 symbol) + { + UInt32 m = 1; + for (int i = 0; i < NumBitLevels; i++) + { + UInt32 bit = symbol & 1; + Models[startIndex + m].Encode(rangeEncoder, bit); + m = (m << 1) | bit; + symbol >>= 1; + } + } + } - struct BitTreeDecoder - { - BitDecoder[] Models; - int NumBitLevels; + struct BitTreeDecoder + { + BitDecoder[] Models; + int NumBitLevels; - public BitTreeDecoder(int numBitLevels) - { - NumBitLevels = numBitLevels; - Models = new BitDecoder[1 << numBitLevels]; - } + public BitTreeDecoder(int numBitLevels) + { + NumBitLevels = numBitLevels; + Models = new BitDecoder[1 << numBitLevels]; + } - public void Init() - { - for (uint i = 1; i < (1 << NumBitLevels); i++) - Models[i].Init(); - } + public void Init() + { + for (uint i = 1; i < (1 << NumBitLevels); i++) + Models[i].Init(); + } - public uint Decode(RangeCoder.Decoder rangeDecoder) - { - uint m = 1; - for (int bitIndex = NumBitLevels; bitIndex > 0; bitIndex--) - m = (m << 1) + Models[m].Decode(rangeDecoder); - return m - ((uint)1 << NumBitLevels); - } + public uint Decode(RangeCoder.Decoder rangeDecoder) + { + uint m = 1; + for (int bitIndex = NumBitLevels; bitIndex > 0; bitIndex--) + m = (m << 1) + Models[m].Decode(rangeDecoder); + return m - ((uint)1 << NumBitLevels); + } - public uint ReverseDecode(RangeCoder.Decoder rangeDecoder) - { - uint m = 1; - uint symbol = 0; - for (int bitIndex = 0; bitIndex < NumBitLevels; bitIndex++) - { - uint bit = Models[m].Decode(rangeDecoder); - m <<= 1; - m += bit; - symbol |= (bit << bitIndex); - } - return symbol; - } + public uint ReverseDecode(RangeCoder.Decoder rangeDecoder) + { + uint m = 1; + uint symbol = 0; + for (int bitIndex = 0; bitIndex < NumBitLevels; bitIndex++) + { + uint bit = Models[m].Decode(rangeDecoder); + m <<= 1; + m += bit; + symbol |= (bit << bitIndex); + } + return symbol; + } - public static uint ReverseDecode(BitDecoder[] Models, UInt32 startIndex, - RangeCoder.Decoder rangeDecoder, int NumBitLevels) - { - uint m = 1; - uint symbol = 0; - for (int bitIndex = 0; bitIndex < NumBitLevels; bitIndex++) - { - uint bit = Models[startIndex + m].Decode(rangeDecoder); - m <<= 1; - m += bit; - symbol |= (bit << bitIndex); - } - return symbol; - } - } + public static uint ReverseDecode(BitDecoder[] Models, UInt32 startIndex, + RangeCoder.Decoder rangeDecoder, int NumBitLevels) + { + uint m = 1; + uint symbol = 0; + for (int bitIndex = 0; bitIndex < NumBitLevels; bitIndex++) + { + uint bit = Models[startIndex + m].Decode(rangeDecoder); + m <<= 1; + m += bit; + symbol |= (bit << bitIndex); + } + return symbol; + } + } } diff --git a/7zip/ICoder.cs b/7zip/ICoder.cs index 875cb27..f0781b0 100644 --- a/7zip/ICoder.cs +++ b/7zip/ICoder.cs @@ -4,64 +4,64 @@ using System; namespace SevenZip { - /// - /// The exception that is thrown when an error in input stream occurs during decoding. - /// - class DataErrorException : ApplicationException - { - public DataErrorException(): base("Data Error") { } - } + /// + /// The exception that is thrown when an error in input stream occurs during decoding. + /// + class DataErrorException : ApplicationException + { + public DataErrorException() : base("Data Error") { } + } - /// - /// The exception that is thrown when the value of an argument is outside the allowable range. - /// - class InvalidParamException : ApplicationException - { - public InvalidParamException(): base("Invalid Parameter") { } - } + /// + /// The exception that is thrown when the value of an argument is outside the allowable range. + /// + class InvalidParamException : ApplicationException + { + public InvalidParamException() : base("Invalid Parameter") { } + } - public interface ICodeProgress - { - /// - /// Callback progress. - /// - /// - /// input size. -1 if unknown. - /// - /// - /// output size. -1 if unknown. - /// - void SetProgress(Int64 inSize, Int64 outSize); - }; + public interface ICodeProgress + { + /// + /// Callback progress. + /// + /// + /// input size. -1 if unknown. + /// + /// + /// output size. -1 if unknown. + /// + void SetProgress(Int64 inSize, Int64 outSize); + }; - public interface ICoder - { - /// - /// Codes streams. - /// - /// - /// input Stream. - /// - /// - /// output Stream. - /// - /// - /// input Size. -1 if unknown. - /// - /// - /// output Size. -1 if unknown. - /// - /// - /// callback progress reference. - /// - /// - /// if input stream is not valid - /// - void Code(System.IO.Stream inStream, System.IO.Stream outStream, - Int64 inSize, Int64 outSize, ICodeProgress progress); - }; + public interface ICoder + { + /// + /// Codes streams. + /// + /// + /// input Stream. + /// + /// + /// output Stream. + /// + /// + /// input Size. -1 if unknown. + /// + /// + /// output Size. -1 if unknown. + /// + /// + /// callback progress reference. + /// + /// + /// if input stream is not valid + /// + void Code(System.IO.Stream inStream, System.IO.Stream outStream, + Int64 inSize, Int64 outSize, ICodeProgress progress); + }; - /* + /* public interface ICoder2 { void Code(ISequentialInStream []inStreams, @@ -72,86 +72,86 @@ namespace SevenZip }; */ - /// - /// Provides the fields that represent properties idenitifiers for compressing. - /// - public enum CoderPropID - { - /// - /// Specifies default property. - /// - DefaultProp = 0, - /// - /// Specifies size of dictionary. - /// - DictionarySize, - /// - /// Specifies size of memory for PPM*. - /// - UsedMemorySize, - /// - /// Specifies order for PPM methods. - /// - Order, - /// - /// Specifies Block Size. - /// - BlockSize, - /// - /// Specifies number of postion state bits for LZMA (0 <= x <= 4). - /// - PosStateBits, - /// - /// Specifies number of literal context bits for LZMA (0 <= x <= 8). - /// - LitContextBits, - /// - /// Specifies number of literal position bits for LZMA (0 <= x <= 4). - /// - LitPosBits, - /// - /// Specifies number of fast bytes for LZ*. - /// - NumFastBytes, - /// - /// Specifies match finder. LZMA: "BT2", "BT4" or "BT4B". - /// - MatchFinder, - /// - /// Specifies the number of match finder cyckes. - /// - MatchFinderCycles, - /// - /// Specifies number of passes. - /// - NumPasses, - /// - /// Specifies number of algorithm. - /// - Algorithm, - /// - /// Specifies the number of threads. - /// - NumThreads, - /// - /// Specifies mode with end marker. - /// - EndMarker - }; + /// + /// Provides the fields that represent properties idenitifiers for compressing. + /// + public enum CoderPropID + { + /// + /// Specifies default property. + /// + DefaultProp = 0, + /// + /// Specifies size of dictionary. + /// + DictionarySize, + /// + /// Specifies size of memory for PPM*. + /// + UsedMemorySize, + /// + /// Specifies order for PPM methods. + /// + Order, + /// + /// Specifies Block Size. + /// + BlockSize, + /// + /// Specifies number of postion state bits for LZMA (0 <= x <= 4). + /// + PosStateBits, + /// + /// Specifies number of literal context bits for LZMA (0 <= x <= 8). + /// + LitContextBits, + /// + /// Specifies number of literal position bits for LZMA (0 <= x <= 4). + /// + LitPosBits, + /// + /// Specifies number of fast bytes for LZ*. + /// + NumFastBytes, + /// + /// Specifies match finder. LZMA: "BT2", "BT4" or "BT4B". + /// + MatchFinder, + /// + /// Specifies the number of match finder cyckes. + /// + MatchFinderCycles, + /// + /// Specifies number of passes. + /// + NumPasses, + /// + /// Specifies number of algorithm. + /// + Algorithm, + /// + /// Specifies the number of threads. + /// + NumThreads, + /// + /// Specifies mode with end marker. + /// + EndMarker + }; - public interface ISetCoderProperties - { - void SetCoderProperties(CoderPropID[] propIDs, object[] properties); - }; + public interface ISetCoderProperties + { + void SetCoderProperties(CoderPropID[] propIDs, object[] properties); + }; - public interface IWriteCoderProperties - { - void WriteCoderProperties(System.IO.Stream outStream); - } + public interface IWriteCoderProperties + { + void WriteCoderProperties(System.IO.Stream outStream); + } - public interface ISetDecoderProperties - { - void SetDecoderProperties(byte[] properties); - } + public interface ISetDecoderProperties + { + void SetDecoderProperties(byte[] properties); + } } diff --git a/App.xaml.cs b/App.xaml.cs index 3d323e1..31ff73b 100644 --- a/App.xaml.cs +++ b/App.xaml.cs @@ -19,10 +19,10 @@ // DEALINGS IN THE SOFTWARE. using System; -using System.Linq; -using System.Windows; using System.IO; +using System.Linq; using System.Threading; +using System.Windows; namespace WPinternals { diff --git a/DiscUtils/Block.cs b/DiscUtils/Block.cs index 22db695..4d98399 100644 --- a/DiscUtils/Block.cs +++ b/DiscUtils/Block.cs @@ -27,7 +27,7 @@ namespace DiscUtils public Block() { } - + public long Position { get; set; } public byte[] Data { get; set; } diff --git a/DiscUtils/BlockCache.cs b/DiscUtils/BlockCache.cs index 9398d80..2d54ab7 100644 --- a/DiscUtils/BlockCache.cs +++ b/DiscUtils/BlockCache.cs @@ -22,9 +22,7 @@ namespace DiscUtils { - using System; using System.Collections.Generic; - using System.Text; internal class BlockCache where T : Block, new() diff --git a/DiscUtils/BootConfig/DiscUtilsRegistryStorage.cs b/DiscUtils/BootConfig/DiscUtilsRegistryStorage.cs index 0bdb919..9c65e2b 100644 --- a/DiscUtils/BootConfig/DiscUtilsRegistryStorage.cs +++ b/DiscUtils/BootConfig/DiscUtilsRegistryStorage.cs @@ -22,10 +22,10 @@ namespace DiscUtils.BootConfig { + using DiscUtils.Registry; using System; using System.Collections.Generic; using System.Globalization; - using DiscUtils.Registry; internal class DiscUtilsRegistryStorage : BaseStorage { diff --git a/DiscUtils/BootConfig/ElementValue.cs b/DiscUtils/BootConfig/ElementValue.cs index 9d40ad9..8b52ea8 100644 --- a/DiscUtils/BootConfig/ElementValue.cs +++ b/DiscUtils/BootConfig/ElementValue.cs @@ -23,7 +23,6 @@ namespace DiscUtils.BootConfig { using System; - using System.Globalization; /// /// The value of an element. diff --git a/DiscUtils/BootConfig/InheritType.cs b/DiscUtils/BootConfig/InheritType.cs index 4a4c86b..bc8747a 100644 --- a/DiscUtils/BootConfig/InheritType.cs +++ b/DiscUtils/BootConfig/InheritType.cs @@ -22,10 +22,6 @@ namespace DiscUtils.BootConfig { - using System; - using System.Collections.Generic; - using System.Text; - /// /// Indicates the type of objects that can inherit from an object. /// diff --git a/DiscUtils/BootConfig/Store.cs b/DiscUtils/BootConfig/Store.cs index 56450d5..2ee939a 100644 --- a/DiscUtils/BootConfig/Store.cs +++ b/DiscUtils/BootConfig/Store.cs @@ -22,9 +22,9 @@ namespace DiscUtils.BootConfig { + using DiscUtils.Registry; using System; using System.Collections.Generic; - using DiscUtils.Registry; /// /// Represents a Boot Configuration Database store (i.e. a BCD file). diff --git a/DiscUtils/BuilderSparseStreamExtent.cs b/DiscUtils/BuilderSparseStreamExtent.cs index c221f01..416bf3d 100644 --- a/DiscUtils/BuilderSparseStreamExtent.cs +++ b/DiscUtils/BuilderSparseStreamExtent.cs @@ -22,9 +22,7 @@ namespace DiscUtils { - using System; using System.Collections.Generic; - using System.Text; internal class BuilderSparseStreamExtent : BuilderExtent { diff --git a/DiscUtils/ClusterMap.cs b/DiscUtils/ClusterMap.cs index e3e4b19..845e9a1 100644 --- a/DiscUtils/ClusterMap.cs +++ b/DiscUtils/ClusterMap.cs @@ -24,7 +24,6 @@ namespace DiscUtils { using System; using System.Collections.Generic; - using System.Text; /// /// Enumeration of possible cluster roles. @@ -36,12 +35,12 @@ namespace DiscUtils /// /// Unknown, or unspecified role. /// - None = 0x00, + None = 0x00, /// /// Cluster is free. /// - Free = 0x01, + Free = 0x01, /// /// Cluster is in use by a normal file. @@ -69,7 +68,7 @@ namespace DiscUtils /// /// Cluster is marked bad. /// - Bad = 0x20, + Bad = 0x20, } /// diff --git a/DiscUtils/Fat/DirectoryEntry.cs b/DiscUtils/Fat/DirectoryEntry.cs index c09dc71..73db154 100644 --- a/DiscUtils/Fat/DirectoryEntry.cs +++ b/DiscUtils/Fat/DirectoryEntry.cs @@ -24,7 +24,6 @@ namespace DiscUtils.Fat { using System; using System.IO; - using System.Text; internal class DirectoryEntry { diff --git a/DiscUtils/Fat/FileAllocationTable.cs b/DiscUtils/Fat/FileAllocationTable.cs index 9daed7b..03dca48 100644 --- a/DiscUtils/Fat/FileAllocationTable.cs +++ b/DiscUtils/Fat/FileAllocationTable.cs @@ -22,7 +22,6 @@ namespace DiscUtils.Fat { - using System; using System.IO; internal class FileAllocationTable diff --git a/DiscUtils/Fat/FileSystemFactory.cs b/DiscUtils/Fat/FileSystemFactory.cs index 3327827..e41460c 100644 --- a/DiscUtils/Fat/FileSystemFactory.cs +++ b/DiscUtils/Fat/FileSystemFactory.cs @@ -22,8 +22,8 @@ namespace DiscUtils.Fat { - using System.IO; using DiscUtils.Vfs; + using System.IO; [VfsFileSystemFactory] internal class FileSystemFactory : VfsFileSystemFactory diff --git a/DiscUtils/LogicalDiskManager/DynamicDisk.cs b/DiscUtils/LogicalDiskManager/DynamicDisk.cs index 4c825aa..8dec605 100644 --- a/DiscUtils/LogicalDiskManager/DynamicDisk.cs +++ b/DiscUtils/LogicalDiskManager/DynamicDisk.cs @@ -22,9 +22,9 @@ namespace DiscUtils.LogicalDiskManager { + using DiscUtils.Partitions; using System; using System.IO; - using DiscUtils.Partitions; internal class DynamicDisk : IDiagnosticTraceable { diff --git a/DiscUtils/LogicalDiskManager/DynamicDiskGroup.cs b/DiscUtils/LogicalDiskManager/DynamicDiskGroup.cs index a9b52e7..0e29e99 100644 --- a/DiscUtils/LogicalDiskManager/DynamicDiskGroup.cs +++ b/DiscUtils/LogicalDiskManager/DynamicDiskGroup.cs @@ -22,11 +22,11 @@ namespace DiscUtils.LogicalDiskManager { + using DiscUtils.Partitions; using System; using System.Collections.Generic; using System.Globalization; using System.IO; - using DiscUtils.Partitions; internal class DynamicDiskGroup : IDiagnosticTraceable { diff --git a/DiscUtils/LogicalDiskManager/DynamicDiskManager.cs b/DiscUtils/LogicalDiskManager/DynamicDiskManager.cs index 43bec6d..be69aff 100644 --- a/DiscUtils/LogicalDiskManager/DynamicDiskManager.cs +++ b/DiscUtils/LogicalDiskManager/DynamicDiskManager.cs @@ -22,9 +22,9 @@ namespace DiscUtils.LogicalDiskManager { + using DiscUtils.Partitions; using System.Collections.Generic; using System.IO; - using DiscUtils.Partitions; /// /// A class that understands Windows LDM structures, mapping physical volumes to logical volumes. diff --git a/DiscUtils/LogicalDiskManager/TocBlock.cs b/DiscUtils/LogicalDiskManager/TocBlock.cs index 9b9904f..158c4f0 100644 --- a/DiscUtils/LogicalDiskManager/TocBlock.cs +++ b/DiscUtils/LogicalDiskManager/TocBlock.cs @@ -22,8 +22,6 @@ namespace DiscUtils.LogicalDiskManager { - using System; - internal class TocBlock { public string Signature; // TOCBLOCK diff --git a/DiscUtils/MappedStream.cs b/DiscUtils/MappedStream.cs index fd170fb..0995f8b 100644 --- a/DiscUtils/MappedStream.cs +++ b/DiscUtils/MappedStream.cs @@ -22,7 +22,6 @@ namespace DiscUtils { - using System; using System.Collections.Generic; using System.IO; diff --git a/DiscUtils/Ntfs/AttributeDefinitionRecord.cs b/DiscUtils/Ntfs/AttributeDefinitionRecord.cs index 1899619..062bec9 100644 --- a/DiscUtils/Ntfs/AttributeDefinitionRecord.cs +++ b/DiscUtils/Ntfs/AttributeDefinitionRecord.cs @@ -27,25 +27,25 @@ namespace DiscUtils.Ntfs internal enum AttributeCollationRule : int { - Binary = 0x00000000, - Filename = 0x00000001, - UnicodeString = 0x00000002, - UnsignedLong = 0x00000010, - Sid = 0x00000011, - SecurityHash = 0x00000012, + Binary = 0x00000000, + Filename = 0x00000001, + UnicodeString = 0x00000002, + UnsignedLong = 0x00000010, + Sid = 0x00000011, + SecurityHash = 0x00000012, MultipleUnsignedLongs = 0x00000013 } [Flags] internal enum AttributeTypeFlags : int { - None = 0x00, - Indexed = 0x02, - Multiple = 0x04, - NotZero = 0x08, - IndexedUnique = 0x10, - NamedUnique = 0x20, - MustBeResident = 0x40, + None = 0x00, + Indexed = 0x02, + Multiple = 0x04, + NotZero = 0x08, + IndexedUnique = 0x10, + NamedUnique = 0x20, + MustBeResident = 0x40, CanBeNonResident = 0x80 } diff --git a/DiscUtils/Ntfs/CompressedClusterStream.cs b/DiscUtils/Ntfs/CompressedClusterStream.cs index e987bd7..dc05382 100644 --- a/DiscUtils/Ntfs/CompressedClusterStream.cs +++ b/DiscUtils/Ntfs/CompressedClusterStream.cs @@ -22,10 +22,10 @@ namespace DiscUtils.Ntfs { + using DiscUtils.Compression; using System; using System.Collections.Generic; using System.IO; - using DiscUtils.Compression; internal sealed class CompressedClusterStream : ClusterStream { diff --git a/DiscUtils/Ntfs/CookedDataRun.cs b/DiscUtils/Ntfs/CookedDataRun.cs index d6a7e24..241020a 100644 --- a/DiscUtils/Ntfs/CookedDataRun.cs +++ b/DiscUtils/Ntfs/CookedDataRun.cs @@ -23,7 +23,6 @@ namespace DiscUtils.Ntfs { using System; - using System.Collections.Generic; internal class CookedDataRun { diff --git a/DiscUtils/Ntfs/DataRun.cs b/DiscUtils/Ntfs/DataRun.cs index 99739e2..b1abf0c 100644 --- a/DiscUtils/Ntfs/DataRun.cs +++ b/DiscUtils/Ntfs/DataRun.cs @@ -23,7 +23,6 @@ namespace DiscUtils.Ntfs { using System.Globalization; - using System.IO; internal class DataRun { diff --git a/DiscUtils/Ntfs/File.cs b/DiscUtils/Ntfs/File.cs index a192a3f..71127ae 100644 --- a/DiscUtils/Ntfs/File.cs +++ b/DiscUtils/Ntfs/File.cs @@ -809,7 +809,7 @@ namespace DiscUtils.Ntfs return SplitAttribute(record, (NonResidentAttributeRecord)record.FirstAttribute, false); } - + private bool SplitAttribute(FileRecord record, NonResidentAttributeRecord targetAttr, bool atStart) { if (targetAttr.DataRuns.Count <= 1) diff --git a/DiscUtils/Ntfs/FileRecord.cs b/DiscUtils/Ntfs/FileRecord.cs index 09125b4..7dc7976 100644 --- a/DiscUtils/Ntfs/FileRecord.cs +++ b/DiscUtils/Ntfs/FileRecord.cs @@ -24,7 +24,6 @@ namespace DiscUtils.Ntfs { using System; using System.Collections.Generic; - using System.Collections.ObjectModel; using System.IO; [Flags] diff --git a/DiscUtils/Ntfs/FileSystemFactory.cs b/DiscUtils/Ntfs/FileSystemFactory.cs index 923e640..72d9b37 100644 --- a/DiscUtils/Ntfs/FileSystemFactory.cs +++ b/DiscUtils/Ntfs/FileSystemFactory.cs @@ -22,8 +22,8 @@ namespace DiscUtils.Ntfs { - using System.IO; using DiscUtils.Vfs; + using System.IO; [VfsFileSystemFactory] internal class FileSystemFactory : VfsFileSystemFactory diff --git a/DiscUtils/Ntfs/FixupRecordBase.cs b/DiscUtils/Ntfs/FixupRecordBase.cs index dffb159..bba1972 100644 --- a/DiscUtils/Ntfs/FixupRecordBase.cs +++ b/DiscUtils/Ntfs/FixupRecordBase.cs @@ -22,7 +22,6 @@ namespace DiscUtils.Ntfs { - using System; using System.IO; internal abstract class FixupRecordBase diff --git a/DiscUtils/Ntfs/Index.cs b/DiscUtils/Ntfs/Index.cs index 5f80825..7683bbf 100644 --- a/DiscUtils/Ntfs/Index.cs +++ b/DiscUtils/Ntfs/Index.cs @@ -474,7 +474,7 @@ namespace DiscUtils.Ntfs { writer.WriteLine(prefix + " " + EntryAsString(entry, _file.BestName, _name)); } - + if ((entry.Flags & IndexEntryFlags.Node) != 0) { NodeAsString(writer, prefix + " ", GetSubBlock(entry).Node, ":i" + entry.ChildrenVirtualCluster); diff --git a/DiscUtils/Ntfs/IndexBlock.cs b/DiscUtils/Ntfs/IndexBlock.cs index d7dbfdc..b38b750 100644 --- a/DiscUtils/Ntfs/IndexBlock.cs +++ b/DiscUtils/Ntfs/IndexBlock.cs @@ -23,7 +23,6 @@ namespace DiscUtils.Ntfs { using System; - using System.Collections.Generic; using System.IO; internal class IndexBlock : FixupRecordBase diff --git a/DiscUtils/Ntfs/IndexNode.cs b/DiscUtils/Ntfs/IndexNode.cs index 4a43707..51bd993 100644 --- a/DiscUtils/Ntfs/IndexNode.cs +++ b/DiscUtils/Ntfs/IndexNode.cs @@ -404,7 +404,7 @@ namespace DiscUtils.Ntfs } return null; - } + } private IndexEntry PopulateEnd() { diff --git a/DiscUtils/Ntfs/Internals/MasterFileTableAttribute.cs b/DiscUtils/Ntfs/Internals/MasterFileTableAttribute.cs index 234752d..935ec5f 100644 --- a/DiscUtils/Ntfs/Internals/MasterFileTableAttribute.cs +++ b/DiscUtils/Ntfs/Internals/MasterFileTableAttribute.cs @@ -1,9 +1,5 @@ namespace DiscUtils.Ntfs.Internals { - using System; - using System.Collections.Generic; - using System.Text; - public sealed class MasterFileTableAttribute { } diff --git a/DiscUtils/Ntfs/Internals/MasterFileTableRecord.cs b/DiscUtils/Ntfs/Internals/MasterFileTableRecord.cs index 37f76bb..439f464 100644 --- a/DiscUtils/Ntfs/Internals/MasterFileTableRecord.cs +++ b/DiscUtils/Ntfs/Internals/MasterFileTableRecord.cs @@ -22,10 +22,6 @@ namespace DiscUtils.Ntfs.Internals { - using System.Collections; - using System.Collections.Generic; - using System.IO; - public sealed class MasterFileTableRecord { private FileRecord _fileRecord; diff --git a/DiscUtils/Ntfs/Internals/NtfsNamespace.cs b/DiscUtils/Ntfs/Internals/NtfsNamespace.cs index 7058168..7f49e14 100644 --- a/DiscUtils/Ntfs/Internals/NtfsNamespace.cs +++ b/DiscUtils/Ntfs/Internals/NtfsNamespace.cs @@ -22,8 +22,6 @@ namespace DiscUtils.Ntfs.Internals { - using System; - /// /// The known NTFS namespaces. /// diff --git a/DiscUtils/Ntfs/LZNT1.cs b/DiscUtils/Ntfs/LZNT1.cs index 963db10..b7c4f56 100644 --- a/DiscUtils/Ntfs/LZNT1.cs +++ b/DiscUtils/Ntfs/LZNT1.cs @@ -30,8 +30,8 @@ namespace DiscUtils.Ntfs { - using System; using DiscUtils.Compression; + using System; /// /// Implementation of the LZNT1 algorithm used for compressing NTFS files. diff --git a/DiscUtils/Ntfs/NonResidentDataBuffer.cs b/DiscUtils/Ntfs/NonResidentDataBuffer.cs index 04ec896..fa37135 100644 --- a/DiscUtils/Ntfs/NonResidentDataBuffer.cs +++ b/DiscUtils/Ntfs/NonResidentDataBuffer.cs @@ -25,7 +25,6 @@ namespace DiscUtils.Ntfs using System; using System.Collections.Generic; using System.IO; - using DiscUtils.Compression; internal class NonResidentDataBuffer : DiscUtils.Buffer, IMappedBuffer { diff --git a/DiscUtils/Ntfs/NtfsAttribute.cs b/DiscUtils/Ntfs/NtfsAttribute.cs index ed61d53..0e71b4e 100644 --- a/DiscUtils/Ntfs/NtfsAttribute.cs +++ b/DiscUtils/Ntfs/NtfsAttribute.cs @@ -22,7 +22,6 @@ namespace DiscUtils.Ntfs { - using System; using System.Collections.Generic; using System.Globalization; using System.IO; diff --git a/DiscUtils/Ntfs/NtfsFileSystem.cs b/DiscUtils/Ntfs/NtfsFileSystem.cs index 97aa3ae..78a0c3f 100644 --- a/DiscUtils/Ntfs/NtfsFileSystem.cs +++ b/DiscUtils/Ntfs/NtfsFileSystem.cs @@ -1097,7 +1097,7 @@ namespace DiscUtils.Ntfs } } - UpdateStandardInformation(dirEntry, file, delegate(StandardInformation si) { si.FileAttributes = FileNameRecord.SetAttributes(newValue, si.FileAttributes); }); + UpdateStandardInformation(dirEntry, file, delegate (StandardInformation si) { si.FileAttributes = FileNameRecord.SetAttributes(newValue, si.FileAttributes); }); } } @@ -1131,7 +1131,7 @@ namespace DiscUtils.Ntfs { using (new NtfsTransaction()) { - UpdateStandardInformation(path, delegate(StandardInformation si) { si.CreationTime = newTime; }); + UpdateStandardInformation(path, delegate (StandardInformation si) { si.CreationTime = newTime; }); } } @@ -1165,7 +1165,7 @@ namespace DiscUtils.Ntfs { using (new NtfsTransaction()) { - UpdateStandardInformation(path, delegate(StandardInformation si) { si.LastAccessTime = newTime; }); + UpdateStandardInformation(path, delegate (StandardInformation si) { si.LastAccessTime = newTime; }); } } @@ -1199,7 +1199,7 @@ namespace DiscUtils.Ntfs { using (new NtfsTransaction()) { - UpdateStandardInformation(path, delegate(StandardInformation si) { si.ModificationTime = newTime; }); + UpdateStandardInformation(path, delegate (StandardInformation si) { si.ModificationTime = newTime; }); } } @@ -1763,7 +1763,7 @@ namespace DiscUtils.Ntfs { UpdateStandardInformation( path, - delegate(StandardInformation si) + delegate (StandardInformation si) { si.CreationTime = info.CreationTime; si.LastAccessTime = info.LastAccessTime; @@ -1813,7 +1813,7 @@ namespace DiscUtils.Ntfs DirectoryEntry dirEntry = GetDirectoryEntry(path); if (dirEntry == null) { - throw new FileNotFoundException("File not found", path); + throw new FileNotFoundException("File not found", path); } File file = GetFile(dirEntry.Reference); diff --git a/DiscUtils/Ntfs/NtfsFormatter.cs b/DiscUtils/Ntfs/NtfsFormatter.cs index b4ecfae..fcd7954 100644 --- a/DiscUtils/Ntfs/NtfsFormatter.cs +++ b/DiscUtils/Ntfs/NtfsFormatter.cs @@ -137,8 +137,8 @@ namespace DiscUtils.Ntfs SetSecurityAttribute(volumeFile, "O:" + localAdminString + "G:BAD:(A;;0x12019f;;;SY)(A;;0x12019f;;;BA)"); volumeFile.UpdateRecordInMft(); - _context.GetFileByIndex = delegate(long index) { return new File(_context, _context.Mft.GetRecord(index, false)); }; - _context.AllocateFile = delegate(FileRecordFlags frf) { return new File(_context, _context.Mft.AllocateRecord(frf, false)); }; + _context.GetFileByIndex = delegate (long index) { return new File(_context, _context.Mft.GetRecord(index, false)); }; + _context.AllocateFile = delegate (FileRecordFlags frf) { return new File(_context, _context.Mft.AllocateRecord(frf, false)); }; File attrDefFile = CreateSystemFile(MasterFileTable.AttrDefIndex); _context.AttributeDefinitions.WriteTo(attrDefFile); diff --git a/DiscUtils/Ntfs/NtfsStream.cs b/DiscUtils/Ntfs/NtfsStream.cs index fff00c9..40eebb4 100644 --- a/DiscUtils/Ntfs/NtfsStream.cs +++ b/DiscUtils/Ntfs/NtfsStream.cs @@ -22,7 +22,6 @@ namespace DiscUtils.Ntfs { - using System; using System.Collections.Generic; using System.IO; @@ -70,7 +69,7 @@ namespace DiscUtils.Ntfs value.ReadFrom(buffer, 0); return value; } - + /// /// Sets the content of a stream. /// diff --git a/DiscUtils/Ntfs/NtfsTransaction.cs b/DiscUtils/Ntfs/NtfsTransaction.cs index 7d268d4..f7978bd 100644 --- a/DiscUtils/Ntfs/NtfsTransaction.cs +++ b/DiscUtils/Ntfs/NtfsTransaction.cs @@ -23,8 +23,6 @@ namespace DiscUtils.Ntfs { using System; - using System.Collections.Generic; - using System.Text; internal sealed class NtfsTransaction : IDisposable { diff --git a/DiscUtils/Ntfs/RawClusterStream.cs b/DiscUtils/Ntfs/RawClusterStream.cs index 899a67b..afd8bd9 100644 --- a/DiscUtils/Ntfs/RawClusterStream.cs +++ b/DiscUtils/Ntfs/RawClusterStream.cs @@ -22,11 +22,11 @@ namespace DiscUtils.Ntfs { + using DiscUtils; using System; using System.Collections.Generic; using System.Globalization; using System.IO; - using DiscUtils; /// /// Low-level non-resident attribute operations. diff --git a/DiscUtils/Ntfs/SecurityDescriptor.cs b/DiscUtils/Ntfs/SecurityDescriptor.cs index bdc7de2..dc6a1e3 100644 --- a/DiscUtils/Ntfs/SecurityDescriptor.cs +++ b/DiscUtils/Ntfs/SecurityDescriptor.cs @@ -22,10 +22,8 @@ namespace DiscUtils.Ntfs { - using System; using System.IO; using System.Security.AccessControl; - using System.Security.Principal; internal sealed class SecurityDescriptor : IByteArraySerializable, IDiagnosticTraceable { diff --git a/DiscUtils/Ntfs/ShortFileNameOption.cs b/DiscUtils/Ntfs/ShortFileNameOption.cs index 38d00e4..98aba9d 100644 --- a/DiscUtils/Ntfs/ShortFileNameOption.cs +++ b/DiscUtils/Ntfs/ShortFileNameOption.cs @@ -22,10 +22,6 @@ namespace DiscUtils.Ntfs { - using System; - using System.Collections.Generic; - using System.Text; - /// /// Controls whether short file names are created automatically. /// diff --git a/DiscUtils/Ntfs/StructuredNtfsAttribute.cs b/DiscUtils/Ntfs/StructuredNtfsAttribute.cs index b481d00..80b5f18 100644 --- a/DiscUtils/Ntfs/StructuredNtfsAttribute.cs +++ b/DiscUtils/Ntfs/StructuredNtfsAttribute.cs @@ -93,9 +93,9 @@ namespace DiscUtils.Ntfs { using (Stream s = Open(FileAccess.Read)) { - byte[] buffer = Utilities.ReadFully(s, (int)Length); - _structure.ReadFrom(buffer, 0); - _hasContent = s.Length != 0; + byte[] buffer = Utilities.ReadFully(s, (int)Length); + _structure.ReadFrom(buffer, 0); + _hasContent = s.Length != 0; } _initialized = true; diff --git a/DiscUtils/Ntfs/VolumeInformation.cs b/DiscUtils/Ntfs/VolumeInformation.cs index cc8513f..cd77c31 100644 --- a/DiscUtils/Ntfs/VolumeInformation.cs +++ b/DiscUtils/Ntfs/VolumeInformation.cs @@ -22,7 +22,6 @@ namespace DiscUtils.Ntfs { - using System; using System.IO; internal sealed class VolumeInformation : IByteArraySerializable, IDiagnosticTraceable diff --git a/DiscUtils/Ntfs/VolumeName.cs b/DiscUtils/Ntfs/VolumeName.cs index fbd843b..41969d5 100644 --- a/DiscUtils/Ntfs/VolumeName.cs +++ b/DiscUtils/Ntfs/VolumeName.cs @@ -22,7 +22,6 @@ namespace DiscUtils.Ntfs { - using System; using System.IO; using System.Text; diff --git a/DiscUtils/ObjectCache.cs b/DiscUtils/ObjectCache.cs index c86910e..0c51485 100644 --- a/DiscUtils/ObjectCache.cs +++ b/DiscUtils/ObjectCache.cs @@ -23,7 +23,6 @@ namespace DiscUtils { using System; - using System.Collections; using System.Collections.Generic; /// diff --git a/DiscUtils/Ownership.cs b/DiscUtils/Ownership.cs index ff42a1f..e379c2d 100644 --- a/DiscUtils/Ownership.cs +++ b/DiscUtils/Ownership.cs @@ -22,10 +22,6 @@ namespace DiscUtils { - using System; - using System.Collections.Generic; - using System.Text; - /// /// Enumeration used to indicate transfer of disposable objects. /// diff --git a/DiscUtils/Partitions/BiosPartitionInfo.cs b/DiscUtils/Partitions/BiosPartitionInfo.cs index 3412e8b..e6d9f9c 100644 --- a/DiscUtils/Partitions/BiosPartitionInfo.cs +++ b/DiscUtils/Partitions/BiosPartitionInfo.cs @@ -23,7 +23,6 @@ namespace DiscUtils.Partitions { using System; - using System.IO; /// /// Provides access to partition records in a BIOS (MBR) partition table. diff --git a/DiscUtils/Partitions/BiosPartitionedDiskBuilder.cs b/DiscUtils/Partitions/BiosPartitionedDiskBuilder.cs index 62e614a..83cb659 100644 --- a/DiscUtils/Partitions/BiosPartitionedDiskBuilder.cs +++ b/DiscUtils/Partitions/BiosPartitionedDiskBuilder.cs @@ -24,7 +24,6 @@ namespace DiscUtils.Partitions { using System; using System.Collections.Generic; - using System.IO; /// /// Builds a stream with the contents of a BIOS partitioned disk. diff --git a/DiscUtils/Partitions/GuidPartitionInfo.cs b/DiscUtils/Partitions/GuidPartitionInfo.cs index 4778c0b..24037c7 100644 --- a/DiscUtils/Partitions/GuidPartitionInfo.cs +++ b/DiscUtils/Partitions/GuidPartitionInfo.cs @@ -23,7 +23,6 @@ namespace DiscUtils.Partitions { using System; - using System.IO; /// /// Provides access to partition records in a GUID partition table. diff --git a/DiscUtils/Partitions/PartitionInfo.cs b/DiscUtils/Partitions/PartitionInfo.cs index 19a5f67..9b90b89 100644 --- a/DiscUtils/Partitions/PartitionInfo.cs +++ b/DiscUtils/Partitions/PartitionInfo.cs @@ -24,7 +24,6 @@ namespace DiscUtils.Partitions { using System; using System.Globalization; - using System.IO; /// /// Base class representing a disk partition. diff --git a/DiscUtils/PhysicalVolumeInfo.cs b/DiscUtils/PhysicalVolumeInfo.cs index 701d4d6..83176cc 100644 --- a/DiscUtils/PhysicalVolumeInfo.cs +++ b/DiscUtils/PhysicalVolumeInfo.cs @@ -22,9 +22,9 @@ namespace DiscUtils { + using DiscUtils.Partitions; using System; using System.Globalization; - using DiscUtils.Partitions; /// /// Enumeration of possible types of physical volume. diff --git a/DiscUtils/Range.cs b/DiscUtils/Range.cs index 8488a8b..9bcc534 100644 --- a/DiscUtils/Range.cs +++ b/DiscUtils/Range.cs @@ -24,7 +24,6 @@ namespace DiscUtils { using System; using System.Collections.Generic; - using System.Text; /// /// Represents a range of values. diff --git a/DiscUtils/Raw/DiskFactory.cs b/DiscUtils/Raw/DiskFactory.cs index 8fa40d1..17dc483 100644 --- a/DiscUtils/Raw/DiskFactory.cs +++ b/DiscUtils/Raw/DiskFactory.cs @@ -23,7 +23,6 @@ namespace DiscUtils.Raw { using System; - using System.Collections.Generic; using System.IO; [VirtualDiskFactory("RAW", ".img,.ima,.vfd,.flp,.bif")] diff --git a/DiscUtils/Raw/DiskImageFile.cs b/DiscUtils/Raw/DiskImageFile.cs index 2f1b6f5..a092d69 100644 --- a/DiscUtils/Raw/DiskImageFile.cs +++ b/DiscUtils/Raw/DiskImageFile.cs @@ -22,9 +22,9 @@ namespace DiscUtils.Raw { + using DiscUtils.Partitions; using System; using System.IO; - using DiscUtils.Partitions; /// /// Represents a single raw disk image file. diff --git a/DiscUtils/Registry/BinHeader.cs b/DiscUtils/Registry/BinHeader.cs index a071739..331d3fa 100644 --- a/DiscUtils/Registry/BinHeader.cs +++ b/DiscUtils/Registry/BinHeader.cs @@ -22,7 +22,6 @@ namespace DiscUtils.Registry { - using System; using System.IO; internal sealed class BinHeader : IByteArraySerializable diff --git a/DiscUtils/SparseMemoryStream.cs b/DiscUtils/SparseMemoryStream.cs index 5c22bf0..37dc5d4 100644 --- a/DiscUtils/SparseMemoryStream.cs +++ b/DiscUtils/SparseMemoryStream.cs @@ -22,7 +22,6 @@ namespace DiscUtils { - using System.Collections.Generic; using System.IO; /// diff --git a/DiscUtils/Tuple.cs b/DiscUtils/Tuple.cs index ba30e61..7ed0420 100644 --- a/DiscUtils/Tuple.cs +++ b/DiscUtils/Tuple.cs @@ -22,8 +22,6 @@ namespace DiscUtils { - using System; - internal abstract class Tuple { public abstract object this[int i] diff --git a/DiscUtils/UnixFileType.cs b/DiscUtils/UnixFileType.cs index 3b6289a..05d0f98 100644 --- a/DiscUtils/UnixFileType.cs +++ b/DiscUtils/UnixFileType.cs @@ -22,8 +22,6 @@ namespace DiscUtils { - using System; - /// /// Standard Unix-style file type. /// diff --git a/DiscUtils/Utilities.cs b/DiscUtils/Utilities.cs index 460941c..945bd27 100644 --- a/DiscUtils/Utilities.cs +++ b/DiscUtils/Utilities.cs @@ -29,7 +29,7 @@ namespace DiscUtils using System.Text.RegularExpressions; internal delegate TResult Func(T arg); - + internal static class Utilities { /// diff --git a/DiscUtils/Vfs/VfsFileSystemFactoryAttribute.cs b/DiscUtils/Vfs/VfsFileSystemFactoryAttribute.cs index 3532ebf..76313a8 100644 --- a/DiscUtils/Vfs/VfsFileSystemFactoryAttribute.cs +++ b/DiscUtils/Vfs/VfsFileSystemFactoryAttribute.cs @@ -23,8 +23,6 @@ namespace DiscUtils.Vfs { using System; - using System.Collections.Generic; - using System.Text; /// /// Attribute identifying file system factory classes. diff --git a/DiscUtils/VirtualDisk.cs b/DiscUtils/VirtualDisk.cs index 7fc15cf..26228a0 100644 --- a/DiscUtils/VirtualDisk.cs +++ b/DiscUtils/VirtualDisk.cs @@ -22,11 +22,11 @@ namespace DiscUtils { + using DiscUtils.Partitions; using System; using System.Collections.Generic; using System.Globalization; using System.IO; - using DiscUtils.Partitions; /// /// Base class representing virtual hard disks. diff --git a/DiscUtils/VolumeManager.cs b/DiscUtils/VolumeManager.cs index e4a4397..8904bd2 100644 --- a/DiscUtils/VolumeManager.cs +++ b/DiscUtils/VolumeManager.cs @@ -22,11 +22,11 @@ namespace DiscUtils { + using DiscUtils.Partitions; using System; using System.Collections.Generic; using System.Globalization; using System.IO; - using DiscUtils.Partitions; /// /// VolumeManager interprets partitions and other on-disk structures (possibly combining multiple disks). diff --git a/FilePickerControl.xaml.cs b/FilePickerControl.xaml.cs index 0e4a289..ac728ce 100644 --- a/FilePickerControl.xaml.cs +++ b/FilePickerControl.xaml.cs @@ -27,7 +27,7 @@ using System.Windows.Media; namespace WPinternals { - public class PathChangedEventArgs: EventArgs + public class PathChangedEventArgs : EventArgs { public PathChangedEventArgs(string NewPath) : base() @@ -110,7 +110,7 @@ namespace WPinternals { return (string)GetValue(PathProperty); } - set + set { if ((string)GetValue(PathProperty) != value) { diff --git a/HelperClasses.cs b/HelperClasses.cs index fa1e4ca..c082015 100644 --- a/HelperClasses.cs +++ b/HelperClasses.cs @@ -22,25 +22,24 @@ // Where possible the original authors are referenced. using System; -using System.IO; +using System.Collections; using System.Collections.Generic; using System.Globalization; +using System.IO; +using System.IO.Compression; using System.Linq; +using System.Reflection; using System.Text; +using System.Threading; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; +using System.Windows.Input; using System.Windows.Media.Animation; using System.Windows.Media.Imaging; -using System.Threading; -using System.Windows.Input; using System.Windows.Threading; -using System.IO.Compression; -using System.Collections; -using System.Reflection; -using System.Net; namespace WPinternals { @@ -226,11 +225,11 @@ namespace WPinternals public Boolean IsVisible { - get + get { return (Boolean)this.GetValue(IsVisibleProperty); } - set + set { this.SetValue(IsVisibleProperty, value); } @@ -1061,7 +1060,7 @@ namespace WPinternals { } - public DelegateCommand(Action executeMethod, Func canExecuteMethod): base(o => executeMethod(), f => canExecuteMethod()) + public DelegateCommand(Action executeMethod, Func canExecuteMethod) : base(o => executeMethod(), f => canExecuteMethod()) { } @@ -1076,7 +1075,7 @@ namespace WPinternals } } - internal class FlowDocumentScrollViewerNoMouseWheel: FlowDocumentScrollViewer + internal class FlowDocumentScrollViewerNoMouseWheel : FlowDocumentScrollViewer { protected override void OnMouseWheel(MouseWheelEventArgs e) { @@ -1167,7 +1166,7 @@ namespace WPinternals } } - internal class WPinternalsException: Exception + internal class WPinternalsException : Exception { // Message and SubMessaage are always printable internal string SubMessage = null; @@ -1423,7 +1422,7 @@ namespace WPinternals internal DecompressedStream(Stream InputStream) { UnderlyingStream = new ReadSeekableStream(InputStream, 0x100); - + byte[] Signature = new byte["CompressedPartition".Length + 2]; Signature[0x00] = 0xFF; Buffer.BlockCopy(Encoding.ASCII.GetBytes("CompressedPartition"), 0, Signature, 0x01, "CompressedPartition".Length); @@ -1469,7 +1468,7 @@ namespace WPinternals public override bool CanRead { get { return true; } } public override bool CanSeek { get { return false; } } - public override int Read(byte[] buffer, int offset, int count) + public override int Read(byte[] buffer, int offset, int count) { int RealCount = UnderlyingStream.Read(buffer, offset, count); ReadPosition += RealCount; @@ -1483,18 +1482,18 @@ namespace WPinternals } public override bool CanTimeout { get { return UnderlyingStream.CanTimeout; } } public override bool CanWrite { get { return true; } } - public override long Length - { - get + public override long Length + { + get { if (IsSourceCompressed) return (long)DecompressedLength; else return UnderlyingStream.Length; - } + } } public override void SetLength(long value) { throw new NotSupportedException(); } - public override void Write(byte[] buffer, int offset, int count) {throw new NotSupportedException(); } + public override void Write(byte[] buffer, int offset, int count) { throw new NotSupportedException(); } public override void Flush() { UnderlyingStream.Flush(); } public override void Close() { UnderlyingStream.Close(); } protected override void Dispose(bool disposing) @@ -1507,7 +1506,7 @@ namespace WPinternals } // For writing a compressed stream - internal class CompressedStream: Stream + internal class CompressedStream : Stream { private UInt32 HeaderSize; private UInt64 WritePosition; @@ -1541,7 +1540,7 @@ namespace WPinternals public override bool CanWrite { get { return true; } } public override long Length { get { return (long)WritePosition; } } public override void SetLength(long value) { throw new NotSupportedException(); } - public override void Write(byte[] buffer, int offset, int count) + public override void Write(byte[] buffer, int offset, int count) { WritePosition += (UInt64)count; UnderlyingStream.Write(buffer, offset, count); @@ -1558,7 +1557,7 @@ namespace WPinternals } } - internal class SeekableStream: Stream + internal class SeekableStream : Stream { private Stream UnderlyingStream; private Int64 ReadPosition = 0; @@ -1579,7 +1578,7 @@ namespace WPinternals UnderlyingStreamLength = UnderlyingStream.Length; } catch - { + { throw new ArgumentException("Unknown stream length"); } } @@ -1587,7 +1586,7 @@ namespace WPinternals public override bool CanRead { get { return true; } } public override bool CanSeek { get { return true; } } - public override int Read(byte[] buffer, int offset, int count) + public override int Read(byte[] buffer, int offset, int count) { int RealCount = UnderlyingStream.Read(buffer, offset, count); ReadPosition += RealCount; @@ -1642,19 +1641,19 @@ namespace WPinternals { return ReadPosition; } - set + set { Seek(value, SeekOrigin.Begin); } } public override bool CanTimeout { get { return UnderlyingStream.CanTimeout; } } public override bool CanWrite { get { return false; } } - public override long Length - { - get + public override long Length + { + get { return UnderlyingStreamLength; - } + } } public override void SetLength(long value) { throw new NotSupportedException(); } public override void Write(byte[] buffer, int offset, int count) { throw new NotSupportedException(); } @@ -1929,7 +1928,7 @@ namespace WPinternals /// public static class GridViewColumnResize { -#region DependencyProperties + #region DependencyProperties public static readonly DependencyProperty WidthProperty = DependencyProperty.RegisterAttached("Width", typeof(string), typeof(GridViewColumnResize), @@ -1948,7 +1947,7 @@ namespace WPinternals DependencyProperty.RegisterAttached("ListViewResizeBehaviorProperty", typeof(ListViewResizeBehavior), typeof(GridViewColumnResize), null); -#endregion + #endregion public static string GetWidth(DependencyObject obj) { @@ -1970,7 +1969,7 @@ namespace WPinternals obj.SetValue(EnabledProperty, value); } -#region CallBack + #region CallBack private static void OnSetWidthCallback(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e) { @@ -2025,10 +2024,10 @@ namespace WPinternals return behavior; } -#endregion + #endregion + + #region Nested type: GridViewColumnResizeBehavior -#region Nested type: GridViewColumnResizeBehavior - // This class was written by: Rolf Wessels // https://github.com/rolfwessels/lazycowprojects/tree/master/Wpf @@ -2103,13 +2102,13 @@ namespace WPinternals } } -#endregion + #endregion -#region Nested type: ListViewResizeBehavior + #region Nested type: ListViewResizeBehavior // This class was written by: Rolf Wessels // https://github.com/rolfwessels/lazycowprojects/tree/master/Wpf - + /// /// ListViewResizeBehavior class that gets attached to the ListView control /// @@ -2211,7 +2210,7 @@ namespace WPinternals } } -#endregion + #endregion } internal static class ExtensionMethods diff --git a/Models/ByteOperations.cs b/Models/ByteOperations.cs index ba5f656..4e1e050 100644 --- a/Models/ByteOperations.cs +++ b/Models/ByteOperations.cs @@ -365,7 +365,7 @@ namespace WPinternals uint crc = (uint)(((uint)0) ^ (-1)); for (var i = Offset; i < (Offset + Length); i++) { - crc = (crc >> 8) ^ CRC32Table[ (crc ^ Input[i]) & 0xFF ]; + crc = (crc >> 8) ^ CRC32Table[(crc ^ Input[i]) & 0xFF]; } crc = (uint)(crc ^ (-1)); diff --git a/Models/FFU.cs b/Models/FFU.cs index 228345a..faa4bba 100644 --- a/Models/FFU.cs +++ b/Models/FFU.cs @@ -442,7 +442,7 @@ namespace WPinternals byte[] mobilestartup = msms.ToArray(); Version OSVersion = PE.GetProductVersion(mobilestartup); s.Close(); - + return OSVersion.ToString(); } } diff --git a/Models/LZMA.cs b/Models/LZMA.cs index c0b2ee2..3297b25 100644 --- a/Models/LZMA.cs +++ b/Models/LZMA.cs @@ -39,7 +39,7 @@ namespace WPinternals Buffer.BlockCopy(Input, (int)Offset, Properties, 0, 5); UInt64 OutputSize = ByteOperations.ReadUInt64(Input, Offset + 5); - + SevenZip.Compression.LZMA.Decoder Coder = new SevenZip.Compression.LZMA.Decoder(); Coder.SetDecoderProperties(Properties); diff --git a/Models/LumiaDownloadModel.cs b/Models/LumiaDownloadModel.cs index fbc43bb..3e150f3 100644 --- a/Models/LumiaDownloadModel.cs +++ b/Models/LumiaDownloadModel.cs @@ -20,15 +20,15 @@ using System; using System.Collections.Generic; +using System.IO; using System.Linq; -using System.Text; -using System.Threading.Tasks; -using System.Runtime.Serialization; -using System.Runtime.Serialization.Json; using System.Net; using System.Net.Http; using System.Net.Http.Headers; -using System.IO; +using System.Runtime.Serialization; +using System.Runtime.Serialization.Json; +using System.Text; +using System.Threading.Tasks; using System.Xml; using System.Xml.Serialization; @@ -202,13 +202,13 @@ namespace WPinternals if (SoftwarePackages != null) { foreach (SoftwarePackage pkg in SoftwarePackages.softwarePackages) - Package = SoftwarePackages.softwarePackages.FirstOrDefault(); + Package = SoftwarePackages.softwarePackages.FirstOrDefault(); } } if (Package == null) throw new WPinternalsException("ENOSW package not found"); - + SoftwareFile FileInfo = Package.files.Where(f => f.fileName.EndsWith(".secwim", StringComparison.OrdinalIgnoreCase)).First(); SoftwareFile DPLF = Package.files.Where(f => f.fileName.EndsWith(".dpl", StringComparison.OrdinalIgnoreCase)).First(); @@ -231,11 +231,11 @@ namespace WPinternals if (DPLUrl == "") throw new WPinternalsException("DPL not found"); - + Task GetDPLStrTask = HttpClient.GetStringAsync(DPLUrl); GetDPLStrTask.Wait(); string DPLStrString = GetDPLStrTask.Result; - + DPL.Package dpl; XmlSerializer serializer = new XmlSerializer(typeof(DPL.Package)); using (StringReader reader = new StringReader(DPLStrString.Replace("ft:", "").Replace("dpl:", "").Replace("typedes:", ""))) @@ -246,9 +246,9 @@ namespace WPinternals foreach (DPL.File file in dpl.Content.Files.File) { string name = file.Name; - + DPL.Range range = file.Extensions.MmosWimFile.UseCaseCompatibilities.Compatibility.FirstOrDefault().Range; - + if (IsFirmwareBetween(PhoneFirmwareRevision, range.From, range.To)) FileInfo = Package.files.Where(f => f.fileName.EndsWith(name, StringComparison.OrdinalIgnoreCase)).First(); } @@ -363,7 +363,7 @@ namespace WPinternals } } - #pragma warning disable 0649 +#pragma warning disable 0649 [DataContract] internal class FileUrlResult { @@ -379,7 +379,7 @@ namespace WPinternals [DataMember] internal List checksum; } - #pragma warning restore 0649 +#pragma warning restore 0649 [DataContract] public class DiscoveryQueryParameters @@ -454,7 +454,7 @@ namespace WPinternals [DataMember] public List response; - public DiscoveryParameters(): this(DiscoveryCondition.Default) + public DiscoveryParameters() : this(DiscoveryCondition.Default) { } diff --git a/Models/MassStorage.cs b/Models/MassStorage.cs index 78164be..b7e8b21 100644 --- a/Models/MassStorage.cs +++ b/Models/MassStorage.cs @@ -26,7 +26,7 @@ using System.Runtime.InteropServices; namespace WPinternals { - internal class MassStorage: NokiaPhoneModel + internal class MassStorage : NokiaPhoneModel { internal string Drive = null; internal string PhysicalDrive = null; @@ -36,8 +36,8 @@ namespace WPinternals private bool OpenWithWriteAccess; private QualcommSerial Serial; - - internal MassStorage(string DevicePath): base(DevicePath) + + internal MassStorage(string DevicePath) : base(DevicePath) { try { @@ -288,7 +288,7 @@ namespace WPinternals ProgressUpdater Progress = UpdaterPerSector; if ((Progress == null) && (ProgressUpdateCallback != null)) Progress = new ProgressUpdater(SectorCount, ProgressUpdateCallback); - + byte[] Buffer; if (SectorCount >= 0x80) Buffer = new byte[0x10000]; @@ -425,13 +425,13 @@ namespace WPinternals OpenVolume(true); SetSectorPosition(StartSector); - + byte[] Buffer; using (BinaryReader Reader = new BinaryReader(File.Open(Path, FileMode.Open))) { ProgressUpdater Progress = UpdaterPerSector; - if ((Progress == null) && (ProgressUpdateCallback != null)) + if ((Progress == null) && (ProgressUpdateCallback != null)) Progress = new ProgressUpdater((UInt64)(Reader.BaseStream.Length / 0x200), ProgressUpdateCallback); if (Reader.BaseStream.Length >= 0x10000) @@ -443,9 +443,9 @@ namespace WPinternals for (UInt64 i = 0; i < (UInt64)(Reader.BaseStream.Length / 0x200); i += 0x80) { Count = Reader.Read(Buffer, 0, Buffer.Length); - + WriteSectors(Buffer, (uint)Count); - + if (Progress != null) Progress.IncreaseProgress((ulong)Count / 0x200); } diff --git a/Models/NativeMethods.cs b/Models/NativeMethods.cs index 3fa5c8e..07ae6eb 100644 --- a/Models/NativeMethods.cs +++ b/Models/NativeMethods.cs @@ -18,10 +18,10 @@ // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. -using System; -using System.Runtime.InteropServices; -using System.Runtime.ConstrainedExecution; using Microsoft.Win32.SafeHandles; +using System; +using System.Runtime.ConstrainedExecution; +using System.Runtime.InteropServices; using System.Security; namespace WPinternals diff --git a/Models/NokiaFlashModel.cs b/Models/NokiaFlashModel.cs index 57f455b..ca81d42 100644 --- a/Models/NokiaFlashModel.cs +++ b/Models/NokiaFlashModel.cs @@ -100,7 +100,7 @@ namespace WPinternals uint? flags = ReadSecurityFlags(); if (!flags.HasValue) return null; - + var finalconfig = (Fuse)flags.Value; return finalconfig.HasFlag(fuse); } @@ -186,7 +186,7 @@ namespace WPinternals public void SendFfuHeaderV1(byte[] FfuHeader, byte Options = 0) { byte[] Request = new byte[FfuHeader.Length + 0x20]; - + string Header = "NOKXFS"; System.Buffer.BlockCopy(System.Text.Encoding.ASCII.GetBytes(Header), 0, Request, 0, Header.Length); System.Buffer.BlockCopy(BigEndian.GetBytes(0x0001, 2), 0, Request, 0x06, 2); // Protocol version = 0x0001 @@ -279,7 +279,7 @@ namespace WPinternals System.Buffer.BlockCopy(BigEndian.GetBytes(0x0000001B, 4), 0, Request, 0x0C, 4); // Subblock type for Payload v2 = 0x1B System.Buffer.BlockCopy(BigEndian.GetBytes(FfuChunk.Length + 0x0C, 4), 0, Request, 0x10, 4); // Subblock length = length of chunk + 0x08 - + System.Buffer.BlockCopy(BigEndian.GetBytes(FfuChunk.Length, 4), 0, Request, 0x14, 4); // Payload length = length of chunk Request[0x18] = Options; // Data options = 0 (1 = verify) @@ -368,18 +368,18 @@ namespace WPinternals if (ResultCode != 0) ThrowFlashError(ResultCode); } - + internal void SwitchToMmosContext() { byte[] Request = new byte[7]; ByteOperations.WriteAsciiString(Request, 0, "NOKXCBA"); ExecuteRawVoidMethod(Request); - + ResetDevice(); Dispose(true); } - + private void ThrowFlashError(int ErrorCode) { string SubMessage; @@ -549,11 +549,11 @@ namespace WPinternals MMOSFile.Read(data, 0, (int)(length - offset)); LoadMmosBinary(length, (uint)offset, false, data); } - + SwitchToMmosContext(); ResetPhone(); } - + LogFile.EndAction("FlashMMOS"); } @@ -613,9 +613,9 @@ namespace WPinternals // If this function is used with a locked BootMgr v1, // then the mode-switching should be done outside this function, // because the context-switches that are used here are not supported on BootMgr v1. - + // Only works in BootLoader-mode or on unlocked bootloaders in Flash-mode!! - + PhoneInfo Info = ReadPhoneInfo(ExtendedInfo: false); FlashAppType OriginalAppType = Info.App; bool Switch = ((Info.App != FlashAppType.BootManager) && Info.SecureFfuEnabled && !Info.Authenticated && !Info.RdcPresent); @@ -1112,7 +1112,7 @@ namespace WPinternals ExecuteRawMethod(Request); } - internal enum SecureBootKeyType: byte + internal enum SecureBootKeyType : byte { Retail = 0, Engineering = 1 @@ -1154,7 +1154,7 @@ namespace WPinternals public string Imei; // Extended info public string Firmware; // Extended info public byte[] RKH; // Extended info - + public FlashAppType App; public byte FlashAppVersionMajor; diff --git a/Models/NokiaPhoneModel.cs b/Models/NokiaPhoneModel.cs index 9e71c27..02c99d1 100644 --- a/Models/NokiaPhoneModel.cs +++ b/Models/NokiaPhoneModel.cs @@ -27,7 +27,7 @@ using System.Linq; namespace WPinternals { - internal class NokiaPhoneModel: IDisposable + internal class NokiaPhoneModel : IDisposable { protected bool Disposed = false; private USBDevice Device = null; diff --git a/Models/Privileges.cs b/Models/Privileges.cs index 795e5c5..74cbe74 100644 --- a/Models/Privileges.cs +++ b/Models/Privileges.cs @@ -21,15 +21,15 @@ using System; using System.Collections.Specialized; using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; using System.Runtime.ConstrainedExecution; +using System.Runtime.InteropServices; using System.Threading; namespace WPinternals { using Luid = NativeMethods.LUID; - using Win32Exception = System.ComponentModel.Win32Exception; using PrivilegeNotHeldException = System.Security.AccessControl.PrivilegeNotHeldException; + using Win32Exception = System.ComponentModel.Win32Exception; internal delegate void PrivilegedCallback(object state); diff --git a/Models/QualcommPartition.cs b/Models/QualcommPartition.cs index 9a7332f..221bbdf 100644 --- a/Models/QualcommPartition.cs +++ b/Models/QualcommPartition.cs @@ -47,7 +47,7 @@ namespace WPinternals internal uint CertificatesOffset; internal byte[] RootKeyHash = null; - internal QualcommPartition(string Path): this(File.ReadAllBytes(Path)) { } + internal QualcommPartition(string Path) : this(File.ReadAllBytes(Path)) { } internal QualcommPartition(byte[] Binary, uint Offset = 0) { diff --git a/Models/QualcommSahara.cs b/Models/QualcommSahara.cs index 6015005..3b75924 100644 --- a/Models/QualcommSahara.cs +++ b/Models/QualcommSahara.cs @@ -23,7 +23,7 @@ using System.Threading.Tasks; namespace WPinternals { - internal enum SaharaMode: uint + internal enum SaharaMode : uint { ImageTransferPending = 0x00, ImagetransferComplete = 0x01, @@ -154,7 +154,7 @@ namespace WPinternals LogFile.Log("MaxLength: 0x" + ByteOperations.ReadUInt32(Hello, 0x10).ToString("X8"), LogType.FileOnly); LogFile.Log("Mode: 0x" + ByteOperations.ReadUInt32(Hello, 0x14).ToString("X8"), LogType.FileOnly); - byte[] HelloResponse = new byte[] { + byte[] HelloResponse = new byte[] { 0x02, 0x00, 0x00, 0x00, 0x30, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 @@ -233,7 +233,7 @@ namespace WPinternals Incoming = System.Text.Encoding.ASCII.GetString(Serial.GetResponse(null)); LogFile.Log("In: " + Incoming, LogType.FileOnly); }; - + LogFile.Log("Incoming Hello-response received", LogType.FileOnly); HandshakeCompleted = true; } diff --git a/Models/QualcommSerial.cs b/Models/QualcommSerial.cs index aeca980..9ab23e9 100644 --- a/Models/QualcommSerial.cs +++ b/Models/QualcommSerial.cs @@ -24,7 +24,7 @@ using System.IO.Ports; namespace WPinternals { - internal class QualcommSerial: IDisposable + internal class QualcommSerial : IDisposable { private bool Disposed = false; private SerialPort Port = null; @@ -37,7 +37,7 @@ namespace WPinternals public QualcommSerial(string DevicePath) { CRC16 = new CRC16(0x1189, 0xFFFF, 0xFFFF); - + string[] DevicePathElements = DevicePath.Split(new char[] { '#' }); if (string.Compare(DevicePathElements[3], "{86E0D1E0-8089-11D0-9CE4-08003E301F73}", true) == 0) { @@ -132,7 +132,7 @@ namespace WPinternals for (int i = 0; i < ResponsePattern.Length; i++) if (DecodedResponse[i] != ResponsePattern[i]) { - byte[] LogResponse = new byte[DecodedResponse.Length < 0x10 ? DecodedResponse.Length: 0x10]; + byte[] LogResponse = new byte[DecodedResponse.Length < 0x10 ? DecodedResponse.Length : 0x10]; LogFile.Log("Qualcomm serial response: " + Converter.ConvertHexToString(LogResponse, ""), LogType.FileOnly); LogFile.Log("Expected: " + Converter.ConvertHexToString(ResponsePattern, ""), LogType.FileOnly); throw new BadMessageException(); @@ -292,7 +292,7 @@ namespace WPinternals public class CRC16 { - private UInt16[] ChecksumTable = + private UInt16[] ChecksumTable = new UInt16[] { 0x0000, 0x1189, 0x2312, 0x329b, 0x4624, 0x57ad, 0x6536, 0x74bf, 0x8c48, 0x9dc1, 0xaf5a, 0xbed3, 0xca6c, 0xdbe5, 0xe97e, 0xf8f7, diff --git a/Models/SBL1.cs b/Models/SBL1.cs index 246c900..e5f5492 100644 --- a/Models/SBL1.cs +++ b/Models/SBL1.cs @@ -22,14 +22,14 @@ using System; namespace WPinternals { - internal class SBL1: QualcommPartition + internal class SBL1 : QualcommPartition { - internal SBL1(byte[] Binary): base(Binary, 0x2800) { } + internal SBL1(byte[] Binary) : base(Binary, 0x2800) { } internal byte[] GenerateExtraSector(byte[] PartitionHeader) { UInt32? Offset = ByteOperations.FindPattern(Binary, - new byte[] { + new byte[] { 0x15, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1B, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 @@ -56,7 +56,7 @@ namespace WPinternals Offset = ByteOperations.FindPattern(Binary, new byte[] { - 0x01, 0xFF, 0xA0, 0xE3, 0xFF, 0xFF, 0xA0, 0xE1, 0x1C, 0xD0, 0x8D, 0xE2, 0xF0, 0x4F, 0xBD, 0xE8, + 0x01, 0xFF, 0xA0, 0xE3, 0xFF, 0xFF, 0xA0, 0xE1, 0x1C, 0xD0, 0x8D, 0xE2, 0xF0, 0x4F, 0xBD, 0xE8, 0x1E, 0xFF, 0x2F, 0xE1 }, new byte[] { diff --git a/Models/SBL2.cs b/Models/SBL2.cs index 8c4e05b..bc2242b 100644 --- a/Models/SBL2.cs +++ b/Models/SBL2.cs @@ -42,7 +42,7 @@ namespace WPinternals 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }, null); - + if (PatchOffset == null) throw new BadImageFormatException(); diff --git a/Models/SBL3.cs b/Models/SBL3.cs index 5b613fe..f3ce784 100644 --- a/Models/SBL3.cs +++ b/Models/SBL3.cs @@ -35,7 +35,7 @@ namespace WPinternals internal SBL3(string FileName) { Binary = null; - + // First try to parse as FFU try { @@ -52,7 +52,7 @@ namespace WPinternals { byte[] SBL3Header; byte[] SBL3Pattern = new byte[] { 0x18, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF0, 0x8F, 0xFF, 0xFF, 0xFF, 0xFF }; - byte[] SBL3Mask = new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF }; + byte[] SBL3Mask = new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF }; UInt32? Offset = ByteOperations.FindPatternInFile(FileName, SBL3Pattern, SBL3Mask, out SBL3Header); diff --git a/Models/UEFI.cs b/Models/UEFI.cs index 444737f..58023c9 100644 --- a/Models/UEFI.cs +++ b/Models/UEFI.cs @@ -324,7 +324,7 @@ namespace WPinternals Buffer.BlockCopy( DecompressedImage, (int)(File.BinaryOffset + OldBinarySize + OldSectionPadding), - NewImage, + NewImage, (int)(File.BinaryOffset + NewBinarySize + NewSectionPadding), (int)(File.FileOffset + OldFileSize - File.BinaryOffset - OldBinarySize - OldSectionPadding)); @@ -334,8 +334,8 @@ namespace WPinternals // Copy volume-tail Buffer.BlockCopy( - DecompressedImage, - (int)(File.FileOffset + OldFileSize + OldFilePadding), + DecompressedImage, + (int)(File.FileOffset + OldFileSize + OldFilePadding), NewImage, (int)(File.FileOffset + NewFileSize + NewFilePadding), (int)(DecompressedImage.Length - File.FileOffset - OldFileSize - OldFilePadding)); @@ -386,7 +386,7 @@ namespace WPinternals // The new binary will include the Qualcomm header, but not the signature and certificates, because they won't match anyway. byte[] NewBinary = new byte[Binary.Length]; Buffer.BlockCopy(Binary, 0, NewBinary, 0, (int)CompressedSubImageOffset); - + ByteOperations.WriteUInt32(NewBinary, 0x10, ByteOperations.ReadUInt32(NewBinary, 0x14)); // Complete image size - does not include signature and certs anymore ByteOperations.WriteUInt32(NewBinary, 0x18, 0x00000000); // Address of signature ByteOperations.WriteUInt32(NewBinary, 0x1C, 0x00000000); // Signature length @@ -433,7 +433,7 @@ namespace WPinternals if (NewCompressedImage.Length > CompressedSubImageSize) { - Buffer.BlockCopy(Binary, (int)(FileHeaderOffset + OldFileSize + OldFilePadding), NewBinary, (int)(FileHeaderOffset + NewFileSize + NewFilePadding), + Buffer.BlockCopy(Binary, (int)(FileHeaderOffset + OldFileSize + OldFilePadding), NewBinary, (int)(FileHeaderOffset + NewFileSize + NewFilePadding), (int)(VolumeHeaderOffset + VolumeSize - FileHeaderOffset - NewFileSize - NewFilePadding)); } else @@ -548,8 +548,8 @@ namespace WPinternals byte[] SecurityDxe = GetFile("SecurityDxe"); ClearEfiChecksum(SecurityDxe); - UInt32? PatchOffset = ByteOperations.FindPattern(SecurityDxe, - new byte[] { 0xF0, 0x41, 0x2D, 0xE9, 0xFF, 0xFF, 0xB0, 0xE1, 0x28, 0xD0, 0x4D, 0xE2, 0xFF, 0xFF, 0xA0, 0xE1, 0x00, 0x00, 0xFF, 0x13, 0x20, 0xFF, 0xA0, 0xE3 }, + UInt32? PatchOffset = ByteOperations.FindPattern(SecurityDxe, + new byte[] { 0xF0, 0x41, 0x2D, 0xE9, 0xFF, 0xFF, 0xB0, 0xE1, 0x28, 0xD0, 0x4D, 0xE2, 0xFF, 0xFF, 0xA0, 0xE1, 0x00, 0x00, 0xFF, 0x13, 0x20, 0xFF, 0xA0, 0xE3 }, new byte[] { 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x00, 0x00, 0xFF, 0x00, 0x00 }, null); diff --git a/Properties/AssemblyInfo.cs b/Properties/AssemblyInfo.cs index d15d4f2..0ed7563 100644 --- a/Properties/AssemblyInfo.cs +++ b/Properties/AssemblyInfo.cs @@ -1,6 +1,4 @@ using System.Reflection; -using System.Resources; -using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Windows; @@ -33,11 +31,11 @@ using System.Windows; [assembly: ThemeInfo( ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located - //(used if a resource is not found in the page, - // or application resource dictionaries) + //(used if a resource is not found in the page, + // or application resource dictionaries) ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located - //(used if a resource is not found in the page, - // app, or any theme specific resource dictionaries) + //(used if a resource is not found in the page, + // app, or any theme specific resource dictionaries) )] diff --git a/ViewModels/AboutViewModel.cs b/ViewModels/AboutViewModel.cs index c626539..61e6903 100644 --- a/ViewModels/AboutViewModel.cs +++ b/ViewModels/AboutViewModel.cs @@ -20,7 +20,7 @@ namespace WPinternals { - internal class AboutViewModel: ContextViewModel + internal class AboutViewModel : ContextViewModel { internal AboutViewModel() : base() { } diff --git a/ViewModels/BackupTargetSelectionViewModel.cs b/ViewModels/BackupTargetSelectionViewModel.cs index d915981..ebe4627 100644 --- a/ViewModels/BackupTargetSelectionViewModel.cs +++ b/ViewModels/BackupTargetSelectionViewModel.cs @@ -23,7 +23,7 @@ using System.Threading; namespace WPinternals { - internal class BackupTargetSelectionViewModel: ContextViewModel + internal class BackupTargetSelectionViewModel : ContextViewModel { private PhoneNotifierViewModel PhoneNotifier; private Action BackupCallback; diff --git a/ViewModels/BackupViewModel.cs b/ViewModels/BackupViewModel.cs index cb96677..761fb5c 100644 --- a/ViewModels/BackupViewModel.cs +++ b/ViewModels/BackupViewModel.cs @@ -26,7 +26,7 @@ using System.Threading; namespace WPinternals { - internal class BackupViewModel: ContextViewModel + internal class BackupViewModel : ContextViewModel { private PhoneNotifierViewModel PhoneNotifier; private Action Callback; @@ -413,7 +413,7 @@ namespace WPinternals { Partition = GPT.Partitions.Where(p => p.Name == "BACKUP_BS_NV").First(); } - + TotalSizeSectors += Partition.SizeInSectors; PartitionCount++; } diff --git a/ViewModels/BusyViewModel.cs b/ViewModels/BusyViewModel.cs index 849eac4..39d1426 100644 --- a/ViewModels/BusyViewModel.cs +++ b/ViewModels/BusyViewModel.cs @@ -103,7 +103,7 @@ namespace WPinternals OnPropertyChanged("SubMessage"); } } - + private int? _ProgressPercentage = null; public int? ProgressPercentage { @@ -148,7 +148,7 @@ namespace WPinternals { NewText = "Progress: " + ((int)ProgressPercentage).ToString() + "%"; } - if (TimeRemaining != null) + if (TimeRemaining != null) { if (NewText == null) NewText = ""; diff --git a/ViewModels/ContextViewModel.cs b/ViewModels/ContextViewModel.cs index 970c379..6de1bbc 100644 --- a/ViewModels/ContextViewModel.cs +++ b/ViewModels/ContextViewModel.cs @@ -49,7 +49,7 @@ namespace WPinternals } } } - + private ContextViewModel _SubContextViewModel; public ContextViewModel SubContextViewModel { @@ -73,11 +73,11 @@ namespace WPinternals UIContext = SynchronizationContext.Current; } - internal ContextViewModel(MainViewModel Main): this() + internal ContextViewModel(MainViewModel Main) : this() { } - internal ContextViewModel(MainViewModel Main, ContextViewModel SubContext): this(Main) + internal ContextViewModel(MainViewModel Main, ContextViewModel SubContext) : this(Main) { SubContextViewModel = SubContext; } diff --git a/ViewModels/DisclaimerAndNdaViewModel.cs b/ViewModels/DisclaimerAndNdaViewModel.cs index ea7cada..005d653 100644 --- a/ViewModels/DisclaimerAndNdaViewModel.cs +++ b/ViewModels/DisclaimerAndNdaViewModel.cs @@ -29,7 +29,7 @@ namespace WPinternals Action Accepted; internal DisclaimerAndNdaViewModel(Action Accepted) - : base() + : base() { this.Accepted = Accepted; } diff --git a/ViewModels/DisclaimerViewModel.cs b/ViewModels/DisclaimerViewModel.cs index 317b539..a09f398 100644 --- a/ViewModels/DisclaimerViewModel.cs +++ b/ViewModels/DisclaimerViewModel.cs @@ -31,7 +31,7 @@ namespace WPinternals Action Accepted; internal DisclaimerViewModel(Action Accepted) - : base() + : base() { this.Accepted = Accepted; } diff --git a/ViewModels/DownloadsViewModel.cs b/ViewModels/DownloadsViewModel.cs index 008b89e..e633b20 100644 --- a/ViewModels/DownloadsViewModel.cs +++ b/ViewModels/DownloadsViewModel.cs @@ -32,7 +32,7 @@ using System.Windows.Data; namespace WPinternals { - internal class DownloadsViewModel: ContextViewModel + internal class DownloadsViewModel : ContextViewModel { private PhoneNotifierViewModel Notifier; private Timer SpeedTimer; @@ -56,7 +56,7 @@ namespace WPinternals AddFFUCommand = new DelegateCommand(() => { string FFUPath = null; - + Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog(); dlg.DefaultExt = ".ffu"; // Default file extension dlg.Filter = "ROM images (.ffu)|*.ffu"; // Filter files by extension @@ -82,7 +82,7 @@ namespace WPinternals { LastStatusText = "Error: File \"" + FFUFile + "\" was not added."; } - + } else { @@ -496,7 +496,7 @@ namespace WPinternals Failed }; - internal class DownloadEntry: INotifyPropertyChanged + internal class DownloadEntry : INotifyPropertyChanged { private SynchronizationContext UIContext; public event PropertyChangedEventHandler PropertyChanged = delegate { }; diff --git a/ViewModels/DumpRomTargetSelectionViewModel.cs b/ViewModels/DumpRomTargetSelectionViewModel.cs index 4734ebd..32a4b0d 100644 --- a/ViewModels/DumpRomTargetSelectionViewModel.cs +++ b/ViewModels/DumpRomTargetSelectionViewModel.cs @@ -23,7 +23,7 @@ using System.Threading; namespace WPinternals { - internal class DumpRomTargetSelectionViewModel: ContextViewModel + internal class DumpRomTargetSelectionViewModel : ContextViewModel { private Action DumpCallback; internal Action SwitchToUnlockBoot; diff --git a/ViewModels/DumpRomViewModel.cs b/ViewModels/DumpRomViewModel.cs index 5244b1c..5454ae3 100644 --- a/ViewModels/DumpRomViewModel.cs +++ b/ViewModels/DumpRomViewModel.cs @@ -24,7 +24,7 @@ using System.Threading; namespace WPinternals { - internal class DumpRomViewModel: ContextViewModel + internal class DumpRomViewModel : ContextViewModel { private Action SwitchToUnlockBoot; private Action SwitchToUnlockRoot; @@ -56,7 +56,7 @@ namespace WPinternals ActivateSubContext(new BusyViewModel("Initializing ROM dump...")); ulong TotalSizeSectors = 0; - int PartitionCount = 0; + int PartitionCount = 0; Partition Partition; FFU FFU = null; try diff --git a/ViewModels/GettingStartedViewModel.cs b/ViewModels/GettingStartedViewModel.cs index 4c872e4..0ab2cb0 100644 --- a/ViewModels/GettingStartedViewModel.cs +++ b/ViewModels/GettingStartedViewModel.cs @@ -22,7 +22,7 @@ using System; namespace WPinternals { - internal class GettingStartedViewModel: ContextViewModel + internal class GettingStartedViewModel : ContextViewModel { internal Action ShowDisclaimer; internal Action SwitchToUnlockBoot; diff --git a/ViewModels/LumiaFlashRomSourceSelectionViewModel.cs b/ViewModels/LumiaFlashRomSourceSelectionViewModel.cs index a4386cb..bf492c9 100644 --- a/ViewModels/LumiaFlashRomSourceSelectionViewModel.cs +++ b/ViewModels/LumiaFlashRomSourceSelectionViewModel.cs @@ -23,7 +23,7 @@ using System.Threading; namespace WPinternals { - internal class LumiaFlashRomSourceSelectionViewModel: ContextViewModel + internal class LumiaFlashRomSourceSelectionViewModel : ContextViewModel { private PhoneNotifierViewModel PhoneNotifier; private Action FlashPartitionsCallback; diff --git a/ViewModels/LumiaFlashRomViewModel.cs b/ViewModels/LumiaFlashRomViewModel.cs index faf69c7..3899969 100644 --- a/ViewModels/LumiaFlashRomViewModel.cs +++ b/ViewModels/LumiaFlashRomViewModel.cs @@ -28,7 +28,7 @@ using System.Threading.Tasks; namespace WPinternals { - internal class LumiaFlashRomViewModel: ContextViewModel + internal class LumiaFlashRomViewModel : ContextViewModel { private PhoneNotifierViewModel PhoneNotifier; internal Action SwitchToUnlockBoot; @@ -178,7 +178,7 @@ namespace WPinternals else if ((MainOSNewSectorCount > 0) && (MainOSNewSectorCount > MainOSOldSectorCount)) { LogFile.Log("Flash failed! Size of partition 'MainOS' is too big."); - ExitFailure("Flash failed!", "Size of partition 'MainOS' is too big."); + ExitFailure("Flash failed!", "Size of partition 'MainOS' is too big."); return; } else if ((DataNewSectorCount > 0) && (DataNewSectorCount > DataOldSectorCount)) @@ -220,7 +220,7 @@ namespace WPinternals i++; Busy.Message = "Flashing partition MainOS (" + i.ToString() + @"/" + PartitionCount.ToString() + ")"; Phone.FlashRawPartition(MainOSPath, "MainOS", Updater); - } + } } catch (Exception Ex) { @@ -249,7 +249,7 @@ namespace WPinternals if (!Result) { - ExitFailure("Flash failed!", null); + ExitFailure("Flash failed!", null); return; } @@ -344,7 +344,7 @@ namespace WPinternals TotalSizeSectors += StreamLengthInSectors; PartitionCount++; - + if (string.Compare(PartitionName, "MainOS", true) == 0) { MainOSOldSectorCount = Partition.SizeInSectors; @@ -467,7 +467,7 @@ namespace WPinternals ExitSuccess("Flash successful! Make sure you disable Windows Update on the phone!", null); }).Start(); } - + // Called from an event-handler. So, "async void" is valid here. internal async void FlashFFU(string FFUPath) { @@ -628,7 +628,7 @@ namespace WPinternals NokiaFlashModel Phone = (NokiaFlashModel)PhoneNotifier.CurrentModel; if (PhoneNotifier.CurrentInterface == PhoneInterfaces.Lumia_Bootloader) Phone.SwitchToFlashAppContext(); - + new Thread(() => { bool Result = true; @@ -722,7 +722,7 @@ namespace WPinternals internal void ExitFailure(string Message, string SubMessage) { - MessageViewModel ErrorMessageViewModel = new MessageViewModel(Message, () => + MessageViewModel ErrorMessageViewModel = new MessageViewModel(Message, () => { IsSwitchingInterface = false; Callback(); diff --git a/ViewModels/LumiaInfoViewModel.cs b/ViewModels/LumiaInfoViewModel.cs index a1ff095..e7f7655 100644 --- a/ViewModels/LumiaInfoViewModel.cs +++ b/ViewModels/LumiaInfoViewModel.cs @@ -22,7 +22,7 @@ using System; namespace WPinternals { - internal class LumiaInfoViewModel: ContextViewModel + internal class LumiaInfoViewModel : ContextViewModel { internal PhoneInterfaces? CurrentInterface; internal IDisposable CurrentModel; diff --git a/ViewModels/LumiaModeViewModel.cs b/ViewModels/LumiaModeViewModel.cs index 4473ef9..011807a 100644 --- a/ViewModels/LumiaModeViewModel.cs +++ b/ViewModels/LumiaModeViewModel.cs @@ -111,7 +111,8 @@ namespace WPinternals catch (Exception Ex) { IsSwitchingInterface = false; - ActivateSubContext(new MessageViewModel(Ex.Message, () => { + ActivateSubContext(new MessageViewModel(Ex.Message, () => + { Callback(); Refresh(); })); diff --git a/ViewModels/LumiaUnlockBootViewModel.cs b/ViewModels/LumiaUnlockBootViewModel.cs index a529199..c595df2 100644 --- a/ViewModels/LumiaUnlockBootViewModel.cs +++ b/ViewModels/LumiaUnlockBootViewModel.cs @@ -519,7 +519,7 @@ namespace WPinternals SuccessMessageViewModel.SubMessage = SubMessage; ActivateSubContext(SuccessMessageViewModel); } - + void NewDeviceArrived(ArrivalEventArgs Args) { // Do not start on a new thread, because EvaluateViewState will also create new ViewModels and those should be created on the UI thread. diff --git a/ViewModels/LumiaUnlockBootloaderViewModel.cs b/ViewModels/LumiaUnlockBootloaderViewModel.cs index c4eae1e..91a6dc9 100644 --- a/ViewModels/LumiaUnlockBootloaderViewModel.cs +++ b/ViewModels/LumiaUnlockBootloaderViewModel.cs @@ -52,7 +52,7 @@ namespace WPinternals byte[] RebootCommand = new byte[] { 0x4E, 0x4F, 0x4B, 0x52 }; // NOKR FlashModel.ExecuteRawVoidMethod(RebootCommand); } - + private static void SendLoader(PhoneNotifierViewModel PhoneNotifier, List PossibleLoaders) { // Assume 9008 mode @@ -123,13 +123,13 @@ namespace WPinternals if (Notifier.CurrentInterface == PhoneInterfaces.Lumia_Bootloader) ((NokiaFlashModel)Notifier.CurrentModel).ContinueBoot(); - + if (Notifier.CurrentInterface != PhoneInterfaces.Lumia_Normal) { ExitFailure("Failed to relock phone", "Your phone is half relocked. You may need to reflash a stock ROM"); return; } - + ExitSuccess("Bootloader restored successfully!"); } @@ -165,7 +165,7 @@ namespace WPinternals ExitFailure("Failed to unlock phone", "Your phone is half unlocked. You may need to reflash a stock ROM"); return; } - + ExitSuccess("Bootloader unlocked successfully!", null); } @@ -184,7 +184,7 @@ namespace WPinternals if (UpdateWorkingStatus == null) UpdateWorkingStatus = (m, s, v, st) => { }; if (ExitSuccess == null) ExitSuccess = (m, s) => { }; if (ExitFailure == null) ExitFailure = (m, s) => { }; - + try { if (Notifier.CurrentModel is NokiaFlashModel) @@ -404,7 +404,7 @@ namespace WPinternals LogFile.LogException(Ex); throw new Exception("Error: Parsing SBL3 from FFU failed."); } - + if (DumpPartitions) { try @@ -481,7 +481,7 @@ namespace WPinternals LogFile.Log("Flash GPT at 0x" + ((UInt32)0x200).ToString("X8")); CurrentModel.FlashSectors(1, GPT, 0); Progress.SetProgress(0x21); - + LogFile.Log("Flash SBL2 at 0x" + ((UInt32)NewGPT.GetPartition("SBL2").FirstSector * 0x200).ToString("X8")); CurrentModel.FlashRawPartition(SBL2, "SBL2", Progress); LogFile.Log("Flash SBL3 at 0x" + ((UInt32)NewGPT.GetPartition("SBL3").FirstSector * 0x200).ToString("X8")); @@ -669,7 +669,7 @@ namespace WPinternals { LogFile.Log("Assembling data for unlock", LogType.FileAndConsole); SetWorkingStatus("Assembling data for unlock", null, null); - + if ((FFUPath == null) || (FFUPath.Length == 0)) throw new ArgumentNullException("FFU path is missing"); @@ -679,7 +679,7 @@ namespace WPinternals bool DumpPartitions = false; string DumpFilePrefix = Environment.ExpandEnvironmentVariables("%ALLUSERSPROFILE%\\WPInternals\\") + DateTime.Now.ToString("yyyy-MM-dd hh.mm.ss") + " - "; bool IsBootLoaderUnlocked = false; - + FFU FFU = null; try { @@ -698,7 +698,7 @@ namespace WPinternals throw new Exception("Error: The version of the Flash Application on the phone could not be determined."); if ((FlashVersion.ApplicationMajor < 1) || ((FlashVersion.ApplicationMajor == 1) && (FlashVersion.ApplicationMinor < 28))) throw new Exception("Error: The version of the Flash Application on the phone is too old. Update your phone using Windows Updates or flash a newer ROM to your phone. Then try again."); - + UefiSecurityStatusResponse SecurityStatus = ((NokiaFlashModel)Notifier.CurrentModel).ReadSecurityStatus(); IsBootLoaderUnlocked = (SecurityStatus.AuthenticationStatus || SecurityStatus.RdcStatus || !SecurityStatus.SecureFfuEfuseStatus); } @@ -751,7 +751,7 @@ namespace WPinternals if (Notifier.CurrentInterface != PhoneInterfaces.Lumia_Bootloader) throw new WPinternalsException("Phone is in an unexpected mode."); - + NewGPT = ((NokiaFlashModel)Notifier.CurrentModel).ReadGPT(); await SwitchModeViewModel.SwitchTo(Notifier, PhoneInterfaces.Lumia_Flash); @@ -766,7 +766,7 @@ namespace WPinternals { NewGPT = FFU.GPT; } - + // Make sure all partitions are in range of the emergency flasher. NewGPT.RestoreBackupPartitions(); @@ -797,7 +797,7 @@ namespace WPinternals GPT = NewGPT.Rebuild(); } } - + if (DumpPartitions) { try @@ -1084,7 +1084,7 @@ namespace WPinternals { NokiaFlashModel CurrentModel = (NokiaFlashModel)Notifier.CurrentModel; LogFile.Log("Start flashing in Custom Flash mode"); - + UInt64 TotalSectorCount = (UInt64)0x21 + 1 + (UInt64)(SBL2.Length / 0x200) + (UInt64)(SBL3.Length / 0x200) + @@ -1092,7 +1092,7 @@ namespace WPinternals SetWorkingStatus("Flashing unlocked bootloader (part 1)...", MaxProgressValue: 100, Status: WPinternalsStatus.Flashing); ProgressUpdater Progress = new ProgressUpdater(TotalSectorCount, (int ProgressPercentage, TimeSpan? TimeSpan) => UpdateWorkingStatus("Flashing unlocked bootloader (part 1)...", CurrentProgressValue: (ulong)ProgressPercentage, Status: WPinternalsStatus.Flashing)); - + LogFile.Log("Flash GPT at 0x" + ((UInt32)0x200).ToString("X8")); CurrentModel.FlashSectors(1, GPT, 0); Progress.SetProgress(0x21); @@ -1198,7 +1198,7 @@ namespace WPinternals Flasher.Flash(Start, FFU.GetPartition("WINSECAPP"), Progress, 0, Length); Flasher.ClosePartition(); - + LogFile.Log("Partition closed. Flashing ready. Rebooting."); // Reboot phone to Flash app @@ -1359,7 +1359,7 @@ namespace WPinternals if (BackNV != null) UndoEFIESPPadding = true; } - + if (!IsSpecB) { await SwitchModeViewModel.SwitchTo(Notifier, PhoneInterfaces.Lumia_Flash); @@ -1809,7 +1809,7 @@ namespace WPinternals Parts[0].ProgressText = "Flashing unlocked bootloader (part 1)..."; else Parts[0].ProgressText = "Flashing unlocked bootloader (part 2)..."; - + // Now add NV partition Partition BACKUP_BS_NV = GPT.GetPartition("BACKUP_BS_NV"); Partition UEFI_BS_NV; @@ -1861,7 +1861,7 @@ namespace WPinternals } await LumiaUnlockBootloaderViewModel.LumiaFlashParts(Notifier, ProfileFFU.Path, false, false, Parts, true, false, true, true, false, SetWorkingStatus, UpdateWorkingStatus, null, null, EDEPath); - + if ((Notifier.CurrentInterface != PhoneInterfaces.Lumia_Bootloader) && (Notifier.CurrentInterface != PhoneInterfaces.Lumia_Flash)) await Notifier.WaitForArrival(); @@ -2145,12 +2145,12 @@ namespace WPinternals ((NokiaFlashModel)Notifier.CurrentModel).SwitchToFlashAppContext(); Parts = LumiaUnlockBootloaderViewModel.LumiaGenerateEFIESPFlashPayload(UnlockedEFIESP, GPT, ProfileFFU, IsSpecB); - + if (IsSpecB) Parts[0].ProgressText = "Flashing unlocked bootloader (part 2)..."; else Parts[0].ProgressText = "Flashing unlocked bootloader (part 3)..."; - + await LumiaUnlockBootloaderViewModel.LumiaFlashParts(Notifier, ProfileFFU.Path, false, false, Parts, true, true, true, true, false, SetWorkingStatus, UpdateWorkingStatus, null, null, EDEPath); if (!IsSpecB) @@ -2181,7 +2181,7 @@ namespace WPinternals Partition EFIESP = DeviceGPT.GetPartition("EFIESP"); UInt16 ReservedOGSectors = ByteOperations.ReadUInt16(DeviceFFU.GetPartition("EFIESP"), 0xE); - + UInt16 ReservedSectors = LumiaGetFirstEFIESPSectorCount(DeviceGPT, DeviceFFU, IsSpecB); Int32 EFIESPFirstPartSize = IsSpecB ? DeviceFFU.ChunkSize : (int)SectorSize * ReservedOGSectors; @@ -2218,7 +2218,7 @@ namespace WPinternals Int32 EFIESPFirstPartSize = IsSpecB ? DeviceFFU.ChunkSize : (int)SectorSize * ReservedOGSectors; byte[] FirstSector = DeviceFFU.GetPartition("EFIESP").Take(EFIESPFirstPartSize).ToArray(); - + List Parts = new List(); FlashPart Part = new FlashPart(); @@ -2256,7 +2256,7 @@ namespace WPinternals return ReservedSectors; } - + private static async Task LumiaFlashParts(PhoneNotifierViewModel Notifier, string FFUPath, bool PerformFullFlashFirst, bool SkipWrite, List Parts, bool DoResetFirst = true, bool ClearFlashingStatusAtEnd = true, bool CheckSectorAlignment = true, bool ShowProgress = true, bool Experimental = false, SetWorkingStatus SetWorkingStatus = null, UpdateWorkingStatus UpdateWorkingStatus = null, ExitSuccess ExitSuccess = null, ExitFailure ExitFailure = null, string EDEPath = null) { PhoneInfo Info = ((NokiaFlashModel)Notifier.CurrentModel).ReadPhoneInfo(); diff --git a/ViewModels/LumiaUnlockRootTargetSelectionViewModel.cs b/ViewModels/LumiaUnlockRootTargetSelectionViewModel.cs index fdcd6a2..0d10145 100644 --- a/ViewModels/LumiaUnlockRootTargetSelectionViewModel.cs +++ b/ViewModels/LumiaUnlockRootTargetSelectionViewModel.cs @@ -23,19 +23,19 @@ using System.Threading; namespace WPinternals { - internal class LumiaUnlockRootTargetSelectionViewModel: LumiaRootAccessTargetSelectionViewModel + internal class LumiaUnlockRootTargetSelectionViewModel : LumiaRootAccessTargetSelectionViewModel { public LumiaUnlockRootTargetSelectionViewModel(PhoneNotifierViewModel PhoneNotifier, Action SwitchToUnlockBoot, Action SwitchToDumpRom, Action SwitchToFlashRom, Action UnlockPhoneCallback, Action UnlockImageCallback) : base(PhoneNotifier, SwitchToUnlockBoot, SwitchToDumpRom, SwitchToFlashRom, UnlockPhoneCallback, UnlockImageCallback) { } } - internal class LumiaUndoRootTargetSelectionViewModel: LumiaRootAccessTargetSelectionViewModel + internal class LumiaUndoRootTargetSelectionViewModel : LumiaRootAccessTargetSelectionViewModel { public LumiaUndoRootTargetSelectionViewModel(PhoneNotifierViewModel PhoneNotifier, Action SwitchToUnlockBoot, Action SwitchToDumpRom, Action SwitchToFlashRom, Action UnlockPhoneCallback, Action UnlockImageCallback) : base(PhoneNotifier, SwitchToUnlockBoot, SwitchToDumpRom, SwitchToFlashRom, UnlockPhoneCallback, UnlockImageCallback) { } } - internal class LumiaRootAccessTargetSelectionViewModel: ContextViewModel + internal class LumiaRootAccessTargetSelectionViewModel : ContextViewModel { private PhoneNotifierViewModel PhoneNotifier; internal Action SwitchToUnlockBoot; diff --git a/ViewModels/LumiaUnlockRootViewModel.cs b/ViewModels/LumiaUnlockRootViewModel.cs index c832de3..7017835 100644 --- a/ViewModels/LumiaUnlockRootViewModel.cs +++ b/ViewModels/LumiaUnlockRootViewModel.cs @@ -24,7 +24,7 @@ using System.Threading; namespace WPinternals { - internal class LumiaUnlockRootViewModel: ContextViewModel + internal class LumiaUnlockRootViewModel : ContextViewModel { private PhoneNotifierViewModel PhoneNotifier; private Action SwitchToUnlockBoot; @@ -82,7 +82,8 @@ namespace WPinternals } catch (Exception Ex) { - ActivateSubContext(new MessageViewModel(Ex.Message, () => { + ActivateSubContext(new MessageViewModel(Ex.Message, () => + { Callback(); ActivateSubContext(null); })); diff --git a/ViewModels/MainViewModel.cs b/ViewModels/MainViewModel.cs index b8042fa..272dc6c 100644 --- a/ViewModels/MainViewModel.cs +++ b/ViewModels/MainViewModel.cs @@ -84,13 +84,13 @@ namespace WPinternals } private ContextViewModel _ContextViewModel; - public ContextViewModel ContextViewModel - { - get - { - return _ContextViewModel; - } - set + public ContextViewModel ContextViewModel + { + get + { + return _ContextViewModel; + } + set { if (_ContextViewModel != value) { @@ -103,7 +103,7 @@ namespace WPinternals } OnPropertyChanged("ContextViewModel"); } - } + } } private SynchronizationContext MainSyncContext; diff --git a/ViewModels/MessageViewModel.cs b/ViewModels/MessageViewModel.cs index 520443d..8bc0c46 100644 --- a/ViewModels/MessageViewModel.cs +++ b/ViewModels/MessageViewModel.cs @@ -22,7 +22,7 @@ using System; namespace WPinternals { - internal class MessageViewModel: ContextViewModel + internal class MessageViewModel : ContextViewModel { internal MessageViewModel(string Message, Action OkAction = null, Action CancelAction = null) : base() diff --git a/ViewModels/NokiaFlashViewModel.cs b/ViewModels/NokiaFlashViewModel.cs index 6064f05..98f7457 100644 --- a/ViewModels/NokiaFlashViewModel.cs +++ b/ViewModels/NokiaFlashViewModel.cs @@ -92,7 +92,7 @@ namespace WPinternals { SecurityFlags = (UInt32)CurrentModel.ReadSecurityFlags(); LogFile.Log("Security flags: 0x" + SecurityFlags.ToString("X8")); - + FinalConfigDakStatus = CurrentModel.ReadFuseStatus(NokiaFlashModel.Fuse.Dak); FinalConfigFastBootStatus = CurrentModel.ReadFuseStatus(NokiaFlashModel.Fuse.FastBoot); FinalConfigFfuVerifyStatus = CurrentModel.ReadFuseStatus(NokiaFlashModel.Fuse.FfuVerify); diff --git a/ViewModels/NokiaMassStorageViewModel.cs b/ViewModels/NokiaMassStorageViewModel.cs index 52ae572..f098e79 100644 --- a/ViewModels/NokiaMassStorageViewModel.cs +++ b/ViewModels/NokiaMassStorageViewModel.cs @@ -18,11 +18,9 @@ // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. -using System.Threading; - namespace WPinternals { - internal class NokiaMassStorageViewModel: ContextViewModel + internal class NokiaMassStorageViewModel : ContextViewModel { private MassStorage CurrentModel; diff --git a/ViewModels/NokiaModeFlashViewModel.cs b/ViewModels/NokiaModeFlashViewModel.cs index 3e7314d..8730240 100644 --- a/ViewModels/NokiaModeFlashViewModel.cs +++ b/ViewModels/NokiaModeFlashViewModel.cs @@ -19,11 +19,7 @@ // DEALINGS IN THE SOFTWARE. using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; using System.Threading; -using System.Threading.Tasks; namespace WPinternals { diff --git a/ViewModels/NokiaModeMassStorageViewModel.cs b/ViewModels/NokiaModeMassStorageViewModel.cs index cc9d95e..6c3c8aa 100644 --- a/ViewModels/NokiaModeMassStorageViewModel.cs +++ b/ViewModels/NokiaModeMassStorageViewModel.cs @@ -19,7 +19,6 @@ // DEALINGS IN THE SOFTWARE. using System; -using System.Collections.Generic; namespace WPinternals { diff --git a/ViewModels/NokiaModeNormalViewModel.cs b/ViewModels/NokiaModeNormalViewModel.cs index 08ee6d3..4217afc 100644 --- a/ViewModels/NokiaModeNormalViewModel.cs +++ b/ViewModels/NokiaModeNormalViewModel.cs @@ -22,7 +22,7 @@ using System; namespace WPinternals { - internal class NokiaModeNormalViewModel: ContextViewModel + internal class NokiaModeNormalViewModel : ContextViewModel { private NokiaPhoneModel CurrentModel; private Action RequestModeSwitch; diff --git a/ViewModels/NotImplementedViewModel.cs b/ViewModels/NotImplementedViewModel.cs index b272a04..3bd68da 100644 --- a/ViewModels/NotImplementedViewModel.cs +++ b/ViewModels/NotImplementedViewModel.cs @@ -20,7 +20,7 @@ namespace WPinternals { - internal class NotImplementedViewModel: ContextViewModel + internal class NotImplementedViewModel : ContextViewModel { internal string Message { get; set; } diff --git a/ViewModels/PhoneNotifierViewModel.cs b/ViewModels/PhoneNotifierViewModel.cs index 3ba7db9..997e720 100644 --- a/ViewModels/PhoneNotifierViewModel.cs +++ b/ViewModels/PhoneNotifierViewModel.cs @@ -162,7 +162,7 @@ namespace WPinternals LogFile.Log("Mode: Label", LogType.FileAndConsole); NewDeviceArrived(new ArrivalEventArgs((PhoneInterfaces)CurrentInterface, CurrentModel)); } - else if ((e.DevicePath.IndexOf("VID_0421&PID_0661", StringComparison.OrdinalIgnoreCase) >= 0) || + else if ((e.DevicePath.IndexOf("VID_0421&PID_0661", StringComparison.OrdinalIgnoreCase) >= 0) || (e.DevicePath.IndexOf("VID_0421&PID_06FC", StringComparison.OrdinalIgnoreCase) >= 0) || // VID_0421&PID_06FC is for Lumia 930 (e.DevicePath.IndexOf("vid_045e&pid_0a00", StringComparison.OrdinalIgnoreCase) >= 0)) // vid_045e & pid_0a00 & mi_03 = Lumia 950 XL normal mode { @@ -256,7 +256,8 @@ namespace WPinternals // It is not possible to invoke COM objects from a WndProc. // MassStorage uses ManagementObjectSearcher, which is a COM object. // Therefore we use a new thread. - ThreadPool.QueueUserWorkItem(s => { + ThreadPool.QueueUserWorkItem(s => + { lock (ModelLock) { if (!(CurrentModel is MassStorage)) @@ -392,7 +393,8 @@ namespace WPinternals (e.DevicePath.IndexOf("VID_05C6&PID_9008", StringComparison.OrdinalIgnoreCase) >= 0) || (e.DevicePath.IndexOf(@"disk&ven_qualcomm&prod_mmc_storage", StringComparison.OrdinalIgnoreCase) >= 0) || (e.DevicePath.IndexOf(@"DISK&VEN_MSFT&PROD_PHONE_MMC_STOR", StringComparison.OrdinalIgnoreCase) >= 0) - ) { + ) + { if (CurrentInterface != null) LastInterface = CurrentInterface; CurrentInterface = null; diff --git a/ViewModels/RegistrationViewModel.cs b/ViewModels/RegistrationViewModel.cs index 65de77f..1d1859f 100644 --- a/ViewModels/RegistrationViewModel.cs +++ b/ViewModels/RegistrationViewModel.cs @@ -29,7 +29,7 @@ namespace WPinternals Action Failed; internal RegistrationViewModel(Action Completed, Action Failed) - : base() + : base() { this.Completed = Completed; this.Failed = Failed; diff --git a/ViewModels/RestoreSourceSelectionViewModel.cs b/ViewModels/RestoreSourceSelectionViewModel.cs index f8b6538..9b8833a 100644 --- a/ViewModels/RestoreSourceSelectionViewModel.cs +++ b/ViewModels/RestoreSourceSelectionViewModel.cs @@ -23,7 +23,7 @@ using System.Threading; namespace WPinternals { - internal class RestoreSourceSelectionViewModel: ContextViewModel + internal class RestoreSourceSelectionViewModel : ContextViewModel { private PhoneNotifierViewModel PhoneNotifier; private Action RestoreCallback; diff --git a/ViewModels/RestoreViewModel.cs b/ViewModels/RestoreViewModel.cs index 9d133e5..eec82fc 100644 --- a/ViewModels/RestoreViewModel.cs +++ b/ViewModels/RestoreViewModel.cs @@ -24,7 +24,7 @@ using System.Threading; namespace WPinternals { - internal class RestoreViewModel: ContextViewModel + internal class RestoreViewModel : ContextViewModel { private PhoneNotifierViewModel PhoneNotifier; private Action Callback; diff --git a/ViewModels/SwitchModeViewModel.cs b/ViewModels/SwitchModeViewModel.cs index 0c5f241..bea517c 100644 --- a/ViewModels/SwitchModeViewModel.cs +++ b/ViewModels/SwitchModeViewModel.cs @@ -30,7 +30,7 @@ namespace WPinternals internal delegate void ModeSwitchErrorHandler(string Message); internal delegate void ModeSwitchSuccessHandler(IDisposable NewModel, PhoneInterfaces NewInterface); - internal class SwitchModeViewModel: ContextViewModel + internal class SwitchModeViewModel : ContextViewModel { protected PhoneNotifierViewModel PhoneNotifier; protected IDisposable CurrentModel; @@ -149,7 +149,8 @@ namespace WPinternals } else { - UIContext.Post(s => { + UIContext.Post(s => + { ModeSwitchProgress(Message, SubMessage); SetWorkingStatus(Message, SubMessage); }, null); @@ -555,7 +556,7 @@ namespace WPinternals LogFile.LogException(Ex); ModeSwitchErrorWrapper(Ex.Message); } - + LogFile.EndAction("SwitchToLabelMode"); }).Start(); } @@ -685,8 +686,8 @@ namespace WPinternals Part.StartSector = (uint)Target.FirstSector; Part.Stream = SB; Parts.Add(Part); - await LumiaV2UnlockBootViewModel.LumiaV2CustomFlash(PhoneNotifier, null, false, false, Parts, DoResetFirst: true, ClearFlashingStatusAtEnd: false, ShowProgress: false, - SetWorkingStatus: (m, s, v, a, st) => + await LumiaV2UnlockBootViewModel.LumiaV2CustomFlash(PhoneNotifier, null, false, false, Parts, DoResetFirst: true, ClearFlashingStatusAtEnd: false, ShowProgress: false, + SetWorkingStatus: (m, s, v, a, st) => { if (SetWorkingStatus != null) { @@ -697,7 +698,7 @@ namespace WPinternals LastStatus = st; } }, - UpdateWorkingStatus: (m, s, v, st) => + UpdateWorkingStatus: (m, s, v, st) => { if (UpdateWorkingStatus != null) { @@ -775,14 +776,14 @@ namespace WPinternals AsyncAutoResetEvent Event = new AsyncAutoResetEvent(false); SwitchModeViewModel Switch = new SwitchModeViewModel( - Notifier, + Notifier, TargetMode, - ModeSwitchProgress, - (string ErrorMessage) => + ModeSwitchProgress, + (string ErrorMessage) => { LocalErrorMessage = ErrorMessage; Event.Set(); - }, + }, (IDisposable NewModel, PhoneInterfaces NewInterface) => { Result = NewModel; diff --git a/WPinternalsConfig.cs b/WPinternalsConfig.cs index 5c80b32..aeca917 100644 --- a/WPinternalsConfig.cs +++ b/WPinternalsConfig.cs @@ -22,9 +22,8 @@ using System; using System.Collections.Generic; using System.IO; using System.Linq; -using System.Xml.Serialization; using System.Security.Cryptography; -using System.Windows; +using System.Xml.Serialization; namespace WPinternals { @@ -184,7 +183,7 @@ namespace WPinternals internal void RemoveFfuFromRepository(string FFUPath) { int Count = 0; - FFURepository.Where(e => (string.Compare(e.Path, FFUPath, true) == 0)).ToList().ForEach(e => + FFURepository.Where(e => (string.Compare(e.Path, FFUPath, true) == 0)).ToList().ForEach(e => { Count++; FFURepository.Remove(e); @@ -215,7 +214,7 @@ namespace WPinternals { LogFile.Log("Adding emergency files to repository: " + ProgrammerPath, LogType.FileAndConsole); LogFile.Log("Type: " + Type, LogType.FileAndConsole); - + Entry = new EmergencyFileEntry(); Entry.Type = Type; Entry.ProgrammerPath = ProgrammerPath; diff --git a/WinUSBNet/API/APIException.cs b/WinUSBNet/API/APIException.cs index 68615b0..300589f 100644 --- a/WinUSBNet/API/APIException.cs +++ b/WinUSBNet/API/APIException.cs @@ -6,11 +6,8 @@ */ using System; -using System.Collections.Generic; -using System.Text; -using System.Runtime; -using System.Runtime.InteropServices; using System.ComponentModel; +using System.Runtime.InteropServices; namespace MadWizard.WinUSBNet.API @@ -24,7 +21,7 @@ namespace MadWizard.WinUSBNet.API public APIException(string message) : base(message) { - + } public APIException(string message, Exception innerException) : base(message, innerException) { @@ -40,11 +37,11 @@ namespace MadWizard.WinUSBNet.API // ErrorCode = ErrorCode; // Break here // return APIException.Win32(message, ErrorCode); } - - public static APIException Win32(string message, int errorCode) + + public static APIException Win32(string message, int errorCode) { return new APIException(message, new Win32Exception(errorCode)); - + } } diff --git a/WinUSBNet/API/DeviceDetails.cs b/WinUSBNet/API/DeviceDetails.cs index e00852b..64988e0 100644 --- a/WinUSBNet/API/DeviceDetails.cs +++ b/WinUSBNet/API/DeviceDetails.cs @@ -5,11 +5,6 @@ * http://www.opensource.org/licenses/mit-license.php */ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; - namespace MadWizard.WinUSBNet.API { internal struct DeviceDetails diff --git a/WinUSBNet/API/DeviceManagement.cs b/WinUSBNet/API/DeviceManagement.cs index b9b163d..9e9ec0b 100644 --- a/WinUSBNet/API/DeviceManagement.cs +++ b/WinUSBNet/API/DeviceManagement.cs @@ -10,51 +10,51 @@ */ using System; -using System.Runtime.InteropServices; using System.Collections.Generic; +using System.Runtime.InteropServices; using System.Text.RegularExpressions; namespace MadWizard.WinUSBNet.API { - /// - /// Routines for detecting devices and receiving device notifications. - /// - internal static partial class DeviceManagement - { + /// + /// Routines for detecting devices and receiving device notifications. + /// + internal static partial class DeviceManagement + { // Get device name from notification message. // Also checks checkGuid with the GUID from the message to check the notification // is for a relevant device. Other messages might be received. public static string GetNotifyMessageDeviceName(IntPtr pDevBroadcastHeader, Guid checkGuid) - { - int stringSize; + { + int stringSize; - DEV_BROADCAST_DEVICEINTERFACE_1 devBroadcastDeviceInterface = new DEV_BROADCAST_DEVICEINTERFACE_1(); - DEV_BROADCAST_HDR devBroadcastHeader = new DEV_BROADCAST_HDR(); + DEV_BROADCAST_DEVICEINTERFACE_1 devBroadcastDeviceInterface = new DEV_BROADCAST_DEVICEINTERFACE_1(); + DEV_BROADCAST_HDR devBroadcastHeader = new DEV_BROADCAST_HDR(); - // The LParam parameter of Message is a pointer to a DEV_BROADCAST_HDR structure. + // The LParam parameter of Message is a pointer to a DEV_BROADCAST_HDR structure. Marshal.PtrToStructure(pDevBroadcastHeader, devBroadcastHeader); - if ((devBroadcastHeader.dbch_devicetype == DBT_DEVTYP_DEVICEINTERFACE)) - { - // The dbch_devicetype parameter indicates that the event applies to a device interface. - // So the structure in LParam is actually a DEV_BROADCAST_INTERFACE structure, - // which begins with a DEV_BROADCAST_HDR. + if ((devBroadcastHeader.dbch_devicetype == DBT_DEVTYP_DEVICEINTERFACE)) + { + // The dbch_devicetype parameter indicates that the event applies to a device interface. + // So the structure in LParam is actually a DEV_BROADCAST_INTERFACE structure, + // which begins with a DEV_BROADCAST_HDR. - // Obtain the number of characters in dbch_name by subtracting the 32 bytes - // in the strucutre that are not part of dbch_name and dividing by 2 because there are - // 2 bytes per character. + // Obtain the number of characters in dbch_name by subtracting the 32 bytes + // in the strucutre that are not part of dbch_name and dividing by 2 because there are + // 2 bytes per character. stringSize = System.Convert.ToInt32((devBroadcastHeader.dbch_size - 32) / 2); - // The dbcc_name parameter of devBroadcastDeviceInterface contains the device name. - // Trim dbcc_name to match the size of the String. + // The dbcc_name parameter of devBroadcastDeviceInterface contains the device name. + // Trim dbcc_name to match the size of the String. - devBroadcastDeviceInterface.dbcc_name = new char[stringSize + 1]; + devBroadcastDeviceInterface.dbcc_name = new char[stringSize + 1]; - // Marshal data from the unmanaged block pointed to by m.LParam - // to the managed object devBroadcastDeviceInterface. + // Marshal data from the unmanaged block pointed to by m.LParam + // to the managed object devBroadcastDeviceInterface. Marshal.PtrToStructure(pDevBroadcastHeader, devBroadcastDeviceInterface); @@ -66,7 +66,7 @@ namespace MadWizard.WinUSBNet.API string deviceNameString = new String(devBroadcastDeviceInterface.dbcc_name, 0, stringSize); return deviceNameString; - } + } else if ((devBroadcastHeader.dbch_devicetype == DBT_DEVTYP_VOLUME)) { DEV_BROADCAST_VOLUME vol = new DEV_BROADCAST_VOLUME(); @@ -80,10 +80,10 @@ namespace MadWizard.WinUSBNet.API } while (Mask > 0); return @"\\.\" + Convert.ToChar(DriveInt) + ":"; - } + } return null; - } - + } + private static byte[] GetProperty(IntPtr deviceInfoSet, SP_DEVINFO_DATA deviceInfoData, SPDRP property, out int regType) { uint requiredSize; @@ -172,7 +172,7 @@ namespace MadWizard.WinUSBNet.API details.DevicePath = devicePath; details.DeviceDescription = GetStringProperty(deviceInfoSet, deviceInfoData, SPDRP.SPDRP_DEVICEDESC); details.Manufacturer = GetStringProperty(deviceInfoSet, deviceInfoData, SPDRP.SPDRP_MFG); - + // Heathcliff74 details.BusName = ""; try @@ -180,7 +180,7 @@ namespace MadWizard.WinUSBNet.API details.BusName = GetStringProperty(deviceInfoSet, deviceInfoData, new DEVPROPKEY(new Guid(0x540b947e, 0x8b40, 0x45bc, 0xa8, 0xa2, 0x6a, 0x0b, 0x89, 0x4c, 0xbd, 0xa2), 4)); } catch { } - + string[] hardwareIDs = GetMultiStringProperty(deviceInfoSet, deviceInfoData, SPDRP.SPDRP_HARDWAREID); Regex regex = new Regex("^USB\\\\VID_([0-9A-F]{4})&PID_([0-9A-F]{4})", RegexOptions.IgnoreCase); @@ -203,65 +203,65 @@ namespace MadWizard.WinUSBNet.API return details; } - - public static DeviceDetails[] FindDevicesFromGuid(Guid guid) - { + + public static DeviceDetails[] FindDevicesFromGuid(Guid guid) + { IntPtr deviceInfoSet = IntPtr.Zero; List deviceList = new List(); - try - { - deviceInfoSet = SetupDiGetClassDevs(ref guid, IntPtr.Zero, IntPtr.Zero, + try + { + deviceInfoSet = SetupDiGetClassDevs(ref guid, IntPtr.Zero, IntPtr.Zero, DIGCF_PRESENT | DIGCF_DEVICEINTERFACE); if (deviceInfoSet == FileIO.INVALID_HANDLE_VALUE) throw APIException.Win32("Failed to enumerate devices."); int memberIndex = 0; - while(true) - { - // Begin with 0 and increment through the device information set until - // no more devices are available. + while (true) + { + // Begin with 0 and increment through the device information set until + // no more devices are available. SP_DEVICE_INTERFACE_DATA deviceInterfaceData = new SP_DEVICE_INTERFACE_DATA(); - // The cbSize element of the deviceInterfaceData structure must be set to - // the structure's size in bytes. - // The size is 28 bytes for 32-bit code and 32 bytes for 64-bit code. - deviceInterfaceData.cbSize = Marshal.SizeOf(deviceInterfaceData); - + // The cbSize element of the deviceInterfaceData structure must be set to + // the structure's size in bytes. + // The size is 28 bytes for 32-bit code and 32 bytes for 64-bit code. + deviceInterfaceData.cbSize = Marshal.SizeOf(deviceInterfaceData); + bool success; - success = SetupDiEnumDeviceInterfaces(deviceInfoSet, IntPtr.Zero, ref guid, memberIndex, ref deviceInterfaceData); + success = SetupDiEnumDeviceInterfaces(deviceInfoSet, IntPtr.Zero, ref guid, memberIndex, ref deviceInterfaceData); - // Find out if a device information set was retrieved. - if (!success) - { + // Find out if a device information set was retrieved. + if (!success) + { int lastError = Marshal.GetLastWin32Error(); if (lastError == ERROR_NO_MORE_ITEMS) break; throw APIException.Win32("Failed to get device interface."); - } - // A device is present. + } + // A device is present. int bufferSize = 0; - success = SetupDiGetDeviceInterfaceDetail - (deviceInfoSet, - ref deviceInterfaceData, - IntPtr.Zero, - 0, - ref bufferSize, - IntPtr.Zero); + success = SetupDiGetDeviceInterfaceDetail + (deviceInfoSet, + ref deviceInterfaceData, + IntPtr.Zero, + 0, + ref bufferSize, + IntPtr.Zero); if (!success) { if (Marshal.GetLastWin32Error() != ERROR_INSUFFICIENT_BUFFER) throw APIException.Win32("Failed to get interface details buffer size."); } - + IntPtr detailDataBuffer = IntPtr.Zero; try { - + // Allocate memory for the SP_DEVICE_INTERFACE_DETAIL_DATA structure using the returned buffer size. detailDataBuffer = Marshal.AllocHGlobal(bufferSize); @@ -288,10 +288,10 @@ namespace MadWizard.WinUSBNet.API if (!success) throw APIException.Win32("Failed to get device interface details."); - - + + // Skip over cbsize (4 bytes) to get the address of the devicePathName. - + IntPtr pDevicePathName = new IntPtr(detailDataBuffer.ToInt64() + 4); string pathName = Marshal.PtrToStringUni(pDevicePathName); @@ -299,7 +299,7 @@ namespace MadWizard.WinUSBNet.API DeviceDetails details = GetDeviceDetails(pathName, deviceInfoSet, da); - + deviceList.Add(details); } finally @@ -311,58 +311,58 @@ namespace MadWizard.WinUSBNet.API } } memberIndex++; - } - } - finally - { + } + } + finally + { if (deviceInfoSet != IntPtr.Zero && deviceInfoSet != FileIO.INVALID_HANDLE_VALUE) - { - SetupDiDestroyDeviceInfoList(deviceInfoSet); - } - } + { + SetupDiDestroyDeviceInfoList(deviceInfoSet); + } + } return deviceList.ToArray(); - } + } - public static void RegisterForDeviceNotifications(IntPtr controlHandle, Guid classGuid, ref IntPtr deviceNotificationHandle) - { + public static void RegisterForDeviceNotifications(IntPtr controlHandle, Guid classGuid, ref IntPtr deviceNotificationHandle) + { - DEV_BROADCAST_DEVICEINTERFACE devBroadcastDeviceInterface = new DEV_BROADCAST_DEVICEINTERFACE(); - IntPtr devBroadcastDeviceInterfaceBuffer = IntPtr.Zero; - try - { - int size = Marshal.SizeOf(devBroadcastDeviceInterface); - devBroadcastDeviceInterface.dbcc_size = size; + DEV_BROADCAST_DEVICEINTERFACE devBroadcastDeviceInterface = new DEV_BROADCAST_DEVICEINTERFACE(); + IntPtr devBroadcastDeviceInterfaceBuffer = IntPtr.Zero; + try + { + int size = Marshal.SizeOf(devBroadcastDeviceInterface); + devBroadcastDeviceInterface.dbcc_size = size; devBroadcastDeviceInterface.dbcc_devicetype = DBT_DEVTYP_DEVICEINTERFACE; - devBroadcastDeviceInterface.dbcc_reserved = 0; - devBroadcastDeviceInterface.dbcc_classguid = classGuid; - devBroadcastDeviceInterfaceBuffer = Marshal.AllocHGlobal(size); + devBroadcastDeviceInterface.dbcc_reserved = 0; + devBroadcastDeviceInterface.dbcc_classguid = classGuid; + devBroadcastDeviceInterfaceBuffer = Marshal.AllocHGlobal(size); - // Copy the DEV_BROADCAST_DEVICEINTERFACE structure to the buffer. - // Set fDeleteOld True to prevent memory leaks. - Marshal.StructureToPtr(devBroadcastDeviceInterface, devBroadcastDeviceInterfaceBuffer, true); + // Copy the DEV_BROADCAST_DEVICEINTERFACE structure to the buffer. + // Set fDeleteOld True to prevent memory leaks. + Marshal.StructureToPtr(devBroadcastDeviceInterface, devBroadcastDeviceInterfaceBuffer, true); - deviceNotificationHandle = RegisterDeviceNotification(controlHandle, devBroadcastDeviceInterfaceBuffer, DEVICE_NOTIFY_WINDOW_HANDLE); + deviceNotificationHandle = RegisterDeviceNotification(controlHandle, devBroadcastDeviceInterfaceBuffer, DEVICE_NOTIFY_WINDOW_HANDLE); if (deviceNotificationHandle == IntPtr.Zero) throw APIException.Win32("Failed to register device notification"); - + // Marshal data from the unmanaged block devBroadcastDeviceInterfaceBuffer to - // the managed object devBroadcastDeviceInterface + // the managed object devBroadcastDeviceInterface Marshal.PtrToStructure(devBroadcastDeviceInterfaceBuffer, devBroadcastDeviceInterface); - } - finally - { + } + finally + { // Free the memory allocated previously by AllocHGlobal. - if (devBroadcastDeviceInterfaceBuffer != IntPtr.Zero) + if (devBroadcastDeviceInterfaceBuffer != IntPtr.Zero) Marshal.FreeHGlobal(devBroadcastDeviceInterfaceBuffer); - } - } + } + } public static void StopDeviceDeviceNotifications(IntPtr deviceNotificationHandle) - { + { if (!DeviceManagement.UnregisterDeviceNotification(deviceNotificationHandle)) throw APIException.Win32("Failed to unregister device notification"); - } - } + } + } } diff --git a/WinUSBNet/API/DeviceManagementAPI.cs b/WinUSBNet/API/DeviceManagementAPI.cs index 66e5ed7..be9791d 100644 --- a/WinUSBNet/API/DeviceManagementAPI.cs +++ b/WinUSBNet/API/DeviceManagementAPI.cs @@ -14,14 +14,14 @@ using System.Runtime.InteropServices; namespace MadWizard.WinUSBNet.API { - /// - /// API declarations relating to device management (SetupDixxx and - /// RegisterDeviceNotification functions). - /// + /// + /// API declarations relating to device management (SetupDixxx and + /// RegisterDeviceNotification functions). + /// - internal static partial class DeviceManagement - { - // from dbt.h + internal static partial class DeviceManagement + { + // from dbt.h internal const Int32 DBT_DEVICEARRIVAL = 0X8000; internal const Int32 DBT_DEVICEREMOVECOMPLETE = 0X8004; @@ -40,31 +40,31 @@ namespace MadWizard.WinUSBNet.API private const Int32 DIGCF_PRESENT = 2; private const Int32 DIGCF_DEVICEINTERFACE = 0X10; - // Two declarations for the DEV_BROADCAST_DEVICEINTERFACE structure. + // Two declarations for the DEV_BROADCAST_DEVICEINTERFACE structure. - // Use this one in the call to RegisterDeviceNotification() and - // in checking dbch_devicetype in a DEV_BROADCAST_HDR structure: + // Use this one in the call to RegisterDeviceNotification() and + // in checking dbch_devicetype in a DEV_BROADCAST_HDR structure: - [StructLayout(LayoutKind.Sequential)] + [StructLayout(LayoutKind.Sequential)] private class DEV_BROADCAST_DEVICEINTERFACE - { - internal Int32 dbcc_size; - internal Int32 dbcc_devicetype; - internal Int32 dbcc_reserved; - internal Guid dbcc_classguid; - internal Int16 dbcc_name; - } + { + internal Int32 dbcc_size; + internal Int32 dbcc_devicetype; + internal Int32 dbcc_reserved; + internal Guid dbcc_classguid; + internal Int16 dbcc_name; + } - [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] private class DEV_BROADCAST_DEVICEINTERFACE_1 - { - internal Int32 dbcc_size; - internal Int32 dbcc_devicetype; - internal Int32 dbcc_reserved; - internal Guid dbcc_classguid; - [MarshalAs(UnmanagedType.ByValArray, SizeConst = 255)] - internal Char[] dbcc_name; - } + { + internal Int32 dbcc_size; + internal Int32 dbcc_devicetype; + internal Int32 dbcc_reserved; + internal Guid dbcc_classguid; + [MarshalAs(UnmanagedType.ByValArray, SizeConst = 255)] + internal Char[] dbcc_name; + } [StructLayout(LayoutKind.Sequential)] public class DEV_BROADCAST_VOLUME @@ -75,21 +75,21 @@ namespace MadWizard.WinUSBNet.API public Int32 dbcv_unitmask; } - [StructLayout(LayoutKind.Sequential)] + [StructLayout(LayoutKind.Sequential)] private class DEV_BROADCAST_HDR - { - internal Int32 dbch_size; - internal Int32 dbch_devicetype; - internal Int32 dbch_reserved; - } + { + internal Int32 dbch_size; + internal Int32 dbch_devicetype; + internal Int32 dbch_reserved; + } private struct SP_DEVICE_INTERFACE_DATA - { - internal Int32 cbSize; - internal System.Guid InterfaceClassGuid; - internal Int32 Flags; - internal IntPtr Reserved; - } + { + internal Int32 cbSize; + internal System.Guid InterfaceClassGuid; + internal Int32 Flags; + internal IntPtr Reserved; + } private struct SP_DEVINFO_DATA { internal Int32 cbSize; @@ -145,14 +145,14 @@ namespace MadWizard.WinUSBNet.API [DllImport("user32.dll", CharSet = CharSet.Unicode, SetLastError = true)] private static extern IntPtr RegisterDeviceNotification(IntPtr hRecipient, IntPtr NotificationFilter, Int32 Flags); - //[DllImport("setupapi.dll", SetLastError = true)] - //internal static extern Int32 SetupDiCreateDeviceInfoList(ref System.Guid ClassGuid, Int32 hwndParent); + //[DllImport("setupapi.dll", SetLastError = true)] + //internal static extern Int32 SetupDiCreateDeviceInfoList(ref System.Guid ClassGuid, Int32 hwndParent); - [DllImport("setupapi.dll", SetLastError = true)] - private static extern Int32 SetupDiDestroyDeviceInfoList(IntPtr DeviceInfoSet); + [DllImport("setupapi.dll", SetLastError = true)] + private static extern Int32 SetupDiDestroyDeviceInfoList(IntPtr DeviceInfoSet); - [DllImport("setupapi.dll", SetLastError = true)] - private static extern bool SetupDiEnumDeviceInterfaces(IntPtr DeviceInfoSet, IntPtr DeviceInfoData, ref System.Guid InterfaceClassGuid, Int32 MemberIndex, ref SP_DEVICE_INTERFACE_DATA DeviceInterfaceData); + [DllImport("setupapi.dll", SetLastError = true)] + private static extern bool SetupDiEnumDeviceInterfaces(IntPtr DeviceInfoSet, IntPtr DeviceInfoData, ref System.Guid InterfaceClassGuid, Int32 MemberIndex, ref SP_DEVICE_INTERFACE_DATA DeviceInterfaceData); [DllImport("setupapi.dll", CharSet = CharSet.Unicode, SetLastError = true)] private static extern bool SetupDiGetDeviceRegistryProperty(IntPtr DeviceInfoSet, ref SP_DEVINFO_DATA DeviceInfoData, SPDRP Property, out int PropertyRegDataType, byte[] PropertyBuffer, uint PropertyBufferSize, out UInt32 RequiredSize); @@ -163,19 +163,19 @@ namespace MadWizard.WinUSBNet.API [DllImport("setupapi.dll", CharSet = CharSet.Unicode, SetLastError = true)] static extern unsafe bool SetupDiGetDeviceProperty(IntPtr deviceInfoSet, ref SP_DEVINFO_DATA DeviceInfoData, ref DEVPROPKEY propertyKey, out UInt32 propertyType, byte[] propertyBuffer, Int32 propertyBufferSize, out int requiredSize, UInt32 flags); - [DllImport("setupapi.dll", SetLastError = true, CharSet = CharSet.Unicode)] + [DllImport("setupapi.dll", SetLastError = true, CharSet = CharSet.Unicode)] private static extern IntPtr SetupDiGetClassDevs(ref System.Guid ClassGuid, IntPtr Enumerator, IntPtr hwndParent, Int32 Flags); - [DllImport("setupapi.dll", SetLastError = true, CharSet = CharSet.Unicode)] + [DllImport("setupapi.dll", SetLastError = true, CharSet = CharSet.Unicode)] private static extern bool SetupDiGetDeviceInterfaceDetail(IntPtr DeviceInfoSet, ref SP_DEVICE_INTERFACE_DATA DeviceInterfaceData, IntPtr DeviceInterfaceDetailData, Int32 DeviceInterfaceDetailDataSize, ref Int32 RequiredSize, ref SP_DEVINFO_DATA DeviceInfoData); [DllImport("setupapi.dll", SetLastError = true, CharSet = CharSet.Unicode)] private static extern bool SetupDiGetDeviceInterfaceDetail(IntPtr DeviceInfoSet, ref SP_DEVICE_INTERFACE_DATA DeviceInterfaceData, IntPtr DeviceInterfaceDetailData, Int32 DeviceInterfaceDetailDataSize, ref Int32 RequiredSize, IntPtr DeviceInfoData); - [DllImport("user32.dll", SetLastError = true)] - private static extern bool UnregisterDeviceNotification(IntPtr Handle); + [DllImport("user32.dll", SetLastError = true)] + private static extern bool UnregisterDeviceNotification(IntPtr Handle); private const int ERROR_NO_MORE_ITEMS = 259; private const int ERROR_INSUFFICIENT_BUFFER = 122; - } + } } diff --git a/WinUSBNet/API/FileAPI.cs b/WinUSBNet/API/FileAPI.cs index 9192727..296b5b2 100644 --- a/WinUSBNet/API/FileAPI.cs +++ b/WinUSBNet/API/FileAPI.cs @@ -9,19 +9,19 @@ * See http://www.lvr.com/winusb.htm for more information */ -using System; using Microsoft.Win32.SafeHandles; +using System; using System.Runtime.InteropServices; namespace MadWizard.WinUSBNet.API { - /// - /// API declarations relating to file I/O (and used by WinUsb). - /// + /// + /// API declarations relating to file I/O (and used by WinUsb). + /// - sealed internal class FileIO - { - public const Int32 FILE_ATTRIBUTE_NORMAL = 0X80; + sealed internal class FileIO + { + public const Int32 FILE_ATTRIBUTE_NORMAL = 0X80; public const Int32 FILE_FLAG_OVERLAPPED = 0X40000000; public const Int32 FILE_SHARE_READ = 1; public const Int32 FILE_SHARE_WRITE = 2; @@ -32,8 +32,8 @@ namespace MadWizard.WinUSBNet.API public const Int32 ERROR_IO_PENDING = 997; - [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)] + [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)] public static extern SafeFileHandle CreateFile(String lpFileName, UInt32 dwDesiredAccess, Int32 dwShareMode, IntPtr lpSecurityAttributes, Int32 dwCreationDisposition, Int32 dwFlagsAndAttributes, Int32 hTemplateFile); - } + } } diff --git a/WinUSBNet/API/WinUSBDevice.cs b/WinUSBNet/API/WinUSBDevice.cs index d8ace3f..899dc8c 100644 --- a/WinUSBNet/API/WinUSBDevice.cs +++ b/WinUSBNet/API/WinUSBDevice.cs @@ -9,22 +9,21 @@ * See http://www.lvr.com/winusb.htm for more information */ -using System; using Microsoft.Win32.SafeHandles; -using System.Runtime.InteropServices; +using System; using System.Collections.Generic; +using System.Runtime.InteropServices; using System.Threading; -using System.ComponentModel; namespace MadWizard.WinUSBNet.API { - /// - /// Wrapper for a WinUSB device dealing with the WinUSB and additional interface handles - /// - partial class WinUSBDevice : IDisposable - { + /// + /// Wrapper for a WinUSB device dealing with the WinUSB and additional interface handles + /// + partial class WinUSBDevice : IDisposable + { private bool _disposed = false; - private SafeFileHandle _deviceHandle; + private SafeFileHandle _deviceHandle; private IntPtr _winUsbHandle = IntPtr.Zero; private IntPtr[] _addInterfaces = null; public WinUSBDevice() @@ -57,13 +56,13 @@ namespace MadWizard.WinUSBNet.API if (disposing) { - // Dispose managed resources + // Dispose managed resources if (_deviceHandle != null && !_deviceHandle.IsInvalid) _deviceHandle.Dispose(); _deviceHandle = null; } - // Dispose unmanaged resources + // Dispose unmanaged resources FreeWinUSB(); _disposed = true; } @@ -105,8 +104,8 @@ namespace MadWizard.WinUSBNet.API bool success = WinUsb_GetDescriptor(_winUsbHandle, USB_STRING_DESCRIPTOR_TYPE, index, 0, buffer, (uint)buffer.Length, out transfered); if (!success) - throw APIException.Win32("Failed to get USB string descriptor (" + index + "): 0x" + Marshal.GetLastWin32Error().ToString("X8")); - + throw APIException.Win32("Failed to get USB string descriptor (" + index + "): 0x" + Marshal.GetLastWin32Error().ToString("X8")); + int length = buffer[0] - 2; if (length <= 0) return null; @@ -115,10 +114,10 @@ namespace MadWizard.WinUSBNet.API } public void ControlTransfer(byte requestType, byte request, ushort value, ushort index, ushort length, byte[] data) - { - uint bytesReturned = 0; - WINUSB_SETUP_PACKET setupPacket; - + { + uint bytesReturned = 0; + WINUSB_SETUP_PACKET setupPacket; + setupPacket.RequestType = requestType; setupPacket.Request = request; setupPacket.Value = value; @@ -128,26 +127,26 @@ namespace MadWizard.WinUSBNet.API bool success = WinUsb_ControlTransfer(_winUsbHandle, setupPacket, data, length, ref bytesReturned, IntPtr.Zero); if (!success) // todo check bytes returned? throw APIException.Win32("Control transfer on WinUSB device failed."); - } + } - - public void OpenDevice(string devicePathName) - { + + public void OpenDevice(string devicePathName) + { try { - _deviceHandle = FileIO.CreateFile(devicePathName, - (FileIO.GENERIC_WRITE | FileIO.GENERIC_READ), - FileIO.FILE_SHARE_READ | FileIO.FILE_SHARE_WRITE, - IntPtr.Zero, - FileIO.OPEN_EXISTING, - FileIO.FILE_ATTRIBUTE_NORMAL | FileIO.FILE_FLAG_OVERLAPPED, - 0); + _deviceHandle = FileIO.CreateFile(devicePathName, + (FileIO.GENERIC_WRITE | FileIO.GENERIC_READ), + FileIO.FILE_SHARE_READ | FileIO.FILE_SHARE_WRITE, + IntPtr.Zero, + FileIO.OPEN_EXISTING, + FileIO.FILE_ATTRIBUTE_NORMAL | FileIO.FILE_FLAG_OVERLAPPED, + 0); if (_deviceHandle.IsInvalid) throw APIException.Win32("Failed to open WinUSB device handle."); InitializeDevice(); } - catch(Exception) + catch (Exception) { if (_deviceHandle != null) { @@ -157,7 +156,7 @@ namespace MadWizard.WinUSBNet.API FreeWinUSB(); throw; } - } + } private IntPtr InterfaceHandle(int index) { @@ -194,11 +193,11 @@ namespace MadWizard.WinUSBNet.API pipes = pipeList.ToArray(); } - private void InitializeDevice() - { - bool success; + private void InitializeDevice() + { + bool success; - success = WinUsb_Initialize(_deviceHandle, ref _winUsbHandle); + success = WinUsb_Initialize(_deviceHandle, ref _winUsbHandle); if (!success) throw APIException.Win32("Failed to initialize WinUSB handle. Device might not be connected."); @@ -237,10 +236,10 @@ namespace MadWizard.WinUSBNet.API // Bind handle (needed for overlapped I/O thread pool) ThreadPool.BindHandle(_deviceHandle); // TODO: bind interface handles as well? doesn't seem to be necessary - } + } - public void ReadPipe(int ifaceIndex, byte pipeID, byte[] buffer, int offset, int bytesToRead, out uint bytesRead) - { + public void ReadPipe(int ifaceIndex, byte pipeID, byte[] buffer, int offset, int bytesToRead, out uint bytesRead) + { bool success; unsafe { @@ -254,7 +253,7 @@ namespace MadWizard.WinUSBNet.API } if (!success) throw APIException.Win32("Failed to read pipe on WinUSB device."); - } + } private unsafe void HandleOverlappedAPI(bool success, string errorMessage, NativeOverlapped* pOverlapped, USBAsyncResult result, int bytesTransfered) { @@ -276,13 +275,13 @@ namespace MadWizard.WinUSBNet.API result.OnCompletion(true, null, bytesTransfered, false); // is the callback still called in this case?? todo } - + } public void ReadPipeOverlapped(int ifaceIndex, byte pipeID, byte[] buffer, int offset, int bytesToRead, USBAsyncResult result) { Overlapped overlapped = new Overlapped(); - + overlapped.AsyncResult = result; unsafe @@ -313,7 +312,7 @@ namespace MadWizard.WinUSBNet.API uint bytesWritten; pOverlapped = overlapped.Pack(PipeIOCallback, buffer); - + bool success; // Buffer is pinned already by overlapped.Pack fixed (byte* pBuffer = buffer) @@ -326,13 +325,13 @@ namespace MadWizard.WinUSBNet.API } } - + public void ControlTransferOverlapped(byte requestType, byte request, ushort value, ushort index, ushort length, byte[] data, USBAsyncResult result) - { - uint bytesReturned = 0; - WINUSB_SETUP_PACKET setupPacket; - + { + uint bytesReturned = 0; + WINUSB_SETUP_PACKET setupPacket; + setupPacket.RequestType = requestType; setupPacket.Request = request; setupPacket.Value = value; @@ -349,7 +348,7 @@ namespace MadWizard.WinUSBNet.API bool success = WinUsb_ControlTransfer(_winUsbHandle, setupPacket, data, length, ref bytesReturned, pOverlapped); HandleOverlappedAPI(success, "Asynchronous control transfer on WinUSB device failed.", pOverlapped, result, (int)bytesReturned); } - } + } private unsafe void PipeIOCallback(uint errorCode, uint numBytes, NativeOverlapped* pOverlapped) { @@ -393,7 +392,7 @@ namespace MadWizard.WinUSBNet.API } public void WritePipe(int ifaceIndex, byte pipeID, byte[] buffer, int offset, int length) - { + { uint bytesWritten; bool success; unsafe @@ -408,8 +407,8 @@ namespace MadWizard.WinUSBNet.API } if (!success || (bytesWritten != length)) throw APIException.Win32("Failed to write pipe on WinUSB device."); - - } + + } public void FlushPipe(int ifaceIndex, byte pipeID) { @@ -419,29 +418,29 @@ namespace MadWizard.WinUSBNet.API } public void SetPipePolicy(int ifaceIndex, byte pipeID, POLICY_TYPE policyType, bool value) - { + { byte byteVal = (byte)(value ? 1 : 0); bool success = WinUsb_SetPipePolicy(InterfaceHandle(ifaceIndex), pipeID, (uint)policyType, 1, ref byteVal); if (!success) throw APIException.Win32("Failed to set WinUSB pipe policy."); - } + } public void SetPipePolicy(int ifaceIndex, byte pipeID, POLICY_TYPE policyType, uint value) - { - + { + bool success = WinUsb_SetPipePolicy(InterfaceHandle(ifaceIndex), pipeID, (uint)policyType, 4, ref value); if (!success) throw APIException.Win32("Failed to set WinUSB pipe policy."); - } + } public bool GetPipePolicyBool(int ifaceIndex, byte pipeID, POLICY_TYPE policyType) { byte result; uint length = 1; - + bool success = WinUsb_GetPipePolicy(InterfaceHandle(ifaceIndex), pipeID, (uint)policyType, ref length, out result); if (!success || length != 1) throw APIException.Win32("Failed to get WinUSB pipe policy."); @@ -451,7 +450,7 @@ namespace MadWizard.WinUSBNet.API public uint GetPipePolicyUInt(int ifaceIndex, byte pipeID, POLICY_TYPE policyType) { - + uint result; uint length = 4; bool success = WinUsb_GetPipePolicy(InterfaceHandle(ifaceIndex), pipeID, (uint)policyType, ref length, out result); @@ -460,5 +459,5 @@ namespace MadWizard.WinUSBNet.API throw APIException.Win32("Failed to get WinUSB pipe policy."); return result; } - } + } } diff --git a/WinUSBNet/API/WinUSBDeviceAPI.cs b/WinUSBNet/API/WinUSBDeviceAPI.cs index 2624692..4f097dd 100644 --- a/WinUSBNet/API/WinUSBDeviceAPI.cs +++ b/WinUSBNet/API/WinUSBDeviceAPI.cs @@ -9,90 +9,90 @@ * See http://www.lvr.com/winusb.htm for more information */ -using System; using Microsoft.Win32.SafeHandles; +using System; using System.Runtime.InteropServices; using System.Threading; namespace MadWizard.WinUSBNet.API { - [StructLayout(LayoutKind.Sequential)] - struct USB_DEVICE_DESCRIPTOR - { - public byte bLength; - public byte bDescriptorType; - public ushort bcdUSB; - public byte bDeviceClass; - public byte bDeviceSubClass; - public byte bDeviceProtocol; - public byte bMaxPacketSize0; - public ushort idVendor; - public ushort idProduct; - public ushort bcdDevice; - public byte iManufacturer; - public byte iProduct; - public byte iSerialNumber; - public byte bNumConfigurations; - }; + [StructLayout(LayoutKind.Sequential)] + struct USB_DEVICE_DESCRIPTOR + { + public byte bLength; + public byte bDescriptorType; + public ushort bcdUSB; + public byte bDeviceClass; + public byte bDeviceSubClass; + public byte bDeviceProtocol; + public byte bMaxPacketSize0; + public ushort idVendor; + public ushort idProduct; + public ushort bcdDevice; + public byte iManufacturer; + public byte iProduct; + public byte iSerialNumber; + public byte bNumConfigurations; + }; - [StructLayout(LayoutKind.Sequential)] - struct USB_CONFIGURATION_DESCRIPTOR - { - public byte bLength; - public byte bDescriptorType; - public ushort wTotalLength; - public byte bNumInterfaces; - public byte bConfigurationValue; - public byte iConfiguration; - public byte bmAttributes; - public byte MaxPower; - } + [StructLayout(LayoutKind.Sequential)] + struct USB_CONFIGURATION_DESCRIPTOR + { + public byte bLength; + public byte bDescriptorType; + public ushort wTotalLength; + public byte bNumInterfaces; + public byte bConfigurationValue; + public byte iConfiguration; + public byte bmAttributes; + public byte MaxPower; + } - [StructLayout(LayoutKind.Sequential)] - struct USB_INTERFACE_DESCRIPTOR - { - public byte bLength; - public byte bDescriptorType; - public byte bInterfaceNumber; - public byte bAlternateSetting; - public byte bNumEndpoints; - public byte bInterfaceClass; - public byte bInterfaceSubClass; - public byte bInterfaceProtocol; - public byte iInterface; - }; - enum USBD_PIPE_TYPE : int - { - UsbdPipeTypeControl, - UsbdPipeTypeIsochronous, - UsbdPipeTypeBulk, - UsbdPipeTypeInterrupt, - } - [StructLayout(LayoutKind.Sequential)] - struct WINUSB_PIPE_INFORMATION - { - public USBD_PIPE_TYPE PipeType; - public byte PipeId; - public ushort MaximumPacketSize; - public byte Interval; - } + [StructLayout(LayoutKind.Sequential)] + struct USB_INTERFACE_DESCRIPTOR + { + public byte bLength; + public byte bDescriptorType; + public byte bInterfaceNumber; + public byte bAlternateSetting; + public byte bNumEndpoints; + public byte bInterfaceClass; + public byte bInterfaceSubClass; + public byte bInterfaceProtocol; + public byte iInterface; + }; + enum USBD_PIPE_TYPE : int + { + UsbdPipeTypeControl, + UsbdPipeTypeIsochronous, + UsbdPipeTypeBulk, + UsbdPipeTypeInterrupt, + } + [StructLayout(LayoutKind.Sequential)] + struct WINUSB_PIPE_INFORMATION + { + public USBD_PIPE_TYPE PipeType; + public byte PipeId; + public ushort MaximumPacketSize; + public byte Interval; + } - enum POLICY_TYPE : int - { - SHORT_PACKET_TERMINATE = 1, - AUTO_CLEAR_STALL, - PIPE_TRANSFER_TIMEOUT, - IGNORE_SHORT_PACKETS, - ALLOW_PARTIAL_READS, - AUTO_FLUSH, - RAW_IO, - } + enum POLICY_TYPE : int + { + SHORT_PACKET_TERMINATE = 1, + AUTO_CLEAR_STALL, + PIPE_TRANSFER_TIMEOUT, + IGNORE_SHORT_PACKETS, + ALLOW_PARTIAL_READS, + AUTO_FLUSH, + RAW_IO, + } - partial class WinUSBDevice - { - private const UInt32 DEVICE_SPEED = ((UInt32)(1)); - + partial class WinUSBDevice + { + private const UInt32 DEVICE_SPEED = ((UInt32)(1)); + private enum USB_DEVICE_SPEED : int { UsbLowSpeed = 1, @@ -110,75 +110,75 @@ namespace MadWizard.WinUSBNet.API public ushort Length; } - [DllImport("winusb.dll", SetLastError = true)] + [DllImport("winusb.dll", SetLastError = true)] private static extern bool WinUsb_ControlTransfer(IntPtr InterfaceHandle, WINUSB_SETUP_PACKET SetupPacket, Byte[] Buffer, UInt32 BufferLength, ref UInt32 LengthTransferred, IntPtr Overlapped); [DllImport("winusb.dll", SetLastError = true)] private static unsafe extern bool WinUsb_ControlTransfer(IntPtr InterfaceHandle, WINUSB_SETUP_PACKET SetupPacket, Byte[] Buffer, UInt32 BufferLength, ref UInt32 LengthTransferred, NativeOverlapped* pOverlapped); - [DllImport("winusb.dll", SetLastError = true)] + [DllImport("winusb.dll", SetLastError = true)] private static extern bool WinUsb_Free(IntPtr InterfaceHandle); - [DllImport("winusb.dll", SetLastError = true)] + [DllImport("winusb.dll", SetLastError = true)] private static extern bool WinUsb_Initialize(SafeFileHandle DeviceHandle, ref IntPtr InterfaceHandle); - [DllImport("winusb.dll", SetLastError = true)] + [DllImport("winusb.dll", SetLastError = true)] private static extern bool WinUsb_QueryDeviceInformation(IntPtr InterfaceHandle, UInt32 InformationType, ref UInt32 BufferLength, out byte Buffer); - [DllImport("winusb.dll", SetLastError = true)] + [DllImport("winusb.dll", SetLastError = true)] private static extern bool WinUsb_QueryInterfaceSettings(IntPtr InterfaceHandle, Byte AlternateInterfaceNumber, out USB_INTERFACE_DESCRIPTOR UsbAltInterfaceDescriptor); - [DllImport("winusb.dll", SetLastError = true)] + [DllImport("winusb.dll", SetLastError = true)] private static extern bool WinUsb_QueryPipe(IntPtr InterfaceHandle, Byte AlternateInterfaceNumber, Byte PipeIndex, out WINUSB_PIPE_INFORMATION PipeInformation); - [DllImport("winusb.dll", SetLastError = true)] + [DllImport("winusb.dll", SetLastError = true)] private static unsafe extern bool WinUsb_ReadPipe(IntPtr InterfaceHandle, byte PipeID, byte* pBuffer, uint BufferLength, out uint LengthTransferred, IntPtr Overlapped); [DllImport("winusb.dll", SetLastError = true)] private static unsafe extern bool WinUsb_ReadPipe(IntPtr InterfaceHandle, byte PipeID, byte* pBuffer, uint BufferLength, out uint LengthTransferred, NativeOverlapped* pOverlapped); - + [DllImport("winusb.dll", SetLastError = true)] private static extern bool WinUsb_AbortPipe(IntPtr InterfaceHandle, byte PipeID); - // Two declarations for WinUsb_SetPipePolicy. - // Use this one when the returned Value is a Byte (all except PIPE_TRANSFER_TIMEOUT): + // Two declarations for WinUsb_SetPipePolicy. + // Use this one when the returned Value is a Byte (all except PIPE_TRANSFER_TIMEOUT): - [DllImport("winusb.dll", SetLastError = true)] + [DllImport("winusb.dll", SetLastError = true)] private static extern bool WinUsb_SetPipePolicy(IntPtr InterfaceHandle, Byte PipeID, UInt32 PolicyType, UInt32 ValueLength, ref byte Value); [DllImport("winusb.dll", SetLastError = true)] private static extern bool WinUsb_GetPipePolicy(IntPtr InterfaceHandle, Byte PipeID, UInt32 PolicyType, ref UInt32 ValueLength, out byte Value); - // Use this alias when the returned Value is a UInt32 (PIPE_TRANSFER_TIMEOUT only): + // Use this alias when the returned Value is a UInt32 (PIPE_TRANSFER_TIMEOUT only): - [DllImport("winusb.dll", SetLastError = true)] + [DllImport("winusb.dll", SetLastError = true)] private static extern bool WinUsb_SetPipePolicy(IntPtr InterfaceHandle, Byte PipeID, UInt32 PolicyType, UInt32 ValueLength, ref UInt32 Value); [DllImport("winusb.dll", SetLastError = true)] private static extern bool WinUsb_GetPipePolicy(IntPtr InterfaceHandle, Byte PipeID, UInt32 PolicyType, ref UInt32 ValueLength, out UInt32 Value); - [DllImport("winusb.dll", SetLastError = true)] + [DllImport("winusb.dll", SetLastError = true)] private static unsafe extern bool WinUsb_WritePipe(IntPtr InterfaceHandle, byte PipeID, byte* pBuffer, uint BufferLength, out uint LengthTransferred, IntPtr Overlapped); - + [DllImport("winusb.dll", SetLastError = true)] private static unsafe extern bool WinUsb_WritePipe(IntPtr InterfaceHandle, byte PipeID, byte* pBuffer, uint BufferLength, out uint LengthTransferred, NativeOverlapped* pOverlapped); [DllImport("kernel32.dll", SetLastError = true)] private static unsafe extern bool CancelIo(IntPtr hFile); - + [DllImport("kernel32.dll", SetLastError = true)] private static unsafe extern bool CancelIoEx(IntPtr hFile, NativeOverlapped* pOverlapped); - + [DllImport("winusb.dll", SetLastError = true)] private static unsafe extern bool WinUsb_ResetPipe(IntPtr InterfaceHandle, byte PipeID); - + [DllImport("winusb.dll", SetLastError = true)] private static extern bool WinUsb_FlushPipe(IntPtr InterfaceHandle, byte PipeID); - + [DllImport("winusb.dll", SetLastError = true)] private static extern bool WinUsb_GetDescriptor(IntPtr InterfaceHandle, byte DescriptorType, byte Index, UInt16 LanguageID, byte[] Buffer, UInt32 BufferLength, out UInt32 LengthTransfered); @@ -194,12 +194,12 @@ namespace MadWizard.WinUSBNet.API [DllImport("winusb.dll", SetLastError = true)] private static extern bool WinUsb_GetAssociatedInterface(IntPtr InterfaceHandle, byte AssociatedInterfaceIndex, out IntPtr AssociatedInterfaceHandle); - + private const int USB_DEVICE_DESCRIPTOR_TYPE = 0x01; private const int USB_CONFIGURATION_DESCRIPTOR_TYPE = 0x02; private const int USB_STRING_DESCRIPTOR_TYPE = 0x03; private const int ERROR_NO_MORE_ITEMS = 259; - } + } } diff --git a/WinUSBNet/DeviceNotifyHook.cs b/WinUSBNet/DeviceNotifyHook.cs index 7a5dfb5..a73dc81 100644 --- a/WinUSBNet/DeviceNotifyHook.cs +++ b/WinUSBNet/DeviceNotifyHook.cs @@ -6,9 +6,6 @@ */ using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; using System.Windows; using System.Windows.Interop; @@ -127,7 +124,7 @@ namespace MadWizard.WinUSBNet if (disposing) { // clean managed resources - + // do not clean the notifier here. the notifier owns and will dispose this object. } if (_notifyHandle != IntPtr.Zero) diff --git a/WinUSBNet/USB.cs b/WinUSBNet/USB.cs index 4be4086..20e9669 100644 --- a/WinUSBNet/USB.cs +++ b/WinUSBNet/USB.cs @@ -5,9 +5,6 @@ * http://www.opensource.org/licenses/mit-license.php */ -using System; - - namespace MadWizard.WinUSBNet { /// diff --git a/WinUSBNet/USBAsyncResult.cs b/WinUSBNet/USBAsyncResult.cs index b1c2bb7..e33b3f3 100644 --- a/WinUSBNet/USBAsyncResult.cs +++ b/WinUSBNet/USBAsyncResult.cs @@ -6,9 +6,6 @@ */ using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; using System.Threading; namespace MadWizard.WinUSBNet { @@ -21,7 +18,7 @@ namespace MadWizard.WinUSBNet private ManualResetEvent _waitEvent; private int _bytesTransfered; private Exception _error; - + public USBAsyncResult(AsyncCallback userCallback, object stateObject) { _stateObject = stateObject; @@ -33,7 +30,7 @@ namespace MadWizard.WinUSBNet public object AsyncState { - get + get { return _stateObject; } @@ -55,7 +52,7 @@ namespace MadWizard.WinUSBNet } public WaitHandle AsyncWaitHandle { - get + get { lock (this) { @@ -68,7 +65,7 @@ namespace MadWizard.WinUSBNet public bool CompletedSynchronously { - get + get { lock (this) { @@ -79,7 +76,7 @@ namespace MadWizard.WinUSBNet public bool IsCompleted { - get + get { lock (this) { @@ -131,6 +128,6 @@ namespace MadWizard.WinUSBNet } } - + } } diff --git a/WinUSBNet/USBDevice.cs b/WinUSBNet/USBDevice.cs index 3d469c6..d4bca20 100644 --- a/WinUSBNet/USBDevice.cs +++ b/WinUSBNet/USBDevice.cs @@ -7,7 +7,6 @@ using System; using System.Collections.Generic; -using System.Text; namespace MadWizard.WinUSBNet { @@ -45,7 +44,7 @@ namespace MadWizard.WinUSBNet get; private set; } - + /// /// Collection of all interfaces available on the USB device /// @@ -167,7 +166,7 @@ namespace MadWizard.WinUSBNet API.WINUSB_PIPE_INFORMATION[] pipesInfo; _wuDevice.GetInterfaceInfo(i, out descriptor, out pipesInfo); USBPipe[] interfacePipes = new USBPipe[pipesInfo.Length]; - for(int k=0;k /// Initiates a control transfer without a data stage over the default control endpoint. The request should have an OUT direction (specified by the highest bit /// of the parameter. The setup packets' length member will be set to zero. @@ -532,7 +531,7 @@ namespace MadWizard.WinUSBNet ControlTransfer(requestType, request, value, index, new byte[0]); } - + /// /// Initiates an asynchronous control transfer without a data stage over the default control endpoint. This method allows both IN and OUT direction transfers, depending @@ -702,7 +701,7 @@ namespace MadWizard.WinUSBNet return BeginControlTransfer(requestType, request, value, index, new byte[0], userCallback, stateObject); } - + private void CheckNotDisposed() { if (_disposed) @@ -756,7 +755,7 @@ namespace MadWizard.WinUSBNet if (detailList.Length == 0) return null; - + return new USBDevice(detailList[0].DevicePath); } @@ -769,8 +768,8 @@ namespace MadWizard.WinUSBNet /// no device with the given GUID could be found null is returned. public static USBDevice GetSingleDevice(string guidString) { - - return USBDevice.GetSingleDevice(new Guid(guidString)); + + return USBDevice.GetSingleDevice(new Guid(guidString)); } private static USBDeviceDescriptor GetDeviceDescriptor(string devicePath) @@ -821,6 +820,6 @@ namespace MadWizard.WinUSBNet throw new USBException("Failed to retrieve device descriptor.", e); } } - + } } diff --git a/WinUSBNet/USBDeviceDescriptor.cs b/WinUSBNet/USBDeviceDescriptor.cs index 3ec4402..31a2f8d 100644 --- a/WinUSBNet/USBDeviceDescriptor.cs +++ b/WinUSBNet/USBDeviceDescriptor.cs @@ -6,8 +6,6 @@ */ using System; -using System.Collections.Generic; -using System.Text; namespace MadWizard.WinUSBNet { @@ -51,9 +49,9 @@ namespace MadWizard.WinUSBNet /// Friendly device name, or path name when no /// further device information is available /// - public string FullName - { - get + public string FullName + { + get { if (Manufacturer != null && Product != null) return Product + " - " + Manufacturer; @@ -127,7 +125,7 @@ namespace MadWizard.WinUSBNet { BaseClass = (USBBaseClass)(int)deviceDesc.bDeviceClass; } - + } diff --git a/WinUSBNet/USBDeviceInfo.cs b/WinUSBNet/USBDeviceInfo.cs index 094d02c..4733461 100644 --- a/WinUSBNet/USBDeviceInfo.cs +++ b/WinUSBNet/USBDeviceInfo.cs @@ -5,11 +5,6 @@ * http://www.opensource.org/licenses/mit-license.php */ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; - namespace MadWizard.WinUSBNet { /// diff --git a/WinUSBNet/USBException.cs b/WinUSBNet/USBException.cs index 18293b5..d22d441 100644 --- a/WinUSBNet/USBException.cs +++ b/WinUSBNet/USBException.cs @@ -6,8 +6,6 @@ */ using System; -using System.Collections.Generic; -using System.Text; namespace MadWizard.WinUSBNet { diff --git a/WinUSBNet/USBInterface.cs b/WinUSBNet/USBInterface.cs index 606c4c6..066038d 100644 --- a/WinUSBNet/USBInterface.cs +++ b/WinUSBNet/USBInterface.cs @@ -6,8 +6,6 @@ */ using System; -using System.Collections.Generic; -using System.Text; namespace MadWizard.WinUSBNet { @@ -33,7 +31,7 @@ namespace MadWizard.WinUSBNet get; private set; } - + /// /// USB device associated with this interface /// @@ -100,7 +98,7 @@ namespace MadWizard.WinUSBNet get; private set; } - + /// Zero based interface index in WinUSB. /// Note that this is not necessarily the same as the interface *number* /// from the interface descriptor. There might be interfaces within the @@ -128,7 +126,7 @@ namespace MadWizard.WinUSBNet { BaseClass = (USBBaseClass)(int)rawDesc.bInterfaceClass; } - + Device = device; Pipes = pipes; @@ -146,7 +144,7 @@ namespace MadWizard.WinUSBNet OutPipe = pipe; } - + } } } diff --git a/WinUSBNet/USBInterfaceCollection.cs b/WinUSBNet/USBInterfaceCollection.cs index d4dae90..9d6533f 100644 --- a/WinUSBNet/USBInterfaceCollection.cs +++ b/WinUSBNet/USBInterfaceCollection.cs @@ -6,7 +6,6 @@ */ using System; -using System.Text; using System.Collections; using System.Collections.Generic; @@ -134,7 +133,7 @@ namespace MadWizard.WinUSBNet /// is not necessarily the same as the interface index. /// Thrown when the given interface number does not exist in the collection. /// - public USBInterface this[ int interfaceNumber ] + public USBInterface this[int interfaceNumber] { get { diff --git a/WinUSBNet/USBNotifier.cs b/WinUSBNet/USBNotifier.cs index b7dbb68..ae33727 100644 --- a/WinUSBNet/USBNotifier.cs +++ b/WinUSBNet/USBNotifier.cs @@ -6,9 +6,6 @@ */ using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; namespace MadWizard.WinUSBNet { @@ -18,7 +15,7 @@ namespace MadWizard.WinUSBNet /// The source of the event /// Details of the event public delegate void USBEventHandler(object sender, USBEvent e); - + /// /// Event type enumeration for WinUSB events /// @@ -59,7 +56,7 @@ namespace MadWizard.WinUSBNet { this.Guid = guid; this.DevicePath = devicePath; - this.Type= type; + this.Type = type; } } @@ -221,7 +218,7 @@ namespace MadWizard.WinUSBNet public void Dispose() { Dispose(true); - GC.SuppressFinalize(this); + GC.SuppressFinalize(this); } /// diff --git a/WinUSBNet/USBPipe.cs b/WinUSBNet/USBPipe.cs index a58dd61..b142e15 100644 --- a/WinUSBNet/USBPipe.cs +++ b/WinUSBNet/USBPipe.cs @@ -6,8 +6,6 @@ */ using System; -using System.Collections.Generic; -using System.Text; namespace MadWizard.WinUSBNet { @@ -27,14 +25,14 @@ namespace MadWizard.WinUSBNet /// /// Endpoint address including the direction in the most significant bit /// - public byte Address + public byte Address { get { return _pipeInfo.PipeId; } } - + /// /// The USBDevice this pipe is associated with /// @@ -45,7 +43,7 @@ namespace MadWizard.WinUSBNet return _device; } } - + /// /// Maximum packet size for transfers on this endpoint /// @@ -125,9 +123,9 @@ namespace MadWizard.WinUSBNet try { uint bytesRead; - + _device.InternalDevice.ReadPipe(Interface.InterfaceIndex, _pipeInfo.PipeId, buffer, offset, length, out bytesRead); - + return (int)bytesRead; } catch (API.APIException e) @@ -255,7 +253,7 @@ namespace MadWizard.WinUSBNet { Write(buffer, 0, buffer.Length); } - + /// /// Writes data from a buffer to the pipe. /// @@ -379,7 +377,7 @@ namespace MadWizard.WinUSBNet LogAndThrowException(new USBException("Failed to abort pipe.", e)); } } - + /// /// Resets all pending transfers for this pipe. /// @@ -430,7 +428,7 @@ namespace MadWizard.WinUSBNet // Initialize policy now that interface is set (policy requires interface) _policy = new USBPipePolicy(_device, _interface.InterfaceIndex, _pipeInfo.PipeId); } - + private void LogException(Exception Ex) { WPinternals.LogFile.Log("Error on USB port!", WPinternals.LogType.FileOnly); @@ -442,7 +440,7 @@ namespace MadWizard.WinUSBNet if ((LastWritten == null) && (Ex is USBException) && (Ex.InnerException is MadWizard.WinUSBNet.API.APIException) && (((MadWizard.WinUSBNet.API.APIException)Ex.InnerException).InnerException is System.ComponentModel.Win32Exception) && (((System.ComponentModel.Win32Exception)Ex.InnerException.InnerException).NativeErrorCode == 0X1F)) - WPinternals.LogFile.Log("Failed to communicate on new USB connection", WPinternals.LogType.FileAndConsole); + WPinternals.LogFile.Log("Failed to communicate on new USB connection", WPinternals.LogType.FileAndConsole); if (LastWritten != null) WPinternals.LogFile.Log("Last written: " + WPinternals.Converter.ConvertHexToString(LastWritten, ""), WPinternals.LogType.FileOnly); diff --git a/WinUSBNet/USBPipeCollection.cs b/WinUSBNet/USBPipeCollection.cs index 7d2fd76..9f9e9c4 100644 --- a/WinUSBNet/USBPipeCollection.cs +++ b/WinUSBNet/USBPipeCollection.cs @@ -6,7 +6,6 @@ */ using System; -using System.Text; using System.Collections; using System.Collections.Generic; @@ -37,7 +36,7 @@ namespace MadWizard.WinUSBNet /// The pipe with the given pipe address /// Thrown if no pipe with the specified address /// is available in the collection. - public USBPipe this [byte pipeAddress] + public USBPipe this[byte pipeAddress] { get { @@ -80,11 +79,11 @@ namespace MadWizard.WinUSBNet { get { - return GetCurrent(); + return GetCurrent(); } } - - + + object IEnumerator.Current { get @@ -122,7 +121,7 @@ namespace MadWizard.WinUSBNet { return new UsbPipeEnumerator(GetPipeList()); } - + /// /// Returns an enumerator that iterates through a collection. /// diff --git a/WinUSBNet/USBPipePolicy.cs b/WinUSBNet/USBPipePolicy.cs index f198393..5032815 100644 --- a/WinUSBNet/USBPipePolicy.cs +++ b/WinUSBNet/USBPipePolicy.cs @@ -6,9 +6,6 @@ */ using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; namespace MadWizard.WinUSBNet { @@ -30,7 +27,7 @@ namespace MadWizard.WinUSBNet _device = device; } - + private void RequireDirectionOut() { @@ -82,7 +79,7 @@ namespace MadWizard.WinUSBNet _device.InternalDevice.SetPipePolicy(_interfaceIndex, _pipeID, API.POLICY_TYPE.AUTO_CLEAR_STALL, value); } } - + /// /// If both AllowPartialReads and AutoFlush are true, when the device returns more data than requested by the client it /// will discard the remaining data. Default value is false. Only available on IN direction pipes. @@ -119,7 +116,7 @@ namespace MadWizard.WinUSBNet _device.InternalDevice.SetPipePolicy(_interfaceIndex, _pipeID, API.POLICY_TYPE.IGNORE_SHORT_PACKETS, value); } } - + /// /// Specifies the timeout in milliseconds for pipe operations. If an operation does not finish within the specified time it will fail. /// When set to zero, no timeout is used. Default value is zero.