pucrunch.c 50 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614
  1. /* pucrunch.c: Pucrunch compression code
  2. Pucrunch 1997-2005 by Pasi 'Albert' Ojala, a1bert@iki.fi
  3. Copyright (C) 2000 Thomas Nussbaumer
  4. Copyright (C) 2007 Kevin Kofler
  5. This program is free software; you can redistribute it and/or modify
  6. it under the terms of the GNU General Public License as published by
  7. the Free Software Foundation; either version 2, or (at your option)
  8. any later version.
  9. This program is distributed in the hope that it will be useful,
  10. but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. GNU General Public License for more details.
  13. You should have received a copy of the GNU General Public License
  14. along with this program; if not, write to the Free Software Foundation,
  15. Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */
  16. #include <stdio.h>
  17. #include <stdlib.h>
  18. #include <string.h>
  19. #include <math.h>
  20. #include <ctype.h>
  21. #include <time.h>
  22. #include "../generic.h"
  23. #include "../formats/packhead.h" // compressed header definition
  24. #include "pucrunch.h"
  25. #define VERBOSE_OUT stdout
  26. #ifndef min
  27. #define min(a,b) ((a<b)?(a):(b))
  28. #endif
  29. #define LRANGE (((2<<maxGamma)-3)*256) /* 0..125, 126 -> 1..127 */
  30. #define MAXLZLEN (2<<maxGamma)
  31. #define MAXRLELEN (((2<<maxGamma)-2)*256) /* 0..126 -> 1..127 */
  32. #define DEFAULT_LZLEN LRANGE
  33. unsigned short *rle, *elr, *lzlen, *lzpos;
  34. int *length, inlen;
  35. unsigned char *indata, *mode, *newesc;
  36. unsigned short *backSkip;
  37. enum MODE {
  38. LITERAL = 0,
  39. LZ77 = 1,
  40. RLE = 2,
  41. MMARK = 4
  42. };
  43. int lzopt = 0;
  44. int maxGamma = 7;
  45. int reservedBytes = 2;
  46. int escBits = 2;
  47. int escMask = 0xc0;
  48. int extraLZPosBits = 0;
  49. int rleUsed = 31;
  50. unsigned char rleLen[256];
  51. int lenValue[256];
  52. int lrange, maxlzlen, maxrlelen;
  53. int gainedEscaped = 0;
  54. int gainedRle = 0, gainedSRle = 0, gainedLRle = 0;
  55. int gainedLz = 0, gainedRlecode = 0;
  56. int timesEscaped = 0, timesNormal = 0;
  57. int timesRle = 0, timesSRle = 0, timesLRle = 0;
  58. int timesLz = 0;
  59. int lenStat[8][4];
  60. unsigned char rleValues[32] = {1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
  61. 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
  62. int rleHist[256];
  63. #define OUT_SIZE 65536
  64. unsigned char outBuffer[OUT_SIZE];
  65. int outPointer = 0;
  66. int bitMask = 0x80;
  67. void TTPackInit(void) {
  68. int i;
  69. rleValues[0] = 1;
  70. for (i=1;i<32;i++) rleValues[i] = 0;
  71. for (i=0;i<256;i++) {
  72. rleLen[i] = 0;
  73. lenValue[i] = 0;
  74. rleHist[i] = 0;
  75. }
  76. for (i=0;i<OUT_SIZE;i++) outBuffer[i] = 0;
  77. lrange = 0, maxlzlen = 0, maxrlelen = 0;
  78. gainedEscaped = 0;
  79. gainedRle = 0, gainedSRle = 0, gainedLRle = 0;
  80. gainedLz = 0, gainedRlecode = 0;
  81. timesEscaped = 0, timesNormal = 0;
  82. timesRle = 0, timesSRle = 0, timesLRle = 0;
  83. timesLz = 0;
  84. lrange = 0;
  85. maxlzlen = 0;
  86. maxrlelen = 0;
  87. outPointer = 0;
  88. bitMask = 0x80;
  89. lzopt = 0;
  90. maxGamma = 7;
  91. reservedBytes = 2;
  92. escBits = 2;
  93. escMask = 0xc0;
  94. extraLZPosBits = 0;
  95. rleUsed = 31;
  96. rle = NULL;
  97. elr = NULL;
  98. lzlen = NULL;
  99. lzpos = NULL;
  100. length = NULL;
  101. inlen = 0;
  102. indata = NULL;
  103. mode = NULL;
  104. newesc = NULL;
  105. backSkip = NULL;
  106. }
  107. //=============================================================================
  108. // the packing code
  109. //=============================================================================
  110. int SavePack(unsigned char *data, int size, FILE *fp, int escape,
  111. unsigned char *rleValues, int extraLZPosBits)
  112. {
  113. int i;
  114. if (!data) return 10;
  115. /* Save without decompressor */
  116. PackedHeader cth;
  117. RLEEntries re;
  118. cth.origsize_lo = inlen & 0xff;
  119. cth.origsize_hi = (inlen >> 8);
  120. cth.magic1 = MAGIC_CHAR1;
  121. cth.magic2 = MAGIC_CHAR2;
  122. cth.compsize_lo = (size + rleUsed + sizeof(PackedHeader)) & 0xff;
  123. cth.compsize_hi = (size + rleUsed + sizeof(PackedHeader)) >> 8;
  124. cth.esc1 = (escape >> (8-escBits));
  125. cth.notused3 = 0; // just to make sure it has a defined value
  126. cth.notused4 = 0; // just to make sure it has a defined value
  127. cth.esc2 = escBits;
  128. cth.gamma1 = maxGamma + 1;
  129. cth.gamma2 = (1 << maxGamma);
  130. cth.extralz = extraLZPosBits;
  131. cth.notused1 = 0; // just to make sure it has a defined value
  132. cth.notused2 = 0; // just to make sure it has a defined value
  133. cth.rleentries = rleUsed;
  134. for(i=0; i<rleUsed; i++) re.value[i] = rleValues[i+1];
  135. fwrite(&cth, 1, sizeof(PackedHeader), fp); // write header
  136. fwrite(&re, 1, cth.rleentries, fp); // write rle values
  137. fwrite(data, size, 1, fp); // write compressed data
  138. return 0;
  139. }
  140. //=============================================================================
  141. //
  142. //=============================================================================
  143. void FlushBits(void) {
  144. if (bitMask != 0x80) outPointer++;
  145. }
  146. //=============================================================================
  147. //
  148. //=============================================================================
  149. void PutBit(int bit) {
  150. if (bit && outPointer < OUT_SIZE) outBuffer[outPointer] |= bitMask;
  151. bitMask >>= 1;
  152. if (!bitMask) {
  153. bitMask = 0x80;
  154. outPointer++;
  155. }
  156. }
  157. //=============================================================================
  158. //
  159. //=============================================================================
  160. void PutValue(int value) {
  161. int bits = 0, count = 0;
  162. while (value>1) {
  163. bits = (bits<<1) | (value & 1); /* is reversed compared to value */
  164. value >>= 1;
  165. count++;
  166. PutBit(1);
  167. }
  168. if (count<maxGamma) PutBit(0);
  169. while (count--) {
  170. PutBit((bits & 1)); /* output is reversed again -> same as value */
  171. bits >>= 1;
  172. }
  173. }
  174. //--------------------------------------------
  175. // why not initializing value lenValue[0] ????
  176. //--------------------------------------------
  177. //=============================================================================
  178. //
  179. //=============================================================================
  180. void InitValueLen() {
  181. int i;
  182. // could be heavily optimized, but isn't necessary
  183. for (i=1; i<256; i++) {
  184. int count = 0;
  185. if (i<2) count = 0; /* 1 */
  186. else if (i<4) count = 1; /* 2-3 */
  187. else if (i<8) count = 2; /* 4-7 */
  188. else if (i<16) count = 3; /* 8-15 */
  189. else if (i<32) count = 4; /* 16-31 */
  190. else if (i<64) count = 5; /* 32-63 */
  191. else if (i<128) count = 6; /* 64-127 */
  192. else if (i<256) count = 7; /* 128-255 */
  193. lenValue[i] = 2*count;
  194. if (count<maxGamma) lenValue[i]++;
  195. }
  196. }
  197. #define LenValue(a) (lenValue[a])
  198. //=============================================================================
  199. //
  200. //=============================================================================
  201. void PutNBits(int byte, int bits) {
  202. while (bits--)
  203. PutBit((byte & (1<<bits)));
  204. }
  205. //=============================================================================
  206. //
  207. //=============================================================================
  208. int OutputNormal(int *esc, unsigned char *data, int newesc) {
  209. timesNormal++;
  210. if ((data[0] & escMask) == *esc) {
  211. PutNBits((*esc>>(8-escBits)), escBits); /* escBits>=0 */
  212. PutBit(0);
  213. PutBit(1);
  214. PutBit(0);
  215. *esc = newesc;
  216. PutNBits((*esc>>(8-escBits)), escBits); /* escBits>=0 */
  217. PutNBits(data[0], 8-escBits);
  218. gainedEscaped += escBits + 3;
  219. timesEscaped++;
  220. return 1;
  221. }
  222. PutNBits(data[0], 8);
  223. return 0;
  224. }
  225. //=============================================================================
  226. //
  227. //=============================================================================
  228. void OutputEof(int *esc) {
  229. /* EOF marker */
  230. PutNBits((*esc>>(8-escBits)), escBits); /* escBits>=0 */
  231. PutValue(3); /* >2 */
  232. PutValue((2<<maxGamma)-1); /* Maximum value */
  233. FlushBits();
  234. }
  235. //=============================================================================
  236. //
  237. //=============================================================================
  238. void PutRleByte(int data) {
  239. int index;
  240. for (index = 1; index < 32; index++) {
  241. if (data == rleValues[index]) {
  242. if (index==1) lenStat[0][3]++;
  243. else if (index<=3) lenStat[1][3]++;
  244. else if (index<=7) lenStat[2][3]++;
  245. else if (index<=15) lenStat[3][3]++;
  246. else if (index<=31) lenStat[4][3]++;
  247. gainedRlecode += 8 - LenValue(index);
  248. PutValue(index);
  249. return;
  250. }
  251. }
  252. PutValue(32 + (data>>3));
  253. gainedRlecode -= LenValue(32+(data>>3)) + 3;
  254. PutNBits(data, 3);
  255. lenStat[5][3]++;
  256. }
  257. //=============================================================================
  258. //
  259. //=============================================================================
  260. void InitRleLen() {
  261. int i;
  262. for (i=0; i<256; i++) rleLen[i] = LenValue(32 + 0) + 3;
  263. for (i=1; i<32; i++) rleLen[rleValues[i]] = LenValue(i);
  264. }
  265. #define LenRleByte(d) (rleLen[d])
  266. //=============================================================================
  267. //
  268. //=============================================================================
  269. int LenRle(int len, int data) {
  270. int out = 0;
  271. do {
  272. if (len == 1) {
  273. out += escBits + 3 + 8;
  274. len = 0;
  275. }
  276. else if (len <= (1<<maxGamma)) {
  277. out += escBits + 3 + LenValue(len-1) + LenRleByte(data);
  278. len = 0;
  279. }
  280. else {
  281. int tmp = min(len, maxrlelen);
  282. out += escBits + 3 + maxGamma + 8 +
  283. LenValue(((tmp-1)>>8)+1) + LenRleByte(data);
  284. len -= tmp;
  285. }
  286. } while (len);
  287. return out;
  288. }
  289. //=============================================================================
  290. //
  291. //=============================================================================
  292. int OutputRle(int *esc, unsigned char *data, int rlelen) {
  293. int len = rlelen, tmp;
  294. while (len) {
  295. if (len >= 2 && len <= (1<<maxGamma)) {
  296. /* Short RLE */
  297. if (len==2) lenStat[0][2]++;
  298. else if (len<=4) lenStat[1][2]++;
  299. else if (len<=8) lenStat[2][2]++;
  300. else if (len<=16) lenStat[3][2]++;
  301. else if (len<=32) lenStat[4][2]++;
  302. else if (len<=64) lenStat[5][2]++;
  303. else if (len<=128) lenStat[6][2]++;
  304. else if (len<=256) lenStat[6][2]++;
  305. PutNBits((*esc>>(8-escBits)), escBits); /* escBits>=0 */
  306. PutBit(0);
  307. PutBit(1);
  308. PutBit(1);
  309. PutValue(len-1);
  310. PutRleByte(*data);
  311. tmp = 8*len -escBits -3 -LenValue(len-1) -LenRleByte(*data);
  312. gainedRle += tmp;
  313. gainedSRle += tmp;
  314. timesRle++;
  315. timesSRle++;
  316. return 0;
  317. }
  318. if (len<3) {
  319. while (len--)
  320. OutputNormal(esc, data, *esc);
  321. return 0;
  322. }
  323. if (len <= maxrlelen) {
  324. /* Run-length encoding */
  325. PutNBits((*esc>>(8-escBits)), escBits); /* escBits>=0 */
  326. PutBit(0);
  327. PutBit(1);
  328. PutBit(1);
  329. PutValue((1<<maxGamma) + (((len-1)&0xff)>>(8-maxGamma)));
  330. PutNBits((len-1), 8-maxGamma);
  331. PutValue(((len-1)>>8) + 1);
  332. PutRleByte(*data);
  333. tmp = 8*len -escBits -3 -maxGamma -8 -LenValue(((len-1)>>8)+1)
  334. -LenRleByte(*data);
  335. gainedRle += tmp;
  336. gainedLRle += tmp;
  337. timesRle++;
  338. timesLRle++;
  339. return 0;
  340. }
  341. /* Run-length encoding */
  342. PutNBits((*esc>>(8-escBits)), escBits); /* escBits>=0 */
  343. PutBit(0);
  344. PutBit(1);
  345. PutBit(1);
  346. PutValue((1<<maxGamma) + (((maxrlelen-1)&0xff)>>(8-maxGamma)));
  347. PutNBits((maxrlelen-1) & 0xff, 8-maxGamma);
  348. PutValue(((maxrlelen-1)>>8)+1);
  349. PutRleByte(*data);
  350. tmp = 8*maxrlelen -escBits -3 -maxGamma -8
  351. -LenValue(((maxrlelen-1)>>8)+1) -LenRleByte(*data);
  352. gainedRle += tmp;
  353. gainedLRle += tmp;
  354. timesRle++;
  355. timesLRle++;
  356. len -= maxrlelen;
  357. data += maxrlelen;
  358. }
  359. return 0;
  360. }
  361. //=============================================================================
  362. //
  363. //=============================================================================
  364. int LenLz(int lzlen, int lzpos) {
  365. if (lzlen==2) {
  366. if (lzpos <= 256) return escBits + 2 + 8;
  367. else return 100000;
  368. }
  369. return escBits + 8 + extraLZPosBits +
  370. LenValue(((lzpos-1)>>(8+extraLZPosBits))+1) +
  371. LenValue(lzlen-1);
  372. }
  373. //=============================================================================
  374. //
  375. //=============================================================================
  376. int OutputLz(int *esc, int lzlen, int lzpos, int curpos) {
  377. if (lzlen==2) lenStat[0][1]++;
  378. else if (lzlen<=4) lenStat[1][1]++;
  379. else if (lzlen<=8) lenStat[2][1]++;
  380. else if (lzlen<=16) lenStat[3][1]++;
  381. else if (lzlen<=32) lenStat[4][1]++;
  382. else if (lzlen<=64) lenStat[5][1]++;
  383. else if (lzlen<=128) lenStat[6][1]++;
  384. else if (lzlen<=256) lenStat[7][1]++;
  385. if (lzlen >= 2 && lzlen <= maxlzlen) {
  386. int tmp;
  387. PutNBits((*esc>>(8-escBits)), escBits); /* escBits>=0 */
  388. tmp = ((lzpos-1)>>(8+extraLZPosBits))+2;
  389. if (tmp==2) lenStat[0][0]++;
  390. else if (tmp<=4) lenStat[1][0]++;
  391. else if (tmp<=8) lenStat[2][0]++;
  392. else if (tmp<=16) lenStat[3][0]++;
  393. else if (tmp<=32) lenStat[4][0]++;
  394. else if (tmp<=64) lenStat[5][0]++;
  395. else if (tmp<=128) lenStat[6][0]++;
  396. else if (tmp<=256) lenStat[6][0]++;
  397. if (lzlen==2) {
  398. PutValue(lzlen-1);
  399. PutBit(0);
  400. if (lzpos > 256) fprintf(stderr,"ERROR at %d: lzpos too long (%d) for lzlen==2\n",curpos, lzpos);
  401. }
  402. else {
  403. PutValue(lzlen-1);
  404. PutValue( ((lzpos-1) >> (8+extraLZPosBits)) +1);
  405. PutNBits( ((lzpos-1) >> 8), extraLZPosBits);
  406. }
  407. PutNBits(((lzpos-1) & 0xff) ^ 0xff, 8);
  408. gainedLz += 8*lzlen -LenLz(lzlen, lzpos);
  409. timesLz++;
  410. return 3;
  411. }
  412. fprintf(stderr, "ERROR: lzlen too short/long (%d)\n", lzlen);
  413. return lzlen;
  414. }
  415. /* Non-recursive version */
  416. /* NOTE! IMPORTANT! the "length" array length must be inlen+1 */
  417. //=============================================================================
  418. //
  419. //=============================================================================
  420. int OptimizeLength(int optimize) {
  421. int i;
  422. length[inlen] = 0; /* one off the end, our 'target' */
  423. for (i=inlen-1; i>=0; i--) {
  424. int r1 = 8 + length[i+1], r2, r3;
  425. if (!lzlen[i] && !rle[i]) {
  426. length[i] = r1;
  427. mode[i] = LITERAL;
  428. continue;
  429. }
  430. /* If rle>maxlzlen, skip to the start of the rle-maxlzlen.. */
  431. if (rle[i] > maxlzlen && elr[i] > 1) {
  432. int z = elr[i];
  433. i -= elr[i];
  434. r2 = LenRle(rle[i], indata[i]) + length[i+ rle[i]];
  435. if (optimize) {
  436. int ii, mini = rle[i], minv = r2;
  437. int bot = rle[i] - (1<<maxGamma);
  438. if (bot < 2)
  439. bot = 2;
  440. for (ii=mini-1; ii>=bot; ii--) {
  441. int v = LenRle(ii, indata[i]) + length[i + ii];
  442. if (v < minv) {
  443. minv = v;
  444. mini = ii;
  445. }
  446. }
  447. if (minv != r2) {
  448. lzopt += r2 - minv;
  449. rle[i] = mini;
  450. r2 = minv;
  451. }
  452. }
  453. length[i] = r2;
  454. mode[i] = RLE;
  455. for (; z>=0; z--) {
  456. length[i+z] = r2;
  457. mode[i+z] = RLE;
  458. }
  459. continue;
  460. }
  461. r3 = r2 = r1 + 1000; /* r3 >= r2 > r1 */
  462. if (rle[i]) {
  463. r2 = LenRle(rle[i], indata[i]) + length[i+ rle[i]];
  464. if (optimize) {
  465. int ii, mini = rle[i], minv = r2;
  466. /* Check only the original length and all shorter
  467. lengths that are power of two.
  468. Does not really miss many 'minimums' this way,
  469. at least not globally..
  470. Makes the assumption that the Elias Gamma Code is
  471. used, i.e. values of the form 2^n are 'optimal' */
  472. ii = 2;
  473. while (rle[i] > ii) {
  474. int v = LenRle(ii, indata[i]) + length[i + ii];
  475. if (v < minv) {
  476. minv = v;
  477. mini = ii;
  478. }
  479. ii <<= 1;
  480. }
  481. if (minv != r2) {
  482. lzopt += r2 - minv;
  483. rle[i] = mini;
  484. r2 = minv;
  485. }
  486. }
  487. }
  488. if (lzlen[i]) {
  489. r3 = LenLz(lzlen[i], lzpos[i]) + length[i + lzlen[i]];
  490. if (optimize && lzlen[i]>2) {
  491. int ii, mini = lzlen[i], minv = r3;
  492. int topLen = LenLz(lzlen[i], lzpos[i])
  493. - LenValue(lzlen[i]-1);
  494. /* Check only the original length and all shorter
  495. lengths that are power of two.
  496. Does not really miss many 'minimums' this way,
  497. at least not globally..
  498. Makes the assumption that the Elias Gamma Code is
  499. used, i.e. values of the form 2^n are 'optimal' */
  500. ii = 4;
  501. while (lzlen[i] > ii) {
  502. int v = topLen + LenValue(ii-1) + length[i + ii];
  503. if (v < minv) {
  504. minv = v;
  505. mini = ii;
  506. }
  507. ii <<= 1;
  508. }
  509. /*
  510. Note:
  511. 2-byte optimization checks are no longer done
  512. with the rest, because the equation gives too long
  513. code lengths for 2-byte matches if extraLzPosBits>0.
  514. */
  515. /* Two-byte rescan/check */
  516. if (backSkip[i] && backSkip[i] <= 256) {
  517. /* There are previous occurrances (near enough) */
  518. int v = LenLz(2, (int)backSkip[i]) + length[i + 2];
  519. if (v < minv) {
  520. minv = v;
  521. mini = 2;
  522. lzlen[i] = mini;
  523. r3 = minv;
  524. lzpos[i] = (int)backSkip[i];
  525. }
  526. }
  527. if (minv != r3 && minv < r2) {
  528. lzopt += r3 - minv;
  529. lzlen[i] = mini;
  530. r3 = minv;
  531. }
  532. }
  533. }
  534. if (r2 <= r1) {
  535. if (r2 <= r3) {
  536. length[i] = r2;
  537. mode[i] = RLE;
  538. }
  539. else {
  540. length[i] = r3;
  541. mode[i] = LZ77;
  542. }
  543. }
  544. else {
  545. if (r3 <= r1) {
  546. length[i] = r3;
  547. mode[i] = LZ77;
  548. }
  549. else {
  550. length[i] = r1;
  551. mode[i] = LITERAL;
  552. }
  553. }
  554. }
  555. return length[0];
  556. }
  557. /*
  558. The algorithm in the OptimizeEscape() works as follows:
  559. 1) Only unpacked bytes are processed, they are marked
  560. with MMARK. We proceed from the end to the beginning.
  561. Variable A (old/new length) is updated.
  562. 2) At each unpacked byte, one and only one possible
  563. escape matches. A new escape code must be selected
  564. for this case. The optimal selection is the one which
  565. provides the shortest number of escapes to the end
  566. of the file,
  567. i.e. A[esc] = 1+min(A[0], A[1], .. A[states-1]).
  568. For other states A[esc] = A[esc];
  569. If we change escape in this byte, the new escape is
  570. the one with the smallest value in A.
  571. 3) The starting escape is selected from the possibilities
  572. and mode 0 is restored to all mode 3 locations.
  573. */
  574. //=============================================================================
  575. //
  576. //=============================================================================
  577. int OptimizeEscape(int *startEscape, int *nonNormal) {
  578. int i, j, states = (1<<escBits);
  579. long minp = 0, minv = 0, other = 0;
  580. long a[256]; /* needs int/long */
  581. long b[256]; /* Remembers the # of escaped for each */
  582. int esc8 = 8-escBits;
  583. for (i=0; i<256; i++) b[i] = a[i] = -1;
  584. if (states>256) {
  585. fprintf(stderr, "Escape optimize: only 256 states (%d)!\n",states);
  586. return 0;
  587. }
  588. /* Mark those bytes that are actually outputted */
  589. for (i=0; i<inlen; ) {
  590. switch (mode[i]) {
  591. case LZ77:
  592. other++;
  593. i += lzlen[i];
  594. break;
  595. case RLE:
  596. other++;
  597. i += rle[i];
  598. break;
  599. /*case LITERAL:*/
  600. default:
  601. mode[i++] = MMARK; /* mark it used so we can identify it */
  602. break;
  603. }
  604. }
  605. for (i=inlen-1; i>=0; i--) {
  606. /* Using a table to skip non-normal bytes does not help.. */
  607. if (mode[i] == MMARK) {
  608. int k = (indata[i] >> esc8);
  609. /* Change the tag values back to normal */
  610. mode[i] = LITERAL;
  611. /*
  612. k are the matching bytes,
  613. minv is the minimum value,
  614. minp is the minimum index
  615. */
  616. newesc[i] = (minp << esc8);
  617. a[k] = minv + 1;
  618. b[k] = b[minp] + 1;
  619. if (k==minp) {
  620. /* Minimum changed -> need to find a new minimum */
  621. /* a[k] may still be the minimum */
  622. minv++;
  623. for (k=states-1; k>=0; k--) {
  624. if (a[k] < minv) {
  625. minv = a[k];
  626. minp = k;
  627. /*
  628. There may be others, but the first one that
  629. is smaller than the old minimum is equal to
  630. any other new minimum.
  631. */
  632. break;
  633. }
  634. }
  635. }
  636. }
  637. }
  638. /* Select the best value for the initial escape */
  639. if (startEscape) {
  640. i = inlen; /* make it big enough */
  641. for (j=states-1; j>=0; j--) {
  642. if (a[j] <= i) {
  643. *startEscape = (j << esc8);
  644. i = a[j];
  645. }
  646. }
  647. }
  648. if (nonNormal)
  649. *nonNormal = other;
  650. return b[startEscape ? (*startEscape>>esc8) : 0];
  651. }
  652. //=============================================================================
  653. // Initialize the RLE byte code table according to all RLE's found so far O(n)
  654. //=============================================================================
  655. void InitRle(void) {
  656. int p, mr, mv, i;
  657. for (i=1; i<32; i++) {
  658. mr = -1;
  659. mv = 0;
  660. for (p=0; p<256; p++) {
  661. if (rleHist[p] > mv) {
  662. mv = rleHist[p];
  663. mr = p;
  664. }
  665. }
  666. if (mv>0) {
  667. rleValues[i] = mr;
  668. rleHist[mr] = -1;
  669. } else
  670. break;
  671. }
  672. InitRleLen();
  673. }
  674. //=============================================================================
  675. // Initialize the RLE byte code table according to RLE's actually used O(n)
  676. //=============================================================================
  677. void OptimizeRle(int flags) {
  678. int p, mr, mv, i;
  679. if (flags & F_STATS) fprintf(VERBOSE_OUT, "RLE Byte Code Re-Tune, RLE Ranks:\n");
  680. for (p=0; p<256; p++) rleHist[p] = 0;
  681. for (p=0; p<inlen; ) {
  682. switch (mode[p]) {
  683. case LZ77:
  684. p += lzlen[p];
  685. break;
  686. case RLE:
  687. rleHist[indata[p]]++;
  688. p += rle[p];
  689. break;
  690. default:
  691. p++;
  692. break;
  693. }
  694. }
  695. for (i=1; i<32; i++) {
  696. mr = -1;
  697. mv = 0;
  698. for (p=0; p<256; p++) {
  699. if (rleHist[p] > mv) {
  700. mv = rleHist[p];
  701. mr = p;
  702. }
  703. }
  704. if (mv>0) {
  705. rleValues[i] = mr;
  706. if (flags & F_STATS) {
  707. fprintf(VERBOSE_OUT, " %2d.0x%02x %-3d ", i, mr, mv);
  708. if (!((i - 1) % 6)) fprintf(VERBOSE_OUT, "\n");
  709. }
  710. rleHist[mr] = -1;
  711. }
  712. else {
  713. break;
  714. }
  715. }
  716. rleUsed = i-1;
  717. if (flags & F_STATS)
  718. if (((i - 1) % 6)!=1) fprintf(VERBOSE_OUT, "\n");
  719. InitRleLen();
  720. }
  721. //=============================================================================
  722. //
  723. //=============================================================================
  724. int PackLz77(int lzsz, int flags, int *startEscape)
  725. {
  726. int i, j, outlen, p, headerSize;
  727. int escape;
  728. unsigned char *hashValue;
  729. unsigned char *a;
  730. int k;
  731. unsigned short *lastPair;
  732. unsigned short err_occured = 0;
  733. int rescan = 0;
  734. if (lzsz < 0 || lzsz > lrange) {
  735. fprintf(stderr, "LZ range must be from 0 to %d (was %d). Set to %d.\n",
  736. lrange, lzsz, lrange);
  737. lzsz = lrange;
  738. }
  739. if (lzsz > 65535) {
  740. fprintf(stderr,
  741. "LZ range must be from 0 to 65535 (was %d). Set to 65535.\n",
  742. lzsz);
  743. lzsz = 65535;
  744. }
  745. if (!lzsz) fprintf(stderr, "Warning: zero LZ range. Only RLE packing used.\n");
  746. InitRleLen();
  747. length = (int *)calloc(sizeof(int), inlen + 1);
  748. mode = (unsigned char *)calloc(sizeof(unsigned char), inlen);
  749. rle = (unsigned short *)calloc(sizeof(unsigned short), inlen);
  750. elr = (unsigned short *)calloc(sizeof(unsigned short), inlen);
  751. lzlen = (unsigned short *)calloc(sizeof(unsigned short), inlen);
  752. lzpos = (unsigned short *)calloc(sizeof(unsigned short), inlen);
  753. newesc = (unsigned char *)calloc(sizeof(unsigned char), inlen);
  754. backSkip = (unsigned short *)calloc(sizeof(unsigned short), inlen);
  755. hashValue = (unsigned char *)malloc(inlen);
  756. lastPair = (unsigned short *)calloc(sizeof(unsigned short), 256*256);
  757. /* error checking */
  758. if (!length || !mode || !rle || !elr || !lzlen || !lzpos || !newesc ||
  759. !lastPair || !backSkip
  760. || !hashValue)
  761. {
  762. fprintf(stderr, "ERROR: Memory allocation failed!\n");
  763. err_occured = 1;
  764. goto errorexit;
  765. }
  766. i = 0;
  767. j = 0;
  768. a = indata + inlen;
  769. for (p=inlen-1; p>=0; p--) {
  770. k = j;
  771. j = i;
  772. i = *--a; /* Only one read per position */
  773. hashValue[p] = i*3 + j*5 + k*7; /* 7.95 % */
  774. }
  775. /* Detect all RLE and LZ77 jump possibilities */
  776. for (p=0; p<inlen; p++) {
  777. if (flags & F_VERBOSE) {
  778. if (!(p & 2047)) {
  779. fprintf(VERBOSE_OUT, "\r%d ", p);
  780. fflush(VERBOSE_OUT); /* for SAS/C */
  781. }
  782. }
  783. /* check run-length code - must be done, LZ77 search needs it! */
  784. if (rle[p] <= 0) {
  785. unsigned char *a = indata + p;
  786. int val = *a++; /* if this were uchar, it would go to stack..*/
  787. int top = inlen - p;
  788. int rlelen = 1;
  789. /* Loop for the whole RLE */
  790. while (rlelen<top && *a++ == (unsigned char)val) rlelen++;
  791. if (rlelen>=2) {
  792. rleHist[indata[p]]++;
  793. for (i=rlelen-1; i>=0; i--) {
  794. rle[p+i] = rlelen-i;
  795. elr[p+i] = i; /* For RLE backward skipping */
  796. }
  797. }
  798. }
  799. /* check LZ77 code */
  800. if (p+rle[p]+1<inlen) {
  801. int bot = p - lzsz, maxval, maxpos, rlep = rle[p];
  802. unsigned char hashCompare = hashValue[p];
  803. /*
  804. There's always 1 equal byte, although it may
  805. not be marked as RLE.
  806. */
  807. if (rlep <= 0)
  808. rlep = 1;
  809. if (bot < 0)
  810. bot = 0;
  811. bot += (rlep-1);
  812. /*
  813. First get the shortest possible match (if any).
  814. If there is no 2-byte match, don't look further,
  815. because there can't be a longer match.
  816. */
  817. i = (int)lastPair[ (indata[p]<<8) | indata[p+1] ] -1;
  818. if (i>=0 && i>=bot) {
  819. /* Got a 2-byte match at least */
  820. maxval = 2;
  821. maxpos = p-i;
  822. /*
  823. A..AB rlep # of A's, B is something else..
  824. Search for bytes that are in p + (rlep-1), i.e.
  825. the last rle byte ('A') and the non-matching one
  826. ('B'). When found, check if the rle in the compare
  827. position (i) is long enough (i.e. the same number
  828. of A's at p and i-rlep+1).
  829. There are dramatically less matches for AB than for
  830. AA, so we get a huge speedup with this approach.
  831. We are still guaranteed to find the most recent
  832. longest match there is.
  833. */
  834. i = (int)lastPair[(indata[p+(rlep-1)]<<8) | indata[p+rlep]] -1;
  835. while (i>=bot /* && i>=rlep-1 */) { /* bot>=rlep-1, i>=bot ==> i>=rlep-1 */
  836. /* Equal number of A's ? */
  837. if (!(rlep-1) || rle[i-(rlep-1)]==rlep) { /* 'head' matches */
  838. /* rlep==1 ==> (rlep-1)==0 */
  839. /* ivanova.run: 443517 rlep==1,
  840. 709846 rle[i+1-rlep]==rlep */
  841. /*
  842. Check the hash values corresponding to the last
  843. two bytes of the currently longest match and
  844. the first new matching(?) byte. If the hash
  845. values don't match, don't bother to check the
  846. data itself.
  847. */
  848. if (
  849. hashValue[i+maxval-rlep-1] == hashCompare
  850. ) {
  851. unsigned char *a = indata + i+2; /* match */
  852. unsigned char *b = indata + p+rlep-1+2;/* curpos */
  853. int topindex = inlen-(p+rlep-1);
  854. /* the 2 first bytes ARE the same.. */
  855. j = 2;
  856. while (j < topindex && *a++==*b++)
  857. j++;
  858. if (j + rlep-1 > maxval) {
  859. int tmplen = j+rlep-1, tmppos = p-i+rlep-1;
  860. if (tmplen > maxlzlen)
  861. tmplen = maxlzlen;
  862. /* Accept only versions that really are shorter */
  863. if (tmplen*8 - LenLz(tmplen, tmppos) >
  864. maxval*8 - LenLz(maxval, maxpos)) {
  865. maxval = tmplen;
  866. maxpos = tmppos;
  867. hashCompare = hashValue[p+maxval-2];
  868. }
  869. if (maxval == maxlzlen)
  870. break;
  871. }
  872. }
  873. }
  874. if (!backSkip[i])
  875. break; /* No previous occurrances (near enough) */
  876. i -= (int)backSkip[i];
  877. }
  878. /*
  879. If there is 'A' in the previous position also,
  880. RLE-like LZ77 is possible, although rarely
  881. shorter than real RLE.
  882. */
  883. if (p && rle[p-1] > maxval) {
  884. maxval = rle[p-1] - 1;
  885. maxpos = 1;
  886. }
  887. /*
  888. Last, try to find as long as possible match
  889. for the RLE part only.
  890. */
  891. if (maxval < maxlzlen && rlep > maxval) {
  892. bot = p - lzsz;
  893. if (bot < 0)
  894. bot = 0;
  895. /* Note: indata[p] == indata[p+1] */
  896. i = (int)lastPair[indata[p]*257] -1;
  897. while (/* i>= rlep-2 &&*/ i>=bot) {
  898. if (elr[i] + 2 > maxval) {
  899. maxval = min(elr[i] + 2, rlep);
  900. maxpos = p - i + (maxval-2);
  901. if(maxval == rlep)
  902. break; /* Got enough */
  903. }
  904. i -= elr[i];
  905. if (!backSkip[i])
  906. break; /* No previous occurrances (near enough) */
  907. i -= (int)backSkip[i];
  908. }
  909. }
  910. if (p+maxval > inlen) {
  911. fprintf(stderr,"Error @ %d, lzlen %d, pos %d - exceeds inlen\n",p, maxval, maxpos);
  912. maxval = inlen - p;
  913. }
  914. if (maxpos<=256 || maxval > 2) {
  915. if (maxpos < 0) fprintf(stderr, "Error @ %d, lzlen %d, pos %d\n",p, maxval, maxpos);
  916. lzlen[p] = (maxval<maxlzlen)?maxval:maxlzlen;
  917. lzpos[p] = maxpos;
  918. }
  919. }
  920. }
  921. /* Update the two-byte history ('hash table') &
  922. backSkip ('linked list') */
  923. if (p+1<inlen) {
  924. int index = (indata[p]<<8) | indata[p+1];
  925. int ptr = p - (lastPair[index]-1);
  926. if (ptr > p || ptr > 0xffff)
  927. ptr = 0;
  928. backSkip[p] = ptr;
  929. lastPair[index] = p+1;
  930. }
  931. }
  932. if (flags & F_VERBOSE) {
  933. fprintf(VERBOSE_OUT, "\rChecked: %d \n", p);
  934. fflush(VERBOSE_OUT);
  935. }
  936. /* Initialize the RLE selections */
  937. InitRle();
  938. /* Check the normal bytes / all ratio */
  939. {
  940. int mb, mv;
  941. if (flags & F_VERBOSE) {
  942. fprintf(VERBOSE_OUT, "Selecting the number of escape bits.. ");
  943. fflush(VERBOSE_OUT);
  944. }
  945. /*
  946. Absolute maximum number of escaped bytes with
  947. the escape optimize is 2^-n, where n is the
  948. number of escape bits used.
  949. This worst case happens only on equal-
  950. distributed normal bytes (01230123..).
  951. This is why the typical values are so much smaller.
  952. */
  953. mb = 0;
  954. mv = 8*OUT_SIZE;
  955. for (escBits=1; escBits<9; escBits++) {
  956. int escaped, other = 0, c;
  957. escMask = (0xff00>>escBits) & 0xff;
  958. /* Find the optimum path for selected escape bits (no optimize) */
  959. OptimizeLength(0);
  960. /* Optimize the escape selections for this path & escBits */
  961. escaped = OptimizeEscape(&escape, &other);
  962. /* Compare value: bits lost for escaping -- bits lost for prefix */
  963. c = (escBits+3)*escaped + other*escBits;
  964. if (flags & F_STATS) {
  965. fprintf(VERBOSE_OUT, " %d:%d", escBits, c);
  966. fflush(VERBOSE_OUT); /* for SAS/C */
  967. }
  968. if (c < mv) {
  969. mb = escBits;
  970. mv = c;
  971. } else {
  972. /* minimum found */
  973. break;
  974. }
  975. if (escBits==4 && (flags & F_STATS)) fprintf(VERBOSE_OUT, "\n");
  976. }
  977. if (mb==1) { /* Minimum was 1, check 0 */
  978. int escaped;
  979. escBits = 0;
  980. escMask = 0;
  981. /* Find the optimum path for selected escape bits (no optimize) */
  982. OptimizeLength(0);
  983. /* Optimize the escape selections for this path & escBits */
  984. escaped = OptimizeEscape(&escape, NULL);
  985. if ((flags & F_STATS)) {
  986. fprintf(VERBOSE_OUT, " %d:%d", escBits, 3*escaped);
  987. fflush(VERBOSE_OUT); /* for SAS/C */
  988. }
  989. if (3*escaped < mv) {
  990. mb = 0;
  991. /* mv = 3*escaped; */
  992. }
  993. }
  994. if ((flags & F_STATS)) fprintf(VERBOSE_OUT, "\n");
  995. if (flags & F_VERBOSE) fprintf(VERBOSE_OUT, "Selected %d-bit escapes\n", mb);
  996. escBits = mb;
  997. escMask = (0xff00>>escBits) & 0xff;
  998. }
  999. if (flags & F_VERBOSE) {
  1000. fprintf(VERBOSE_OUT, "Optimizing LZ77 and RLE lengths...");
  1001. fflush(VERBOSE_OUT);
  1002. }
  1003. /* Find the optimum path (optimize) */
  1004. OptimizeLength(1);
  1005. if (flags & F_STATS) {
  1006. fprintf(VERBOSE_OUT, " gained %d units.\n", lzopt/8);
  1007. }
  1008. else {
  1009. if (flags & F_VERBOSE) fprintf(VERBOSE_OUT, "\n");
  1010. }
  1011. {
  1012. long lzstat[5] = {0,0,0,0,0}, i, cur = 0, old = extraLZPosBits;
  1013. if (flags & F_VERBOSE) {
  1014. fprintf(VERBOSE_OUT, "Selecting LZPOS LO length.. ");
  1015. fflush(VERBOSE_OUT);
  1016. }
  1017. for (p=0; p<inlen; ) {
  1018. switch (mode[p]) {
  1019. case LZ77:
  1020. extraLZPosBits = 0;
  1021. lzstat[0] += LenLz(lzlen[p], lzpos[p]);
  1022. extraLZPosBits = 1;
  1023. lzstat[1] += LenLz(lzlen[p], lzpos[p]);
  1024. extraLZPosBits = 2;
  1025. lzstat[2] += LenLz(lzlen[p], lzpos[p]);
  1026. extraLZPosBits = 3;
  1027. lzstat[3] += LenLz(lzlen[p], lzpos[p]);
  1028. extraLZPosBits = 4;
  1029. lzstat[4] += LenLz(lzlen[p], lzpos[p]);
  1030. p += lzlen[p];
  1031. break;
  1032. case RLE:
  1033. p += rle[p];
  1034. break;
  1035. default:
  1036. p++;
  1037. break;
  1038. }
  1039. }
  1040. for (i=0; i<5; i++) {
  1041. if (flags & F_STATS) fprintf(VERBOSE_OUT, " %ld:%ld", i + 8, lzstat[i]);
  1042. if (lzstat[i] < lzstat[cur]) cur = i;
  1043. }
  1044. extraLZPosBits = cur;
  1045. if (flags & F_STATS) fprintf(VERBOSE_OUT, "\n");
  1046. if (flags & F_VERBOSE) {
  1047. fprintf(VERBOSE_OUT, "Selected %d-bit LZPOS LO part\n",extraLZPosBits + 8);
  1048. if (cur != old) fprintf(VERBOSE_OUT,"Note: Using option -p%ld you may get better results.\n",cur);
  1049. }
  1050. /* Find the optimum path (optimize) */
  1051. if (extraLZPosBits != old) OptimizeLength(1);
  1052. }
  1053. {
  1054. long stat[4] = {0,0,0,0};
  1055. for (p=0; p<inlen; ) {
  1056. switch (mode[p]) {
  1057. case LZ77:
  1058. if ((lzpos[p] >> 8)+1 > (1<<maxGamma))
  1059. stat[3]++;
  1060. if (lzlen[p] > (1<<maxGamma))
  1061. stat[0]++;
  1062. p += lzlen[p];
  1063. break;
  1064. case RLE:
  1065. if (rle[p] > (1<<(maxGamma-1))) {
  1066. if (rle[p] <= (1<<maxGamma))
  1067. stat[1]++;
  1068. }
  1069. p += rle[p];
  1070. break;
  1071. default:
  1072. p++;
  1073. break;
  1074. }
  1075. }
  1076. /* TODO: better formula.. */
  1077. if (maxGamma < 7 && stat[0] + stat[1] + stat[3] > 10) {
  1078. if (flags & F_VERBOSE) fprintf(VERBOSE_OUT,"Note: Using option -m%d you may get better results.\n",maxGamma+1);
  1079. }
  1080. if (maxGamma > 5 && stat[0] + stat[1] + stat[3] < 4) {
  1081. if (flags & F_VERBOSE) fprintf(VERBOSE_OUT,"Note: Using option -m%d you may get better results.\n",maxGamma-1);
  1082. }
  1083. }
  1084. /* Optimize the escape selections */
  1085. OptimizeEscape(&escape, NULL);
  1086. if (startEscape) *startEscape = escape;
  1087. OptimizeRle(flags); /* Retune the RLE selections */
  1088. if (flags & F_VERBOSE) {
  1089. int oldEscape = escape;
  1090. if (flags & F_VERBOSE) fprintf(VERBOSE_OUT,"normal RLE LZLEN LZPOS(absolute)\n\n");
  1091. for (p=0; p<inlen; ) {
  1092. switch (mode[p]) {
  1093. case LZ77:
  1094. mode[p - lzpos[p]] |= MMARK; /* Was referred to by lz77 */
  1095. p += lzlen[p];
  1096. break;
  1097. case RLE:
  1098. p += rle[p];
  1099. break;
  1100. /* case LITERAL:
  1101. case MMARK:*/
  1102. default:
  1103. p++;
  1104. break;
  1105. }
  1106. }
  1107. j = 0;
  1108. for (p=0; p<inlen; p++) {
  1109. switch (mode[p]) {
  1110. case MMARK | LITERAL:
  1111. case LITERAL:
  1112. if (flags & F_VERBOSE) {
  1113. if (j==p) fprintf(VERBOSE_OUT,">");
  1114. else fprintf(VERBOSE_OUT," ");
  1115. }
  1116. if (j==p) {
  1117. if (flags & F_VERBOSE) {
  1118. fprintf(VERBOSE_OUT,"*001* %03d %03d %04x(%04x) %02x %s %02x",
  1119. rle[p], lzlen[p], lzpos[p], p-lzpos[p], indata[p],
  1120. (mode[p] & MMARK)?"#":" ", newesc[p]);
  1121. }
  1122. if ((indata[p] & escMask) == escape) {
  1123. escape = newesc[p];
  1124. if (flags & F_VERBOSE) fprintf(VERBOSE_OUT,"<<");
  1125. }
  1126. if (flags & F_VERBOSE) fprintf(VERBOSE_OUT,"\n");
  1127. j += 1;
  1128. } else {
  1129. if (flags & F_VERBOSE) fprintf(VERBOSE_OUT,"*001* %03d %03d %04x(%04x) %02x %s %02x\n",
  1130. rle[p], lzlen[p], lzpos[p], p-lzpos[p], indata[p],
  1131. (mode[p] & MMARK)?"#":" ", newesc[p]);
  1132. }
  1133. break;
  1134. case MMARK | LZ77:
  1135. case LZ77:
  1136. if (j==p) {
  1137. if (flags & F_VERBOSE) fprintf(VERBOSE_OUT,">");
  1138. j += lzlen[p];
  1139. } else
  1140. if (flags & F_VERBOSE) fprintf(VERBOSE_OUT," ");
  1141. if (flags & F_VERBOSE) fprintf(VERBOSE_OUT," 001 %03d *%03d* %04x(%04x) %02x %s\n",
  1142. rle[p], lzlen[p], lzpos[p], p-lzpos[p], indata[p],
  1143. (mode[p] & MMARK)?"#":" ");
  1144. break;
  1145. case MMARK | RLE:
  1146. case RLE:
  1147. if (j==p) {
  1148. if (flags & F_VERBOSE) fprintf(VERBOSE_OUT,">");
  1149. j += rle[p];
  1150. } else
  1151. if (flags & F_VERBOSE) fprintf(VERBOSE_OUT," ");
  1152. if (flags & F_VERBOSE) fprintf(VERBOSE_OUT," 001 *%03d* %03d %04x(%04x) %02x %s\n",
  1153. rle[p], lzlen[p], lzpos[p], p-lzpos[p], indata[p],
  1154. (mode[p] & MMARK)?"#":" ");
  1155. break;
  1156. default:
  1157. j++;
  1158. break;
  1159. }
  1160. mode[p] &= ~MMARK;
  1161. }
  1162. escape = oldEscape;
  1163. }
  1164. for (p=0; p<inlen; ) {
  1165. switch (mode[p]) {
  1166. case LITERAL: /* normal */
  1167. length[p] = outPointer;
  1168. OutputNormal(&escape, indata+p, newesc[p]);
  1169. p++;
  1170. break;
  1171. case LZ77: /* lz77 */
  1172. /* Not possible for smaller backSkip table
  1173. (the table is overwritten during previous use) */
  1174. /* Re-search matches to get the closest one */
  1175. if (lzopt && lzlen[p] > 2 && lzlen[p] > rle[p]) {
  1176. int bot = p - lzpos[p] + 1, i;
  1177. unsigned short rlep = rle[p];
  1178. if (!rlep)
  1179. rlep = 1;
  1180. if (bot < 0)
  1181. bot = 0;
  1182. bot += (rlep-1);
  1183. i = p - (int)backSkip[p];
  1184. while (i>=bot /* && i>=rlep-1 */) {
  1185. /* Equal number of A's ? */
  1186. if (rlep==1 || rle[i-rlep+1]==rlep) { /* 'head' matches */
  1187. unsigned char *a = indata + i+1; /* match */
  1188. unsigned char *b = indata + p+rlep-1+1; /* curpos */
  1189. int topindex = inlen-(p+rlep-1);
  1190. j = 1;
  1191. while (j < topindex && *a++==*b++)
  1192. j++;
  1193. if (j + rlep-1 >= lzlen[p]) {
  1194. int tmppos = p-i+rlep-1;
  1195. rescan +=
  1196. LenLz(lzlen[p], lzpos[p]) -
  1197. LenLz(lzlen[p], tmppos);
  1198. lzpos[p] = tmppos;
  1199. break;
  1200. }
  1201. }
  1202. if (!backSkip[i])
  1203. break; /* No previous occurrances (near enough) */
  1204. i -= (int)backSkip[i];
  1205. }
  1206. }
  1207. for (i=0; i<lzlen[p]; i++)
  1208. length[p+i] = outPointer;
  1209. OutputLz(&escape, lzlen[p], lzpos[p], p);
  1210. p += lzlen[p];
  1211. break;
  1212. case RLE: /* rle */
  1213. for (i=0; i<rle[p]; i++)
  1214. length[p+i] = outPointer;
  1215. OutputRle(&escape, indata+p, rle[p]);
  1216. p += rle[p];
  1217. break;
  1218. default: /* Error Flynn :-) */
  1219. p++;
  1220. fprintf(stderr, "Internal error: mode %d\n", mode[p]);
  1221. break;
  1222. }
  1223. }
  1224. OutputEof(&escape);
  1225. i = inlen;
  1226. for (p=0; p<inlen; p++) {
  1227. int pos = (inlen - outPointer) + (int)length[p] - p;
  1228. i = min(i, pos);
  1229. }
  1230. if (i<0)
  1231. reservedBytes = -i + 2;
  1232. else
  1233. reservedBytes = 0;
  1234. headerSize = 16 + rleUsed;
  1235. outlen = outPointer + headerSize; /* unpack code */
  1236. if (flags & F_VERBOSE) fprintf(VERBOSE_OUT, "In: %d, out: %d, ratio: %5.2f%% (%4.2f[%4.2f] b/B)"
  1237. ", gained: %5.2f%%\n",
  1238. inlen, outlen, (double)outlen*100.0/(double)inlen + 0.005,
  1239. 8.0*(double)outlen/(double)inlen + 0.005,
  1240. 8.0*(double)(outlen-headerSize+rleUsed+4)/(double)inlen + 0.005,
  1241. 100.0 - (double)outlen*100.0/(double)inlen + 0.005);
  1242. if (flags & F_VERBOSE) {
  1243. fprintf(VERBOSE_OUT, "Gained RLE: %d (S+L:%d+%d), LZ: %d, Esc: %d"
  1244. ", Decompressor: %d\n",
  1245. gainedRle/8, gainedSRle/8, gainedLRle/8,
  1246. gainedLz/8, -gainedEscaped/8, -headerSize);
  1247. fprintf(VERBOSE_OUT, "Times RLE: %d (%d+%d), LZ: %d, Esc: %d (normal: %d)"
  1248. ", %d escape bit%s\n",
  1249. timesRle, timesSRle, timesLRle,
  1250. timesLz, timesEscaped, timesNormal,
  1251. escBits, (escBits==1)?"":"s" );
  1252. }
  1253. if ((flags & F_STATS)) {
  1254. const char *ll[] = {"2", "3-4", "5-8", "9-16", "17-32", "33-64",
  1255. "65-128", "129-256"};
  1256. fprintf(VERBOSE_OUT, "(Gained by RLE Code: %d, LZPOS LO Bits %d"
  1257. ", maxLen: %d, tag bit/prim. %4.2f)\n",
  1258. gainedRlecode/8 - rleUsed,
  1259. extraLZPosBits + 8,
  1260. (2<<maxGamma),
  1261. (double)((timesRle+timesLz)*escBits +
  1262. timesEscaped*(escBits + 3))/
  1263. (double)(timesRle+timesLz+timesNormal) + 0.0049);
  1264. fprintf(VERBOSE_OUT, " LZPOS HI+2 LZLEN S-RLE RLEcode\n");
  1265. fprintf(VERBOSE_OUT, " ------------------------------\n");
  1266. for (i=0; i<=maxGamma; i++) {
  1267. fprintf(VERBOSE_OUT, "%-7s %5d %5d", ll[i],
  1268. lenStat[i][0], lenStat[i][1]);
  1269. if (i<maxGamma)
  1270. fprintf(VERBOSE_OUT, " %5d", lenStat[i][2]);
  1271. else
  1272. fprintf(VERBOSE_OUT, " -");
  1273. if (i<6)
  1274. fprintf(VERBOSE_OUT, " %5d%s\n", lenStat[i][3], (i==5)?"*":"");
  1275. else
  1276. fprintf(VERBOSE_OUT, " -\n");
  1277. }
  1278. fprintf(VERBOSE_OUT, "LZ77 rescan gained %d bytes\n", rescan/8);
  1279. }
  1280. errorexit:
  1281. if (rle) free(rle);
  1282. if (elr) free(elr);
  1283. if (lzlen) free(lzlen);
  1284. if (lzpos) free(lzpos);
  1285. if (length) free(length);
  1286. if (mode) free(mode);
  1287. if (newesc) free(newesc);
  1288. if (lastPair) free(lastPair);
  1289. if (backSkip) free(backSkip);
  1290. if (hashValue) free(hashValue);
  1291. return err_occured;
  1292. }
  1293. //=============================================================================
  1294. // as usual: the main, but a long one ...
  1295. //=============================================================================
  1296. int TTPack(int flags, int in_len, unsigned char *in_data, FILE *out_file) {
  1297. int startAddr = 0x258;
  1298. int lzlen = -1;
  1299. int startEscape;
  1300. int n;
  1301. unsigned long timeused = clock();
  1302. int memStart = 0x801;
  1303. TTPackInit();
  1304. lrange = LRANGE;
  1305. maxlzlen = MAXLZLEN;
  1306. maxrlelen = MAXRLELEN;
  1307. InitValueLen();
  1308. if (lzlen == -1) lzlen = DEFAULT_LZLEN;
  1309. inlen = in_len;
  1310. indata = in_data;
  1311. if (startAddr + inlen -1 > 0xffff) {
  1312. fprintf(stderr,"ERROR: File is too large to handle (>64936 Bytes)");
  1313. if (indata) free(indata);
  1314. return 1;
  1315. }
  1316. if (flags & F_VERBOSE) {
  1317. fprintf(VERBOSE_OUT, "Load address 0x%04x=%d, Last byte 0x%04x=%d\n",
  1318. startAddr, startAddr, startAddr+inlen-1, startAddr+inlen-1);
  1319. fprintf(VERBOSE_OUT, "New load address 0x%04x=%d\n", memStart, memStart);
  1320. }
  1321. n = PackLz77(lzlen, flags, &startEscape);
  1322. if (!n) {
  1323. // outBuffer ... static global array (65536 Bytes)
  1324. SavePack(outBuffer, outPointer, out_file, startEscape, rleValues, extraLZPosBits);
  1325. timeused = clock()-timeused;
  1326. if (!timeused) timeused++;
  1327. if (flags & F_VERBOSE) fprintf(VERBOSE_OUT,
  1328. "Compressed %d bytes in %4.2f seconds (%4.2f kB/sec)\n",
  1329. inlen,
  1330. (double)timeused/CLOCKS_PER_SEC,
  1331. (double)CLOCKS_PER_SEC*inlen/timeused/1024.0);
  1332. return 0;
  1333. }
  1334. if (indata) free(indata);
  1335. return n;
  1336. }