LZF - Echtzeit Kompressions Algorithmus (verbesserte Version)

    • C#
    • .NET (FX) 4.5–4.8

    Es gibt 2 Antworten in diesem Thema. Der letzte Beitrag () ist von VincentTB.

      LZF - Echtzeit Kompressions Algorithmus (verbesserte Version)

      Hi,
      einige haben vielleicht mitbekommen, dass mir die Signaturen der Methoden von wohl einem der besten freien Kompressionsalgorithmen ganz schön zu schaffen machten. Weil dieser QuickLZ ersetzen soll, war nun meine Aufgabe, LZF so anzupassen, dass alles genauso funktioniert wie vorher. U. a. habe ich die Möglichkeit hinzugefügt, dass man die Startposition des zu dekomprimierenden Arrays auswählen kann und es wird nun direkt ein Byte-Array zurückgegeben. Außerdem sind nun die ersten 4 Bytes die original Größe der Datei, was beim Dekomprimieren ein Vorteil ist, weil man nun exakt so viele Bytes reservieren kann, wie nötig sind (und man nicht schätzen muss).

      Hier sind mal ein paar Messwerte:

      1 KiB1 MiB
      Komprimieren40710 Ticks52 ms (6919662 ticks)
      Dekomprimieren3373 Ticks8 ms (1089177 ticks)


      Mit dem Code:
      Spoiler anzeigen

      C#-Quellcode

      1. var data = new byte[1024];
      2. var random = new Random();
      3. random.NextBytes(data);
      4. byte[] result = null;
      5. var sw = Stopwatch.StartNew();
      6. for (int i = 0; i < 50; i++)
      7. {
      8. result = LZF.Compress(data, 0);
      9. }
      10. Console.WriteLine($"Compressing speed: {sw.ElapsedMilliseconds / 50} ms ({sw.ElapsedTicks} ticks) / KiB, final size: {result.Length / 1024} KiB (50 rounds)");
      11. byte[] decompressed = null;
      12. sw.Restart();
      13. for (int i = 0; i < 50; i++)
      14. {
      15. decompressed = LZF.Decompress(result, 0);
      16. }
      17. sw.Stop();
      18. bool hashesAreEqual;
      19. using (var sha256 = new SHA256CryptoServiceProvider())
      20. {
      21. var originalHash = sha256.ComputeHash(data);
      22. var decompressedHash = sha256.ComputeHash(decompressed);
      23. hashesAreEqual = originalHash.SequenceEqual(decompressedHash);
      24. }
      25. Console.WriteLine($"Decompressing speed: {sw.ElapsedMilliseconds / 50} ms ({sw.ElapsedTicks} ticks) / KiB, hashes are {(hashesAreEqual ? "equal" : "not equal")} (50 rounds)");
      26. data = new byte[1024 * 1024];
      27. random.NextBytes(data);
      28. sw.Restart();
      29. for (int i = 0; i < 50; i++)
      30. {
      31. result = LZF.Compress(data, 0);
      32. }
      33. Console.WriteLine($"Compressing speed: {sw.ElapsedMilliseconds / 50} ms ({sw.ElapsedTicks} ticks) / MiB, final size: {result.Length / 1024} KiB (50 rounds)");
      34. sw.Restart();
      35. for (int i = 0; i < 50; i++)
      36. {
      37. decompressed = LZF.Decompress(result, 0);
      38. }
      39. sw.Stop();
      40. using (var sha256 = new SHA256CryptoServiceProvider())
      41. {
      42. var originalHash = sha256.ComputeHash(data);
      43. var decompressedHash = sha256.ComputeHash(decompressed);
      44. hashesAreEqual = originalHash.SequenceEqual(decompressedHash);
      45. }
      46. Console.WriteLine($"Decompressing speed: {sw.ElapsedMilliseconds / 50} ms ({sw.ElapsedTicks} ticks) / MiB, hashes are {(hashesAreEqual ? "equal" : "not equal")} (50 rounds)");


      Ich denke, dass die Werte ganz Ok sind :D

      Hier ist nun der Code:

      C#-Quellcode

      1. /*
      2. * Remove the C++ things, make it static and add offset parameter:
      3. * Copyright (c) 2016 Anapher <https://github.com/Anapher>
      4. *
      5. * Improved version to C# LibLZF Port:
      6. * Copyright (c) 2010 Roman Atachiants <kelindar@gmail.com>
      7. *
      8. * Original CLZF Port:
      9. * Copyright (c) 2005 Oren J. Maurice <oymaurice@hazorea.org.il>
      10. *
      11. * Original LibLZF Library & Algorithm:
      12. * Copyright (c) 2000-2008 Marc Alexander Lehmann <schmorp@schmorp.de>
      13. *
      14. * Redistribution and use in source and binary forms, with or without modifica-
      15. * tion, are permitted provided that the following conditions are met:
      16. *
      17. * 1. Redistributions of source code must retain the above copyright notice,
      18. * this list of conditions and the following disclaimer.
      19. *
      20. * 2. Redistributions in binary form must reproduce the above copyright
      21. * notice, this list of conditions and the following disclaimer in the
      22. * documentation and/or other materials provided with the distribution.
      23. *
      24. * 3. The name of the author may not be used to endorse or promote products
      25. * derived from this software without specific prior written permission.
      26. *
      27. * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
      28. * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MER-
      29. * CHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
      30. * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPE-
      31. * CIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
      32. * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
      33. * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
      34. * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTH-
      35. * ERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
      36. * OF THE POSSIBILITY OF SUCH DAMAGE.
      37. *
      38. * Alternatively, the contents of this file may be used under the terms of
      39. * the GNU General Public License version 2 (the "GPL"), in which case the
      40. * provisions of the GPL are applicable instead of the above. If you wish to
      41. * allow the use of your version of this file only under the terms of the
      42. * GPL and not to allow others to use your version of this file under the
      43. * BSD license, indicate your decision by deleting the provisions above and
      44. * replace them with the notice and other provisions required by the GPL. If
      45. * you do not delete the provisions above, a recipient may use your version
      46. * of this file under either the BSD or the GPL.
      47. */
      48. using System;
      49. namespace LzfTest
      50. {
      51. /// <summary>
      52. /// Improved C# LZF Compressor, a very small data compression library. The compression algorithm is extremely fast.
      53. /// </summary>
      54. public static class LZF
      55. {
      56. private const uint HLOG = 14;
      57. private const uint HSIZE = 1 << 14;
      58. private const uint MAX_LIT = 1 << 5;
      59. private const uint MAX_OFF = 1 << 13;
      60. private const uint MAX_REF = (1 << 8) + (1 << 3);
      61. /// <summary>
      62. /// Compresses the data using LibLZF algorithm
      63. /// </summary>
      64. /// <param name="input">Reference to the data to compress</param>
      65. /// <param name="output">Reference to a buffer which will contain the compressed data</param>
      66. /// <param name="start"></param>
      67. /// <returns>The size of the compressed archive in the output buffer</returns>
      68. private static int InternalCompress(byte[] input, byte[] output, int start)
      69. {
      70. var hashTable = new long[HSIZE];
      71. Array.Copy(BitConverter.GetBytes(input.Length - start), output, 4);
      72. uint iidx = (uint)start;
      73. uint oidx = 4;
      74. uint hval = (uint)((input[iidx] << 8) | input[iidx + 1]); // FRST(in_data, iidx);
      75. int lit = 0;
      76. for (;;)
      77. {
      78. if (iidx < input.Length - 2)
      79. {
      80. hval = (hval << 8) | input[iidx + 2];
      81. long hslot = (hval ^ (hval << 5)) >> (int)(3 * 8 - HLOG - hval * 5) & (HSIZE - 1);
      82. var reference = hashTable[hslot];
      83. hashTable[hslot] = iidx;
      84. long off;
      85. if ((off = iidx - reference - 1) < MAX_OFF
      86. && iidx + 4 < input.Length
      87. && reference > 0
      88. && input[reference + 0] == input[iidx + 0]
      89. && input[reference + 1] == input[iidx + 1]
      90. && input[reference + 2] == input[iidx + 2]
      91. )
      92. {
      93. /* match found at *reference++ */
      94. uint len = 2;
      95. uint maxlen = (uint)input.Length - iidx - len;
      96. maxlen = maxlen > MAX_REF ? MAX_REF : maxlen;
      97. if (oidx + lit + 1 + 3 >= output.Length)
      98. return 0;
      99. do
      100. len++; while (len < maxlen && input[reference + len] == input[iidx + len]);
      101. if (lit != 0)
      102. {
      103. output[oidx++] = (byte)(lit - 1);
      104. lit = -lit;
      105. do
      106. output[oidx++] = input[iidx + lit]; while (++lit != 0);
      107. }
      108. len -= 2;
      109. iidx++;
      110. if (len < 7)
      111. {
      112. output[oidx++] = (byte)((off >> 8) + (len << 5));
      113. }
      114. else
      115. {
      116. output[oidx++] = (byte)((off >> 8) + (7 << 5));
      117. output[oidx++] = (byte)(len - 7);
      118. }
      119. output[oidx++] = (byte)off;
      120. iidx += len - 1;
      121. hval = (uint)((input[iidx] << 8) | input[iidx + 1]);
      122. hval = (hval << 8) | input[iidx + 2];
      123. hashTable[(hval ^ (hval << 5)) >> (int)(3 * 8 - HLOG - hval * 5) & (HSIZE - 1)] = iidx;
      124. iidx++;
      125. hval = (hval << 8) | input[iidx + 2];
      126. hashTable[(hval ^ (hval << 5)) >> (int)(3 * 8 - HLOG - hval * 5) & (HSIZE - 1)] = iidx;
      127. iidx++;
      128. continue;
      129. }
      130. }
      131. else if (iidx == input.Length)
      132. break;
      133. /* one more literal byte we must copy */
      134. lit++;
      135. iidx++;
      136. if (lit == MAX_LIT)
      137. {
      138. if (oidx + 1 + MAX_LIT >= output.Length)
      139. return 0;
      140. output[oidx++] = (byte)(MAX_LIT - 1);
      141. lit = -lit;
      142. do
      143. output[oidx++] = input[iidx + lit]; while (++lit != 0);
      144. }
      145. }
      146. if (lit != 0)
      147. {
      148. if (oidx + lit + 1 >= output.Length)
      149. return 0;
      150. output[oidx++] = (byte)(lit - 1);
      151. lit = -lit;
      152. do
      153. output[oidx++] = input[iidx + lit]; while (++lit != 0);
      154. }
      155. return (int)oidx;
      156. }
      157. /// <summary>
      158. /// Compresses the data using LibLZF algorithm
      159. /// </summary>
      160. /// <param name="source">Reference to the data to compress</param>
      161. /// <param name="start">The point where it should start to decompress from the <see cref="source" /></param>
      162. /// <returns>The compressed bytes</returns>
      163. public static byte[] Compress(byte[] source, int start)
      164. {
      165. var destination = new byte[source.Length + source.Length / 2 + 36000];
      166. var used = InternalCompress(source, destination, start);
      167. if (used == 0)
      168. return null;
      169. var compressed = new byte[used];
      170. for (uint i = 0; i < used; ++i)
      171. compressed[i] = destination[i];
      172. return compressed;
      173. }
      174. /// <summary>
      175. /// Decompresses the data using LibLZF algorithm
      176. /// </summary>
      177. /// <param name="source">Reference to the data to decompress</param>
      178. /// <param name="start">
      179. /// The point where it should start to decompress from the <see cref="source"/</param>
      180. /// <returns>The decompressed bytes</returns>
      181. public static byte[] Decompress(byte[] source, int start)
      182. {
      183. var decompressed = new byte[GetSize(source, start)];
      184. var used = InternalDecompress(source, decompressed, start);
      185. if (used == 0)
      186. throw new InvalidOperationException("Impossible");
      187. return decompressed;
      188. }
      189. /// <summary>
      190. /// Decompresses the data using LibLZF algorithm
      191. /// </summary>
      192. /// <param name="input">Reference to the data to decompress</param>
      193. /// <param name="output">Reference to a buffer which will contain the decompressed data</param>
      194. /// <param name="start"></param>
      195. /// <returns>Returns decompressed size</returns>
      196. private static int InternalDecompress(byte[] input, byte[] output, int start)
      197. {
      198. uint iidx = 4 + (uint)start;
      199. uint oidx = 0;
      200. do
      201. {
      202. uint ctrl = input[iidx++];
      203. if (ctrl < 1 << 5) /* literal run */
      204. {
      205. ctrl++;
      206. if (oidx + ctrl > output.Length)
      207. {
      208. //SET_ERRNO (E2BIG);
      209. return 0;
      210. }
      211. do
      212. output[oidx++] = input[iidx++]; while (--ctrl != 0);
      213. }
      214. else /* back reference */
      215. {
      216. uint len = ctrl >> 5;
      217. int reference = (int)(oidx - ((ctrl & 0x1f) << 8) - 1);
      218. if (len == 7)
      219. len += input[iidx++];
      220. reference -= input[iidx++];
      221. if (oidx + len + 2 > output.Length)
      222. {
      223. //SET_ERRNO (E2BIG);
      224. return 0;
      225. }
      226. if (reference < 0)
      227. {
      228. //SET_ERRNO (EINVAL);
      229. return 0;
      230. }
      231. output[oidx++] = output[reference++];
      232. output[oidx++] = output[reference++];
      233. do
      234. output[oidx++] = output[reference++]; while (--len != 0);
      235. }
      236. } while (iidx < input.Length);
      237. return (int)oidx;
      238. }
      239. private static int GetSize(byte[] source, int start)
      240. {
      241. return BitConverter.ToInt32(source, start);
      242. }
      243. }
      244. }


      Der Code stammt nicht von mir, wurde aber von mir verbessert. Die Lizenz hat sich nicht verändert, findet ihr hier: csharplzfcompression.codeplex.com/license
      Den originalen Code könnt ihr hier finden: csharplzfcompression.codeplex.com/SourceControl/latest
      Im Anhang findet ihr noch ein Test Projekt, welches ich für die Messwerte oben verwendet habe.
      Dateien
      • LzfTest.zip

        (34,76 kB, 201 mal heruntergeladen, zuletzt: )
      Mfg
      Vincent

      Dieser Beitrag wurde bereits 2 mal editiert, zuletzt von „VincentTB“ ()

      Hi @VincentTB!

      Erst mal: Sehr gute Arbeit ;D

      Hab den Code mal ausprobiert und mir ist da aber folgendes aufgfallen:
      In deinem Bsp erstellst du ein byte-Array, das du zufällig mit Werten füllst. Dass der Code schnell komprimiert stell ich jetz mal außer frage, aber was die Kompressionsstärke in dem Fall angeht, versagt der doch auf ganzer Länge. Oder mach ich da was falsch?

      Wenn ich folgenden Code verwende:

      C#-Quellcode

      1. var data = new byte[1024];
      2. byte[] result = null;
      3. var random = new Random();
      4. random.NextBytes(data);
      5. result = LZF.Compress(data, 0);
      6. File.WriteAllBytes("data.txt", data);
      7. File.WriteAllBytes("result.txt", result);


      dann erstelle ich mir ja 2 Dateien: eine data.txt und eine result.txt
      Wenn ich jetz mit dem Explorer mir die Dateien anschaue, dann ist die erste(data.txt) ganze 1024 bytes groß, die komprimierte datei aber 1060 kb groß.


      Lg Radinator

      PS: Bei 20Mb random bytes ist der Unterschied fast ein ganzes MB
      In general (across programming languages), a pointer is a number that represents a physical location in memory. A nullpointer is (almost always) one that points to 0, and is widely recognized as "not pointing to anything". Since systems have different amounts of supported memory, it doesn't always take the same number of bytes to hold that number, so we call a "native size integer" one that can hold a pointer on any particular system. - Sam Harwell
      @Radinator
      Das ist völlig logisch, zufällige Bytes können nicht komprimiert werden. Es wird größer, weil dann noch Metadaten dazu kommen. Teste das doch mal z. B. mit einer Bild-Datei, diese wird wesentlich kleiner. Zufällige Bytes sind vielleicht nicht optimal, um zu zeigen, was der Algorithmus kann :D Bei dem offiziellen Benchmark wurden auch andere Methoden genutzt, um die Daten zu generieren, für mich war das mehr so eine Kontrolle, dass der Algorithmus trotz meinen Änderungen gut funktioniert.

      Ich habe übrigens bei meiner Implementierung noch einen Check gemacht, ob sich die Kompression überhaupt gelohnt hat, wenn nicht, schicke ich die unkomprimierten Bytes. Das spart dann auch Zeit auf der Clientseite, weil diese dann nicht extra dekomprimiert werden müssen (Man sollte vielleicht dazu sagen, dass es sich um einen Server-Client Datenaustausch handelt).
      Mfg
      Vincent