LzmaAlone.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  1. using System;
  2. using System.IO;
  3. namespace SevenZip
  4. {
  5. using CommandLineParser;
  6. public class CDoubleStream: Stream
  7. {
  8. public System.IO.Stream s1;
  9. public System.IO.Stream s2;
  10. public int fileIndex;
  11. public long skipSize;
  12. public override bool CanRead { get { return true; }}
  13. public override bool CanWrite { get { return false; }}
  14. public override bool CanSeek { get { return false; }}
  15. public override long Length { get { return s1.Length + s2.Length - skipSize; } }
  16. public override long Position
  17. {
  18. get { return 0; }
  19. set { }
  20. }
  21. public override void Flush() { }
  22. public override int Read(byte[] buffer, int offset, int count)
  23. {
  24. int numTotal = 0;
  25. while (count > 0)
  26. {
  27. if (fileIndex == 0)
  28. {
  29. int num = s1.Read(buffer, offset, count);
  30. offset += num;
  31. count -= num;
  32. numTotal += num;
  33. if (num == 0)
  34. fileIndex++;
  35. }
  36. if (fileIndex == 1)
  37. {
  38. numTotal += s2.Read(buffer, offset, count);
  39. return numTotal;
  40. }
  41. }
  42. return numTotal;
  43. }
  44. public override void Write(byte[] buffer, int offset, int count)
  45. {
  46. throw (new Exception("can't Write"));
  47. }
  48. public override long Seek(long offset, System.IO.SeekOrigin origin)
  49. {
  50. throw (new Exception("can't Seek"));
  51. }
  52. public override void SetLength(long value)
  53. {
  54. throw (new Exception("can't SetLength"));
  55. }
  56. }
  57. class LzmaAlone
  58. {
  59. enum Key
  60. {
  61. Help1 = 0,
  62. Help2,
  63. Mode,
  64. Dictionary,
  65. FastBytes,
  66. LitContext,
  67. LitPos,
  68. PosBits,
  69. MatchFinder,
  70. EOS,
  71. StdIn,
  72. StdOut,
  73. Train
  74. };
  75. static void PrintHelp()
  76. {
  77. System.Console.WriteLine("\nUsage: LZMA <e|d> [<switches>...] inputFile outputFile\n" +
  78. " e: encode file\n" +
  79. " d: decode file\n" +
  80. " b: Benchmark\n" +
  81. "<Switches>\n" +
  82. // " -a{N}: set compression mode - [0, 1], default: 1 (max)\n" +
  83. " -d{N}: set dictionary - [0, 29], default: 23 (8MB)\n" +
  84. " -fb{N}: set number of fast bytes - [5, 273], default: 128\n" +
  85. " -lc{N}: set number of literal context bits - [0, 8], default: 3\n" +
  86. " -lp{N}: set number of literal pos bits - [0, 4], default: 0\n" +
  87. " -pb{N}: set number of pos bits - [0, 4], default: 2\n" +
  88. " -mf{MF_ID}: set Match Finder: [bt2, bt4], default: bt4\n" +
  89. " -eos: write End Of Stream marker\n"
  90. // + " -si: read data from stdin\n"
  91. // + " -so: write data to stdout\n"
  92. );
  93. }
  94. static bool GetNumber(string s, out Int32 v)
  95. {
  96. v = 0;
  97. for (int i = 0; i < s.Length; i++)
  98. {
  99. char c = s[i];
  100. if (c < '0' || c > '9')
  101. return false;
  102. v *= 10;
  103. v += (Int32)(c - '0');
  104. }
  105. return true;
  106. }
  107. static int IncorrectCommand()
  108. {
  109. throw (new Exception("Command line error"));
  110. // System.Console.WriteLine("\nCommand line error\n");
  111. // return 1;
  112. }
  113. static int Main2(string[] args)
  114. {
  115. System.Console.WriteLine("\nLZMA# 4.49 Copyright (c) 1999-2007 Igor Pavlov 2006-07-05\n");
  116. if (args.Length == 0)
  117. {
  118. PrintHelp();
  119. return 0;
  120. }
  121. SwitchForm[] kSwitchForms = new SwitchForm[13];
  122. int sw = 0;
  123. kSwitchForms[sw++] = new SwitchForm("?", SwitchType.Simple, false);
  124. kSwitchForms[sw++] = new SwitchForm("H", SwitchType.Simple, false);
  125. kSwitchForms[sw++] = new SwitchForm("A", SwitchType.UnLimitedPostString, false, 1);
  126. kSwitchForms[sw++] = new SwitchForm("D", SwitchType.UnLimitedPostString, false, 1);
  127. kSwitchForms[sw++] = new SwitchForm("FB", SwitchType.UnLimitedPostString, false, 1);
  128. kSwitchForms[sw++] = new SwitchForm("LC", SwitchType.UnLimitedPostString, false, 1);
  129. kSwitchForms[sw++] = new SwitchForm("LP", SwitchType.UnLimitedPostString, false, 1);
  130. kSwitchForms[sw++] = new SwitchForm("PB", SwitchType.UnLimitedPostString, false, 1);
  131. kSwitchForms[sw++] = new SwitchForm("MF", SwitchType.UnLimitedPostString, false, 1);
  132. kSwitchForms[sw++] = new SwitchForm("EOS", SwitchType.Simple, false);
  133. kSwitchForms[sw++] = new SwitchForm("SI", SwitchType.Simple, false);
  134. kSwitchForms[sw++] = new SwitchForm("SO", SwitchType.Simple, false);
  135. kSwitchForms[sw++] = new SwitchForm("T", SwitchType.UnLimitedPostString, false, 1);
  136. Parser parser = new Parser(sw);
  137. try
  138. {
  139. parser.ParseStrings(kSwitchForms, args);
  140. }
  141. catch
  142. {
  143. return IncorrectCommand();
  144. }
  145. if (parser[(int)Key.Help1].ThereIs || parser[(int)Key.Help2].ThereIs)
  146. {
  147. PrintHelp();
  148. return 0;
  149. }
  150. System.Collections.ArrayList nonSwitchStrings = parser.NonSwitchStrings;
  151. int paramIndex = 0;
  152. if (paramIndex >= nonSwitchStrings.Count)
  153. return IncorrectCommand();
  154. string command = (string)nonSwitchStrings[paramIndex++];
  155. command = command.ToLower();
  156. bool dictionaryIsDefined = false;
  157. Int32 dictionary = 1 << 21;
  158. if (parser[(int)Key.Dictionary].ThereIs)
  159. {
  160. Int32 dicLog;
  161. if (!GetNumber((string)parser[(int)Key.Dictionary].PostStrings[0], out dicLog))
  162. IncorrectCommand();
  163. dictionary = (Int32)1 << dicLog;
  164. dictionaryIsDefined = true;
  165. }
  166. string mf = "bt4";
  167. if (parser[(int)Key.MatchFinder].ThereIs)
  168. mf = (string)parser[(int)Key.MatchFinder].PostStrings[0];
  169. mf = mf.ToLower();
  170. if (command == "b")
  171. {
  172. const Int32 kNumDefaultItereations = 10;
  173. Int32 numIterations = kNumDefaultItereations;
  174. if (paramIndex < nonSwitchStrings.Count)
  175. if (!GetNumber((string)nonSwitchStrings[paramIndex++], out numIterations))
  176. numIterations = kNumDefaultItereations;
  177. return LzmaBench.LzmaBenchmark(numIterations, (UInt32)dictionary);
  178. }
  179. string train = "";
  180. if (parser[(int)Key.Train].ThereIs)
  181. train = (string)parser[(int)Key.Train].PostStrings[0];
  182. bool encodeMode = false;
  183. if (command == "e")
  184. encodeMode = true;
  185. else if (command == "d")
  186. encodeMode = false;
  187. else
  188. IncorrectCommand();
  189. bool stdInMode = parser[(int)Key.StdIn].ThereIs;
  190. bool stdOutMode = parser[(int)Key.StdOut].ThereIs;
  191. Stream inStream = null;
  192. if (stdInMode)
  193. {
  194. throw (new Exception("Not implemeted"));
  195. }
  196. else
  197. {
  198. if (paramIndex >= nonSwitchStrings.Count)
  199. IncorrectCommand();
  200. string inputName = (string)nonSwitchStrings[paramIndex++];
  201. inStream = new FileStream(inputName, FileMode.Open, FileAccess.Read);
  202. }
  203. FileStream outStream = null;
  204. if (stdOutMode)
  205. {
  206. throw (new Exception("Not implemeted"));
  207. }
  208. else
  209. {
  210. if (paramIndex >= nonSwitchStrings.Count)
  211. IncorrectCommand();
  212. string outputName = (string)nonSwitchStrings[paramIndex++];
  213. outStream = new FileStream(outputName, FileMode.Create, FileAccess.Write);
  214. }
  215. FileStream trainStream = null;
  216. if (train.Length != 0)
  217. trainStream = new FileStream(train, FileMode.Open, FileAccess.Read);
  218. if (encodeMode)
  219. {
  220. if (!dictionaryIsDefined)
  221. dictionary = 1 << 23;
  222. Int32 posStateBits = 2;
  223. Int32 litContextBits = 3; // for normal files
  224. // UInt32 litContextBits = 0; // for 32-bit data
  225. Int32 litPosBits = 0;
  226. // UInt32 litPosBits = 2; // for 32-bit data
  227. Int32 algorithm = 2;
  228. Int32 numFastBytes = 128;
  229. bool eos = parser[(int)Key.EOS].ThereIs || stdInMode;
  230. if (parser[(int)Key.Mode].ThereIs)
  231. if (!GetNumber((string)parser[(int)Key.Mode].PostStrings[0], out algorithm))
  232. IncorrectCommand();
  233. if (parser[(int)Key.FastBytes].ThereIs)
  234. if (!GetNumber((string)parser[(int)Key.FastBytes].PostStrings[0], out numFastBytes))
  235. IncorrectCommand();
  236. if (parser[(int)Key.LitContext].ThereIs)
  237. if (!GetNumber((string)parser[(int)Key.LitContext].PostStrings[0], out litContextBits))
  238. IncorrectCommand();
  239. if (parser[(int)Key.LitPos].ThereIs)
  240. if (!GetNumber((string)parser[(int)Key.LitPos].PostStrings[0], out litPosBits))
  241. IncorrectCommand();
  242. if (parser[(int)Key.PosBits].ThereIs)
  243. if (!GetNumber((string)parser[(int)Key.PosBits].PostStrings[0], out posStateBits))
  244. IncorrectCommand();
  245. CoderPropID[] propIDs =
  246. {
  247. CoderPropID.DictionarySize,
  248. CoderPropID.PosStateBits,
  249. CoderPropID.LitContextBits,
  250. CoderPropID.LitPosBits,
  251. CoderPropID.Algorithm,
  252. CoderPropID.NumFastBytes,
  253. CoderPropID.MatchFinder,
  254. CoderPropID.EndMarker
  255. };
  256. object[] properties =
  257. {
  258. (Int32)(dictionary),
  259. (Int32)(posStateBits),
  260. (Int32)(litContextBits),
  261. (Int32)(litPosBits),
  262. (Int32)(algorithm),
  263. (Int32)(numFastBytes),
  264. mf,
  265. eos
  266. };
  267. Compression.LZMA.Encoder encoder = new Compression.LZMA.Encoder();
  268. encoder.SetCoderProperties(propIDs, properties);
  269. encoder.WriteCoderProperties(outStream);
  270. Int64 fileSize;
  271. if (eos || stdInMode)
  272. fileSize = -1;
  273. else
  274. fileSize = inStream.Length;
  275. for (int i = 0; i < 8; i++)
  276. outStream.WriteByte((Byte)(fileSize >> (8 * i)));
  277. if (trainStream != null)
  278. {
  279. CDoubleStream doubleStream = new CDoubleStream();
  280. doubleStream.s1 = trainStream;
  281. doubleStream.s2 = inStream;
  282. doubleStream.fileIndex = 0;
  283. inStream = doubleStream;
  284. long trainFileSize = trainStream.Length;
  285. doubleStream.skipSize = 0;
  286. if (trainFileSize > dictionary)
  287. doubleStream.skipSize = trainFileSize - dictionary;
  288. trainStream.Seek(doubleStream.skipSize, SeekOrigin.Begin);
  289. encoder.SetTrainSize((uint)(trainFileSize - doubleStream.skipSize));
  290. }
  291. encoder.Code(inStream, outStream, -1, -1, null);
  292. }
  293. else if (command == "d")
  294. {
  295. byte[] properties = new byte[5];
  296. if (inStream.Read(properties, 0, 5) != 5)
  297. throw (new Exception("input .lzma is too short"));
  298. Compression.LZMA.Decoder decoder = new Compression.LZMA.Decoder();
  299. decoder.SetDecoderProperties(properties);
  300. if (trainStream != null)
  301. {
  302. if (!decoder.Train(trainStream))
  303. throw (new Exception("can't train"));
  304. }
  305. long outSize = 0;
  306. for (int i = 0; i < 8; i++)
  307. {
  308. int v = inStream.ReadByte();
  309. if (v < 0)
  310. throw (new Exception("Can't Read 1"));
  311. outSize |= ((long)(byte)v) << (8 * i);
  312. }
  313. long compressedSize = inStream.Length - inStream.Position;
  314. decoder.Code(inStream, outStream, compressedSize, outSize, null);
  315. }
  316. else
  317. throw (new Exception("Command Error"));
  318. return 0;
  319. }
  320. [STAThread]
  321. static int Main(string[] args)
  322. {
  323. try
  324. {
  325. return Main2(args);
  326. }
  327. catch (Exception e)
  328. {
  329. Console.WriteLine("{0} Caught exception #1.", e);
  330. // throw e;
  331. return 1;
  332. }
  333. }
  334. }
  335. }