ttpack.c 72 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224
  1. /******************************************************************************
  2. *
  3. * project name: TIGCC Tools Suite
  4. * file name: ttpack.c
  5. * initial date: 14/08/2000
  6. * authors: albert@cs.tut.fi
  7. * thomas.nussbaumer@gmx.net
  8. * description: packing program
  9. *
  10. * -----------------------------------------------------------------------------
  11. *
  12. * based on code from Pasi 'Albert' Ojala, albert@cs.tut.fi
  13. * Pucrunch 1997-2005 by Pasi 'Albert' Ojala, a1bert@iki.fi
  14. * Pucrunch is under GNU LGPL:
  15. * See http://creativecommons.org/licenses/LGPL/2.1/ or
  16. * http://www.gnu.org/copyleft/lesser.html
  17. *
  18. * The decompression code is distributed under the
  19. * WXWindows Library Licence:
  20. * See http://www.wxwidgets.org/licence3.txt
  21. *
  22. * In short: binary version of the decompression code can
  23. * accompany the compressed data or used in decompression
  24. * programs.
  25. *
  26. * heavily reduced to fit to the needs by thomas.nussbaumer@gmx.net
  27. *
  28. ******************************************************************************/
  29. #ifndef __TTPACK__
  30. #define __TTPACK__
  31. // if EMBEDDED_USE is defined, than we use this sourcefile from within another
  32. // sourcefile
  33. #ifndef EMBEDDED_USE
  34. #include <stdio.h>
  35. #include <stdlib.h>
  36. #include <string.h>
  37. #include <math.h>
  38. #include <ctype.h>
  39. #include <time.h>
  40. #include "tt.h" // generic defines
  41. #include "ttversion.h" // tigcc tools suite version info
  42. #include "revtools.h" // used for id displaying
  43. #include "packhead.h" // compressed header definition
  44. #ifdef CVS_FILE_REVISION
  45. #undef CVS_FILE_REVISION
  46. #endif
  47. //-----------------------------------------------------------------------------
  48. // DON'T EDIT THE NEXT REVISION BY HAND! THIS IS DONE AUTOMATICALLY BY THE
  49. // CVS SYSTEM !!!
  50. //-----------------------------------------------------------------------------
  51. #define CVS_FILE_REVISION "$Revision: 1.3 $"
  52. //=============================================================================
  53. // outputs usage information of this tool
  54. //=============================================================================
  55. void PrintUsage() {
  56. PRINT_ID("TTPack");
  57. fprintf(USAGE_OUT, "Usage: ttpack [-<flags>] <infile> <outfile>\n" \
  58. " -quiet don't output standard messages (unsets v)\n"\
  59. " -hti treat input as hex textinput\n" \
  60. " -hto generate hex textoutput\n" \
  61. " -fdelta use delta-lz77 -- shortens some files\n" \
  62. " e<val> force escape bits\n" \
  63. " r<val> restrict lz search range\n" \
  64. " n no RLE/LZ length optimization\n" \
  65. " s full statistics\n" \
  66. " v verbose (unsets -quiet)\n" \
  67. " p<val> force extralzposbits\n" \
  68. " m<val> max len 5..7 (2*2^5..2*2^7)\n");
  69. }
  70. #endif
  71. #define FIXF_MACHMASK 0xff
  72. #define FIXF_WRAP 256
  73. #define FIXF_DLZ 512
  74. #define F_VERBOSE (1<<0)
  75. #define F_STATS (1<<1)
  76. #define F_AUTO (1<<2)
  77. #define F_NOOPT (1<<3)
  78. #define F_AUTOEX (1<<4)
  79. #define F_TEXTINPUT (1<<5)
  80. #define F_TEXTOUTPUT (1<<6)
  81. #define F_NORLE (1<<9)
  82. #define F_ERROR (1<<15)
  83. #ifndef min
  84. #define min(a,b) ((a<b)?(a):(b))
  85. #endif
  86. #define LRANGE (((2<<maxGamma)-3)*256) /* 0..125, 126 -> 1..127 */
  87. #define MAXLZLEN (2<<maxGamma)
  88. #define MAXRLELEN (((2<<maxGamma)-2)*256) /* 0..126 -> 1..127 */
  89. #define DEFAULT_LZLEN LRANGE
  90. unsigned short *rle, *elr, *lzlen, *lzpos;
  91. unsigned short *lzlen2, *lzpos2;
  92. int *length, inlen;
  93. unsigned char *indata, *mode, *newesc;
  94. unsigned short *backSkip;
  95. enum MODE {
  96. LITERAL = 0,
  97. LZ77 = 1,
  98. RLE = 2,
  99. DLZ = 3,
  100. MMARK = 4
  101. };
  102. int lzopt = 0;
  103. int maxGamma = 7;
  104. int reservedBytes = 2;
  105. int escBits = 2;
  106. int escMask = 0xc0;
  107. int extraLZPosBits = 0;
  108. int rleUsed = 31;
  109. unsigned char rleLen[256];
  110. int lenValue[256];
  111. int lrange, maxlzlen, maxrlelen;
  112. int gainedEscaped = 0;
  113. int gainedRle = 0, gainedSRle = 0, gainedLRle = 0;
  114. int gainedLz = 0, gainedRlecode = 0;
  115. int gainedDLz = 0, timesDLz = 0;
  116. int timesEscaped = 0, timesNormal = 0;
  117. int timesRle = 0, timesSRle = 0, timesLRle = 0;
  118. int timesLz = 0;
  119. int lenStat[8][4];
  120. unsigned char rleValues[32] = {1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
  121. 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
  122. int rleHist[256];
  123. #define OUT_SIZE 65536
  124. unsigned char outBuffer[OUT_SIZE];
  125. int outPointer = 0;
  126. int bitMask = 0x80;
  127. int quiet = 0;
  128. void TTPackInit(void) {
  129. int i;
  130. rleValues[0] = 1;
  131. for (i=1;i<32;i++) rleValues[i] = 0;
  132. for (i=0;i<256;i++) {
  133. rleLen[i] = 0;
  134. lenValue[i] = 0;
  135. rleHist[i] = 0;
  136. }
  137. for (i=0;i<OUT_SIZE;i++) outBuffer[i] = 0;
  138. lrange = 0, maxlzlen = 0, maxrlelen = 0;
  139. gainedEscaped = 0;
  140. gainedRle = 0, gainedSRle = 0, gainedLRle = 0;
  141. gainedLz = 0, gainedRlecode = 0;
  142. gainedDLz = 0, timesDLz = 0;
  143. timesEscaped = 0, timesNormal = 0;
  144. timesRle = 0, timesSRle = 0, timesLRle = 0;
  145. timesLz = 0;
  146. lrange = 0;
  147. maxlzlen = 0;
  148. maxrlelen = 0;
  149. outPointer = 0;
  150. bitMask = 0x80;
  151. lzopt = 0;
  152. maxGamma = 7;
  153. reservedBytes = 2;
  154. escBits = 2;
  155. escMask = 0xc0;
  156. extraLZPosBits = 0;
  157. rleUsed = 31;
  158. rle = NULL;
  159. elr = NULL;
  160. lzlen = NULL;
  161. lzpos = NULL;
  162. lzlen2 = NULL;
  163. lzpos2 = NULL;
  164. length = NULL;
  165. inlen = 0;
  166. indata = NULL;
  167. mode = NULL;
  168. newesc = NULL;
  169. backSkip = NULL;
  170. }
  171. //=============================================================================
  172. // the packing code
  173. //=============================================================================
  174. int SavePack(int flags,int type, unsigned char *data, int size, char *target,
  175. int start, int escape, unsigned char *rleValues,
  176. int endAddr, int extraLZPosBits,int memStart, int memEnd)
  177. {
  178. FILE *fp = NULL;
  179. int i;
  180. if (!data) return 10;
  181. if (!target) fp = stdout;
  182. if ((type & FIXF_MACHMASK) == 0) {
  183. /* Save without decompressor */
  184. if (fp || (fp = fopen(target, "wb"))) {
  185. PackedHeader cth;
  186. RLEEntries re;
  187. cth.origsize_lo = inlen & 0xff;
  188. cth.origsize_hi = (inlen >> 8);
  189. cth.magic1 = MAGIC_CHAR1;
  190. cth.magic2 = MAGIC_CHAR2;
  191. cth.compsize_lo = (size + rleUsed + sizeof(PackedHeader)) & 0xff;
  192. cth.compsize_hi = (size + rleUsed + sizeof(PackedHeader)) >> 8;
  193. cth.esc1 = (escape >> (8-escBits));
  194. cth.notused3 = 0; // just to make sure it has a defined value
  195. cth.notused4 = 0; // just to make sure it has a defined value
  196. cth.esc2 = escBits;
  197. cth.gamma1 = maxGamma + 1;
  198. cth.gamma2 = (1 << maxGamma);
  199. cth.extralz = extraLZPosBits;
  200. cth.notused1 = 0; // just to make sure it has a defined value
  201. cth.notused2 = 0; // just to make sure it has a defined value
  202. cth.rleentries = rleUsed;
  203. for(i=0; i<rleUsed; i++) re.value[i] = rleValues[i+1];
  204. if (flags & F_TEXTOUTPUT) {
  205. unsigned int loop;
  206. unsigned int written=0;
  207. for (i=0;i<sizeof(PackedHeader);i++,written++) {
  208. fprintf(fp,"0x%02x,",*(((unsigned char*)&cth)+i));
  209. if ((!(written % DEFAULT_ITEMS_PER_LINE)) && written) fputc('\n',fp);
  210. }
  211. for (i=0;i<cth.rleentries;i++,written++) {
  212. fprintf(fp,"0x%02x,",re.value[i]);
  213. if (!(written % DEFAULT_ITEMS_PER_LINE)) fputc('\n',fp);
  214. }
  215. for (loop=0;loop < size;loop++,written++) {
  216. if (loop < size - 1) fprintf(fp,"0x%02x,",data[loop]);
  217. else fprintf(fp,"0x%02x",data[loop]);
  218. if (!(written % DEFAULT_ITEMS_PER_LINE)) fputc('\n',fp);
  219. }
  220. }
  221. else {
  222. fwrite(&cth, 1, sizeof(PackedHeader), fp); // write header
  223. fwrite(&re, 1, cth.rleentries, fp); // write rle values
  224. fwrite(data, size, 1, fp); // write compressed data
  225. if(fp != stdout) fclose(fp);
  226. }
  227. return 0;
  228. }
  229. fprintf(stderr, "ERROR: Could not open %s for writing\n", target);
  230. return 10;
  231. }
  232. fprintf(stderr, "FATAL: invalid type!!\n");
  233. return 10;
  234. }
  235. //=============================================================================
  236. //
  237. //=============================================================================
  238. void FlushBits(void) {
  239. if (bitMask != 0x80) outPointer++;
  240. }
  241. //=============================================================================
  242. //
  243. //=============================================================================
  244. void PutBit(int bit) {
  245. if (bit && outPointer < OUT_SIZE) outBuffer[outPointer] |= bitMask;
  246. bitMask >>= 1;
  247. if (!bitMask) {
  248. bitMask = 0x80;
  249. outPointer++;
  250. }
  251. }
  252. //=============================================================================
  253. //
  254. //=============================================================================
  255. void PutValue(int value) {
  256. int bits = 0, count = 0;
  257. while (value>1) {
  258. bits = (bits<<1) | (value & 1); /* is reversed compared to value */
  259. value >>= 1;
  260. count++;
  261. PutBit(1);
  262. }
  263. if (count<maxGamma) PutBit(0);
  264. while (count--) {
  265. PutBit((bits & 1)); /* output is reversed again -> same as value */
  266. bits >>= 1;
  267. }
  268. }
  269. //--------------------------------------------
  270. // why not initializing value lenValue[0] ????
  271. //--------------------------------------------
  272. //=============================================================================
  273. //
  274. //=============================================================================
  275. void InitValueLen() {
  276. int i;
  277. // could be heavily optimized, but isn't necessary
  278. for (i=1; i<256; i++) {
  279. int count = 0;
  280. if (i<2) count = 0; /* 1 */
  281. else if (i<4) count = 1; /* 2-3 */
  282. else if (i<8) count = 2; /* 4-7 */
  283. else if (i<16) count = 3; /* 8-15 */
  284. else if (i<32) count = 4; /* 16-31 */
  285. else if (i<64) count = 5; /* 32-63 */
  286. else if (i<128) count = 6; /* 64-127 */
  287. else if (i<256) count = 7; /* 128-255 */
  288. lenValue[i] = 2*count;
  289. if (count<maxGamma) lenValue[i]++;
  290. }
  291. }
  292. #define LenValue(a) (lenValue[a])
  293. //=============================================================================
  294. //
  295. //=============================================================================
  296. void PutNBits(int byte, int bits) {
  297. while (bits--)
  298. PutBit((byte & (1<<bits)));
  299. }
  300. //=============================================================================
  301. //
  302. //=============================================================================
  303. int OutputNormal(int *esc, unsigned char *data, int newesc) {
  304. timesNormal++;
  305. if ((data[0] & escMask) == *esc) {
  306. PutNBits((*esc>>(8-escBits)), escBits); /* escBits>=0 */
  307. PutBit(0);
  308. PutBit(1);
  309. PutBit(0);
  310. *esc = newesc;
  311. PutNBits((*esc>>(8-escBits)), escBits); /* escBits>=0 */
  312. PutNBits(data[0], 8-escBits);
  313. gainedEscaped += escBits + 3;
  314. timesEscaped++;
  315. return 1;
  316. }
  317. PutNBits(data[0], 8);
  318. return 0;
  319. }
  320. //=============================================================================
  321. //
  322. //=============================================================================
  323. void OutputEof(int *esc) {
  324. /* EOF marker */
  325. PutNBits((*esc>>(8-escBits)), escBits); /* escBits>=0 */
  326. PutValue(3); /* >2 */
  327. PutValue((2<<maxGamma)-1); /* Maximum value */
  328. FlushBits();
  329. }
  330. //=============================================================================
  331. //
  332. //=============================================================================
  333. void PutRleByte(int data) {
  334. int index;
  335. for (index = 1; index < 32; index++) {
  336. if (data == rleValues[index]) {
  337. if (index==1) lenStat[0][3]++;
  338. else if (index<=3) lenStat[1][3]++;
  339. else if (index<=7) lenStat[2][3]++;
  340. else if (index<=15) lenStat[3][3]++;
  341. else if (index<=31) lenStat[4][3]++;
  342. gainedRlecode += 8 - LenValue(index);
  343. PutValue(index);
  344. return;
  345. }
  346. }
  347. PutValue(32 + (data>>3));
  348. gainedRlecode -= LenValue(32+(data>>3)) + 3;
  349. PutNBits(data, 3);
  350. lenStat[5][3]++;
  351. }
  352. //=============================================================================
  353. //
  354. //=============================================================================
  355. void InitRleLen() {
  356. int i;
  357. for (i=0; i<256; i++) rleLen[i] = LenValue(32 + 0) + 3;
  358. for (i=1; i<32; i++) rleLen[rleValues[i]] = LenValue(i);
  359. }
  360. #define LenRleByte(d) (rleLen[d])
  361. //=============================================================================
  362. //
  363. //=============================================================================
  364. int LenRle(int len, int data) {
  365. int out = 0;
  366. do {
  367. if (len == 1) {
  368. out += escBits + 3 + 8;
  369. len = 0;
  370. }
  371. else if (len <= (1<<maxGamma)) {
  372. out += escBits + 3 + LenValue(len-1) + LenRleByte(data);
  373. len = 0;
  374. }
  375. else {
  376. int tmp = min(len, maxrlelen);
  377. out += escBits + 3 + maxGamma + 8 +
  378. LenValue(((tmp-1)>>8)+1) + LenRleByte(data);
  379. len -= tmp;
  380. }
  381. } while (len);
  382. return out;
  383. }
  384. //=============================================================================
  385. //
  386. //=============================================================================
  387. int OutputRle(int *esc, unsigned char *data, int rlelen) {
  388. int len = rlelen, tmp;
  389. while (len) {
  390. if (len >= 2 && len <= (1<<maxGamma)) {
  391. /* Short RLE */
  392. if (len==2) lenStat[0][2]++;
  393. else if (len<=4) lenStat[1][2]++;
  394. else if (len<=8) lenStat[2][2]++;
  395. else if (len<=16) lenStat[3][2]++;
  396. else if (len<=32) lenStat[4][2]++;
  397. else if (len<=64) lenStat[5][2]++;
  398. else if (len<=128) lenStat[6][2]++;
  399. else if (len<=256) lenStat[6][2]++;
  400. PutNBits((*esc>>(8-escBits)), escBits); /* escBits>=0 */
  401. PutBit(0);
  402. PutBit(1);
  403. PutBit(1);
  404. PutValue(len-1);
  405. PutRleByte(*data);
  406. tmp = 8*len -escBits -3 -LenValue(len-1) -LenRleByte(*data);
  407. gainedRle += tmp;
  408. gainedSRle += tmp;
  409. timesRle++;
  410. timesSRle++;
  411. return 0;
  412. }
  413. if (len<3) {
  414. while (len--)
  415. OutputNormal(esc, data, *esc);
  416. return 0;
  417. }
  418. if (len <= maxrlelen) {
  419. /* Run-length encoding */
  420. PutNBits((*esc>>(8-escBits)), escBits); /* escBits>=0 */
  421. PutBit(0);
  422. PutBit(1);
  423. PutBit(1);
  424. PutValue((1<<maxGamma) + (((len-1)&0xff)>>(8-maxGamma)));
  425. PutNBits((len-1), 8-maxGamma);
  426. PutValue(((len-1)>>8) + 1);
  427. PutRleByte(*data);
  428. tmp = 8*len -escBits -3 -maxGamma -8 -LenValue(((len-1)>>8)+1)
  429. -LenRleByte(*data);
  430. gainedRle += tmp;
  431. gainedLRle += tmp;
  432. timesRle++;
  433. timesLRle++;
  434. return 0;
  435. }
  436. /* Run-length encoding */
  437. PutNBits((*esc>>(8-escBits)), escBits); /* escBits>=0 */
  438. PutBit(0);
  439. PutBit(1);
  440. PutBit(1);
  441. PutValue((1<<maxGamma) + (((maxrlelen-1)&0xff)>>(8-maxGamma)));
  442. PutNBits((maxrlelen-1) & 0xff, 8-maxGamma);
  443. PutValue(((maxrlelen-1)>>8)+1);
  444. PutRleByte(*data);
  445. tmp = 8*maxrlelen -escBits -3 -maxGamma -8
  446. -LenValue(((maxrlelen-1)>>8)+1) -LenRleByte(*data);
  447. gainedRle += tmp;
  448. gainedLRle += tmp;
  449. timesRle++;
  450. timesLRle++;
  451. len -= maxrlelen;
  452. data += maxrlelen;
  453. }
  454. return 0;
  455. }
  456. //=============================================================================
  457. //
  458. //=============================================================================
  459. int LenLz(int lzlen, int lzpos) {
  460. if (lzlen==2) {
  461. if (lzpos <= 256) return escBits + 2 + 8;
  462. else return 100000;
  463. }
  464. return escBits + 8 + extraLZPosBits +
  465. LenValue(((lzpos-1)>>(8+extraLZPosBits))+1) +
  466. LenValue(lzlen-1);
  467. }
  468. //=============================================================================
  469. //
  470. //=============================================================================
  471. int OutputLz(int *esc, int lzlen, int lzpos, char *data, int curpos) {
  472. if (lzlen==2) lenStat[0][1]++;
  473. else if (lzlen<=4) lenStat[1][1]++;
  474. else if (lzlen<=8) lenStat[2][1]++;
  475. else if (lzlen<=16) lenStat[3][1]++;
  476. else if (lzlen<=32) lenStat[4][1]++;
  477. else if (lzlen<=64) lenStat[5][1]++;
  478. else if (lzlen<=128) lenStat[6][1]++;
  479. else if (lzlen<=256) lenStat[7][1]++;
  480. if (lzlen >= 2 && lzlen <= maxlzlen) {
  481. int tmp;
  482. PutNBits((*esc>>(8-escBits)), escBits); /* escBits>=0 */
  483. tmp = ((lzpos-1)>>(8+extraLZPosBits))+2;
  484. if (tmp==2) lenStat[0][0]++;
  485. else if (tmp<=4) lenStat[1][0]++;
  486. else if (tmp<=8) lenStat[2][0]++;
  487. else if (tmp<=16) lenStat[3][0]++;
  488. else if (tmp<=32) lenStat[4][0]++;
  489. else if (tmp<=64) lenStat[5][0]++;
  490. else if (tmp<=128) lenStat[6][0]++;
  491. else if (tmp<=256) lenStat[6][0]++;
  492. if (lzlen==2) {
  493. PutValue(lzlen-1);
  494. PutBit(0);
  495. if (lzpos > 256) fprintf(stderr,"ERROR at %d: lzpos too long (%d) for lzlen==2\n",curpos, lzpos);
  496. }
  497. else {
  498. PutValue(lzlen-1);
  499. PutValue( ((lzpos-1) >> (8+extraLZPosBits)) +1);
  500. PutNBits( ((lzpos-1) >> 8), extraLZPosBits);
  501. }
  502. PutNBits(((lzpos-1) & 0xff) ^ 0xff, 8);
  503. gainedLz += 8*lzlen -LenLz(lzlen, lzpos);
  504. timesLz++;
  505. return 3;
  506. }
  507. fprintf(stderr, "ERROR: lzlen too short/long (%d)\n", lzlen);
  508. return lzlen;
  509. }
  510. /* Non-recursive version */
  511. /* NOTE! IMPORTANT! the "length" array length must be inlen+1 */
  512. //=============================================================================
  513. //
  514. //=============================================================================
  515. int OptimizeLength(int optimize) {
  516. int i;
  517. length[inlen] = 0; /* one off the end, our 'target' */
  518. for (i=inlen-1; i>=0; i--) {
  519. int r1 = 8 + length[i+1], r2, r3;
  520. if (!lzlen[i] && !rle[i] && (!lzlen2 || !lzlen2[i])) {
  521. length[i] = r1;
  522. mode[i] = LITERAL;
  523. continue;
  524. }
  525. /* If rle>maxlzlen, skip to the start of the rle-maxlzlen.. */
  526. if (rle[i] > maxlzlen && elr[i] > 1) {
  527. int z = elr[i];
  528. i -= elr[i];
  529. r2 = LenRle(rle[i], indata[i]) + length[i+ rle[i]];
  530. if (optimize) {
  531. int ii, mini = rle[i], minv = r2;
  532. int bot = rle[i] - (1<<maxGamma);
  533. if (bot < 2)
  534. bot = 2;
  535. for (ii=mini-1; ii>=bot; ii--) {
  536. int v = LenRle(ii, indata[i]) + length[i + ii];
  537. if (v < minv) {
  538. minv = v;
  539. mini = ii;
  540. }
  541. }
  542. if (minv != r2) {
  543. lzopt += r2 - minv;
  544. rle[i] = mini;
  545. r2 = minv;
  546. }
  547. }
  548. length[i] = r2;
  549. mode[i] = RLE;
  550. for (; z>=0; z--) {
  551. length[i+z] = r2;
  552. mode[i+z] = RLE;
  553. }
  554. continue;
  555. }
  556. r3 = r2 = r1 + 1000; /* r3 >= r2 > r1 */
  557. if (rle[i]) {
  558. r2 = LenRle(rle[i], indata[i]) + length[i+ rle[i]];
  559. if (optimize) {
  560. int ii, mini = rle[i], minv = r2;
  561. /* Check only the original length and all shorter
  562. lengths that are power of two.
  563. Does not really miss many 'minimums' this way,
  564. at least not globally..
  565. Makes the assumption that the Elias Gamma Code is
  566. used, i.e. values of the form 2^n are 'optimal' */
  567. ii = 2;
  568. while (rle[i] > ii) {
  569. int v = LenRle(ii, indata[i]) + length[i + ii];
  570. if (v < minv) {
  571. minv = v;
  572. mini = ii;
  573. }
  574. ii <<= 1;
  575. }
  576. if (minv != r2) {
  577. lzopt += r2 - minv;
  578. rle[i] = mini;
  579. r2 = minv;
  580. }
  581. }
  582. }
  583. if (lzlen[i]) {
  584. r3 = LenLz(lzlen[i], lzpos[i]) + length[i + lzlen[i]];
  585. if (optimize && lzlen[i]>2) {
  586. int ii, mini = lzlen[i], minv = r3;
  587. int topLen = LenLz(lzlen[i], lzpos[i])
  588. - LenValue(lzlen[i]-1);
  589. /* Check only the original length and all shorter
  590. lengths that are power of two.
  591. Does not really miss many 'minimums' this way,
  592. at least not globally..
  593. Makes the assumption that the Elias Gamma Code is
  594. used, i.e. values of the form 2^n are 'optimal' */
  595. ii = 4;
  596. while (lzlen[i] > ii) {
  597. int v = topLen + LenValue(ii-1) + length[i + ii];
  598. if (v < minv) {
  599. minv = v;
  600. mini = ii;
  601. }
  602. ii <<= 1;
  603. }
  604. /*
  605. Note:
  606. 2-byte optimization checks are no longer done
  607. with the rest, because the equation gives too long
  608. code lengths for 2-byte matches if extraLzPosBits>0.
  609. */
  610. /* Two-byte rescan/check */
  611. if (backSkip[i] && backSkip[i] <= 256) {
  612. /* There are previous occurrances (near enough) */
  613. int v = LenLz(2, (int)backSkip[i]) + length[i + 2];
  614. if (v < minv) {
  615. minv = v;
  616. mini = 2;
  617. lzlen[i] = mini;
  618. r3 = minv;
  619. lzpos[i] = (int)backSkip[i];
  620. }
  621. }
  622. if (minv != r3 && minv < r2) {
  623. lzopt += r3 - minv;
  624. lzlen[i] = mini;
  625. r3 = minv;
  626. }
  627. }
  628. }
  629. if (r2 <= r1) {
  630. if (r2 <= r3) {
  631. length[i] = r2;
  632. mode[i] = RLE;
  633. }
  634. else {
  635. length[i] = r3;
  636. mode[i] = LZ77;
  637. }
  638. }
  639. else {
  640. if (r3 <= r1) {
  641. length[i] = r3;
  642. mode[i] = LZ77;
  643. }
  644. else {
  645. length[i] = r1;
  646. mode[i] = LITERAL;
  647. }
  648. }
  649. if (lzlen2 && lzlen2[i] > 3) {
  650. r3 = escBits + 2*maxGamma + 16 + LenValue(lzlen2[i]-1) + length[i + lzlen2[i]];
  651. //r3 = LenDLz(lzlen2[i], lzpos2[i]) + length[i + lzlen2[i]];
  652. if (r3 < length[i]) {
  653. length[i] = r3;
  654. mode[i] = DLZ;
  655. }
  656. }
  657. }
  658. return length[0];
  659. }
  660. /*
  661. The algorithm in the OptimizeEscape() works as follows:
  662. 1) Only unpacked bytes are processed, they are marked
  663. with MMARK. We proceed from the end to the beginning.
  664. Variable A (old/new length) is updated.
  665. 2) At each unpacked byte, one and only one possible
  666. escape matches. A new escape code must be selected
  667. for this case. The optimal selection is the one which
  668. provides the shortest number of escapes to the end
  669. of the file,
  670. i.e. A[esc] = 1+min(A[0], A[1], .. A[states-1]).
  671. For other states A[esc] = A[esc];
  672. If we change escape in this byte, the new escape is
  673. the one with the smallest value in A.
  674. 3) The starting escape is selected from the possibilities
  675. and mode 0 is restored to all mode 3 locations.
  676. */
  677. //=============================================================================
  678. //
  679. //=============================================================================
  680. int OptimizeEscape(int *startEscape, int *nonNormal) {
  681. int i, j, states = (1<<escBits);
  682. long minp = 0, minv = 0, other = 0;
  683. long a[256]; /* needs int/long */
  684. long b[256]; /* Remembers the # of escaped for each */
  685. int esc8 = 8-escBits;
  686. for (i=0; i<256; i++) b[i] = a[i] = -1;
  687. if (states>256) {
  688. fprintf(stderr, "Escape optimize: only 256 states (%d)!\n",states);
  689. return 0;
  690. }
  691. /* Mark those bytes that are actually outputted */
  692. for (i=0; i<inlen; ) {
  693. switch (mode[i]) {
  694. case DLZ:
  695. other++;
  696. i += lzlen2[i];
  697. break;
  698. case LZ77:
  699. other++;
  700. i += lzlen[i];
  701. break;
  702. case RLE:
  703. other++;
  704. i += rle[i];
  705. break;
  706. /*case LITERAL:*/
  707. default:
  708. mode[i++] = MMARK; /* mark it used so we can identify it */
  709. break;
  710. }
  711. }
  712. for (i=inlen-1; i>=0; i--) {
  713. /* Using a table to skip non-normal bytes does not help.. */
  714. if (mode[i] == MMARK) {
  715. int k = (indata[i] >> esc8);
  716. /* Change the tag values back to normal */
  717. mode[i] = LITERAL;
  718. /*
  719. k are the matching bytes,
  720. minv is the minimum value,
  721. minp is the minimum index
  722. */
  723. newesc[i] = (minp << esc8);
  724. a[k] = minv + 1;
  725. b[k] = b[minp] + 1;
  726. if (k==minp) {
  727. /* Minimum changed -> need to find a new minimum */
  728. /* a[k] may still be the minimum */
  729. minv++;
  730. for (k=states-1; k>=0; k--) {
  731. if (a[k] < minv) {
  732. minv = a[k];
  733. minp = k;
  734. /*
  735. There may be others, but the first one that
  736. is smaller than the old minimum is equal to
  737. any other new minimum.
  738. */
  739. break;
  740. }
  741. }
  742. }
  743. }
  744. }
  745. /* Select the best value for the initial escape */
  746. if (startEscape) {
  747. i = inlen; /* make it big enough */
  748. for (j=states-1; j>=0; j--) {
  749. if (a[j] <= i) {
  750. *startEscape = (j << esc8);
  751. i = a[j];
  752. }
  753. }
  754. }
  755. if (nonNormal)
  756. *nonNormal = other;
  757. return b[startEscape ? (*startEscape>>esc8) : 0];
  758. }
  759. //=============================================================================
  760. // Initialize the RLE byte code table according to all RLE's found so far O(n)
  761. //=============================================================================
  762. void InitRle(int flags) {
  763. int p, mr, mv, i;
  764. for (i=1; i<32; i++) {
  765. mr = -1;
  766. mv = 0;
  767. for (p=0; p<256; p++) {
  768. if (rleHist[p] > mv) {
  769. mv = rleHist[p];
  770. mr = p;
  771. }
  772. }
  773. if (mv>0) {
  774. rleValues[i] = mr;
  775. rleHist[mr] = -1;
  776. } else
  777. break;
  778. }
  779. InitRleLen();
  780. }
  781. //=============================================================================
  782. // Initialize the RLE byte code table according to RLE's actually used O(n)
  783. //=============================================================================
  784. void OptimizeRle(int flags) {
  785. int p, mr, mv, i;
  786. if ((flags & F_NORLE)) {
  787. rleUsed = 0;
  788. return;
  789. }
  790. if (flags & F_STATS) fprintf(stderr, "RLE Byte Code Re-Tune, RLE Ranks:\n");
  791. for (p=0; p<256; p++) rleHist[p] = 0;
  792. for (p=0; p<inlen; ) {
  793. switch (mode[p]) {
  794. case DLZ:
  795. p += lzlen2[p];
  796. break;
  797. case LZ77:
  798. p += lzlen[p];
  799. break;
  800. case RLE:
  801. rleHist[indata[p]]++;
  802. p += rle[p];
  803. break;
  804. default:
  805. p++;
  806. break;
  807. }
  808. }
  809. for (i=1; i<32; i++) {
  810. mr = -1;
  811. mv = 0;
  812. for (p=0; p<256; p++) {
  813. if (rleHist[p] > mv) {
  814. mv = rleHist[p];
  815. mr = p;
  816. }
  817. }
  818. if (mv>0) {
  819. rleValues[i] = mr;
  820. if (flags & F_STATS) {
  821. fprintf(stderr, " %2d.0x%02x %-3d ", i, mr, mv);
  822. if (!((i - 1) % 6)) fprintf(stderr, "\n");
  823. }
  824. rleHist[mr] = -1;
  825. }
  826. else {
  827. break;
  828. }
  829. }
  830. rleUsed = i-1;
  831. if (flags & F_STATS)
  832. if (((i - 1) % 6)!=1) fprintf(stderr, "\n");
  833. InitRleLen();
  834. }
  835. //=============================================================================
  836. //
  837. //=============================================================================
  838. int PackLz77(int lzsz, int flags, int *startEscape,int endAddr, int memEnd, int type)
  839. {
  840. int i, j, outlen, p, headerSize;
  841. int escape;
  842. unsigned char *hashValue;
  843. unsigned char *a;
  844. int k;
  845. unsigned short *lastPair;
  846. unsigned short err_occured = 0;
  847. int rescan = 0;
  848. if (lzsz < 0 || lzsz > lrange) {
  849. fprintf(stderr, "LZ range must be from 0 to %d (was %d). Set to %d.\n",
  850. lrange, lzsz, lrange);
  851. lzsz = lrange;
  852. }
  853. if (lzsz > 65535) {
  854. fprintf(stderr,
  855. "LZ range must be from 0 to 65535 (was %d). Set to 65535.\n",
  856. lzsz);
  857. lzsz = 65535;
  858. }
  859. if (!lzsz) fprintf(stderr, "Warning: zero LZ range. Only RLE packing used.\n");
  860. InitRleLen();
  861. length = (int *)calloc(sizeof(int), inlen + 1);
  862. mode = (unsigned char *)calloc(sizeof(unsigned char), inlen);
  863. rle = (unsigned short *)calloc(sizeof(unsigned short), inlen);
  864. elr = (unsigned short *)calloc(sizeof(unsigned short), inlen);
  865. lzlen = (unsigned short *)calloc(sizeof(unsigned short), inlen);
  866. lzpos = (unsigned short *)calloc(sizeof(unsigned short), inlen);
  867. if ((type & FIXF_DLZ)) {
  868. lzlen2 = (unsigned short *)calloc(sizeof(unsigned short), inlen);
  869. lzpos2 = (unsigned short *)calloc(sizeof(unsigned short), inlen);
  870. }
  871. else {
  872. lzlen2 = lzpos2 = NULL;
  873. }
  874. newesc = (unsigned char *)calloc(sizeof(unsigned char), inlen);
  875. backSkip = (unsigned short *)calloc(sizeof(unsigned short), inlen);
  876. hashValue = (unsigned char *)malloc(inlen);
  877. lastPair = (unsigned short *)calloc(sizeof(unsigned short), 256*256);
  878. /* error checking */
  879. if (!length || !mode || !rle || !elr || !lzlen || !lzpos || !newesc ||
  880. !lastPair || !backSkip
  881. || ((type & FIXF_DLZ) && (!lzlen2 || !lzpos2))
  882. || !hashValue)
  883. {
  884. fprintf(stderr, "ERROR: Memory allocation failed!\n");
  885. err_occured = 1;
  886. goto errorexit;
  887. }
  888. i = 0;
  889. j = 0;
  890. a = indata + inlen;
  891. for (p=inlen-1; p>=0; p--) {
  892. k = j;
  893. j = i;
  894. i = *--a; /* Only one read per position */
  895. hashValue[p] = i*3 + j*5 + k*7; /* 7.95 % */
  896. }
  897. /* Detect all RLE and LZ77 jump possibilities */
  898. for (p=0; p<inlen; p++) {
  899. if (flags & F_VERBOSE) {
  900. if (!(p & 2047)) {
  901. fprintf(stderr, "\r%d ", p);
  902. fflush(stderr); /* for SAS/C */
  903. }
  904. }
  905. /* check run-length code - must be done, LZ77 search needs it! */
  906. if (rle[p] <= 0) {
  907. unsigned char *a = indata + p;
  908. int val = *a++; /* if this were uchar, it would go to stack..*/
  909. int top = inlen - p;
  910. int rlelen = 1;
  911. /* Loop for the whole RLE */
  912. while (rlelen<top && *a++ == (unsigned char)val) rlelen++;
  913. if (rlelen>=2) {
  914. rleHist[indata[p]]++;
  915. for (i=rlelen-1; i>=0; i--) {
  916. rle[p+i] = rlelen-i;
  917. elr[p+i] = i; /* For RLE backward skipping */
  918. }
  919. }
  920. }
  921. /* check LZ77 code */
  922. if (p+rle[p]+1<inlen) {
  923. int bot = p - lzsz, maxval, maxpos, rlep = rle[p];
  924. unsigned char hashCompare = hashValue[p];
  925. /*
  926. There's always 1 equal byte, although it may
  927. not be marked as RLE.
  928. */
  929. if (rlep <= 0)
  930. rlep = 1;
  931. if (bot < 0)
  932. bot = 0;
  933. bot += (rlep-1);
  934. /*
  935. First get the shortest possible match (if any).
  936. If there is no 2-byte match, don't look further,
  937. because there can't be a longer match.
  938. */
  939. i = (int)lastPair[ (indata[p]<<8) | indata[p+1] ] -1;
  940. if (i>=0 && i>=bot) {
  941. /* Got a 2-byte match at least */
  942. maxval = 2;
  943. maxpos = p-i;
  944. /*
  945. A..AB rlep # of A's, B is something else..
  946. Search for bytes that are in p + (rlep-1), i.e.
  947. the last rle byte ('A') and the non-matching one
  948. ('B'). When found, check if the rle in the compare
  949. position (i) is long enough (i.e. the same number
  950. of A's at p and i-rlep+1).
  951. There are dramatically less matches for AB than for
  952. AA, so we get a huge speedup with this approach.
  953. We are still guaranteed to find the most recent
  954. longest match there is.
  955. */
  956. i = (int)lastPair[(indata[p+(rlep-1)]<<8) | indata[p+rlep]] -1;
  957. while (i>=bot /* && i>=rlep-1 */) { /* bot>=rlep-1, i>=bot ==> i>=rlep-1 */
  958. /* Equal number of A's ? */
  959. if (!(rlep-1) || rle[i-(rlep-1)]==rlep) { /* 'head' matches */
  960. /* rlep==1 ==> (rlep-1)==0 */
  961. /* ivanova.run: 443517 rlep==1,
  962. 709846 rle[i+1-rlep]==rlep */
  963. /*
  964. Check the hash values corresponding to the last
  965. two bytes of the currently longest match and
  966. the first new matching(?) byte. If the hash
  967. values don't match, don't bother to check the
  968. data itself.
  969. */
  970. if (
  971. hashValue[i+maxval-rlep-1] == hashCompare
  972. ) {
  973. unsigned char *a = indata + i+2; /* match */
  974. unsigned char *b = indata + p+rlep-1+2;/* curpos */
  975. int topindex = inlen-(p+rlep-1);
  976. /* the 2 first bytes ARE the same.. */
  977. j = 2;
  978. while (j < topindex && *a++==*b++)
  979. j++;
  980. if (j + rlep-1 > maxval) {
  981. int tmplen = j+rlep-1, tmppos = p-i+rlep-1;
  982. if (tmplen > maxlzlen)
  983. tmplen = maxlzlen;
  984. /* Accept only versions that really are shorter */
  985. if (tmplen*8 - LenLz(tmplen, tmppos) >
  986. maxval*8 - LenLz(maxval, maxpos)) {
  987. maxval = tmplen;
  988. maxpos = tmppos;
  989. hashCompare = hashValue[p+maxval-2];
  990. }
  991. if (maxval == maxlzlen)
  992. break;
  993. }
  994. }
  995. }
  996. if (!backSkip[i])
  997. break; /* No previous occurrances (near enough) */
  998. i -= (int)backSkip[i];
  999. }
  1000. /*
  1001. If there is 'A' in the previous position also,
  1002. RLE-like LZ77 is possible, although rarely
  1003. shorter than real RLE.
  1004. */
  1005. if (p && rle[p-1] > maxval) {
  1006. maxval = rle[p-1] - 1;
  1007. maxpos = 1;
  1008. }
  1009. /*
  1010. Last, try to find as long as possible match
  1011. for the RLE part only.
  1012. */
  1013. if (maxval < maxlzlen && rlep > maxval) {
  1014. bot = p - lzsz;
  1015. if (bot < 0)
  1016. bot = 0;
  1017. /* Note: indata[p] == indata[p+1] */
  1018. i = (int)lastPair[indata[p]*257] -1;
  1019. while (/* i>= rlep-2 &&*/ i>=bot) {
  1020. if (elr[i] + 2 > maxval) {
  1021. maxval = min(elr[i] + 2, rlep);
  1022. maxpos = p - i + (maxval-2);
  1023. if(maxval == rlep)
  1024. break; /* Got enough */
  1025. }
  1026. i -= elr[i];
  1027. if (!backSkip[i])
  1028. break; /* No previous occurrances (near enough) */
  1029. i -= (int)backSkip[i];
  1030. }
  1031. }
  1032. if (p+maxval > inlen) {
  1033. fprintf(stderr,"Error @ %d, lzlen %d, pos %d - exceeds inlen\n",p, maxval, maxpos);
  1034. maxval = inlen - p;
  1035. }
  1036. if (maxpos<=256 || maxval > 2) {
  1037. if (maxpos < 0) fprintf(stderr, "Error @ %d, lzlen %d, pos %d\n",p, maxval, maxpos);
  1038. lzlen[p] = (maxval<maxlzlen)?maxval:maxlzlen;
  1039. lzpos[p] = maxpos;
  1040. }
  1041. }
  1042. }
  1043. /* check LZ77 code again, ROT1..255 */
  1044. if ((type & FIXF_DLZ) && p+rle[p]+1<inlen) {
  1045. int rot;
  1046. for (rot = 1; rot < 255; rot++) {
  1047. int bot = p - /*lzsz*/256, maxval, maxpos, rlep = rle[p];
  1048. unsigned char valueCompare = (indata[p+2] + rot) & 0xff;
  1049. if (rlep <= 0) rlep = 1;
  1050. if (bot < 0) bot = 0;
  1051. bot += (rlep-1);
  1052. i = (int)lastPair[ (((indata[p] + rot) & 0xff)<<8) |
  1053. ((indata[p+1] + rot) & 0xff) ] -1;
  1054. if (i>=0 && i>=bot) {
  1055. maxval = 2;
  1056. maxpos = p-i;
  1057. /*
  1058. A..AB rlep # of A's, B is something else..
  1059. Search for bytes that are in p + (rlep-1), i.e.
  1060. the last rle byte ('A') and the non-matching one
  1061. ('B'). When found, check if the rle in the compare
  1062. position (i) is long enough (i.e. the same number
  1063. of A's at p and i-rlep+1).
  1064. There are dramatically less matches for AB than for
  1065. AA, so we get a huge speedup with this approach.
  1066. We are still guaranteed to find the most recent
  1067. longest match there is.
  1068. */
  1069. i = (int)lastPair[(((indata[p+(rlep-1)] + rot) & 0xff)<<8) |
  1070. ((indata[p+rlep] + rot) & 0xff)] -1;
  1071. while (i>=bot /* && i>=rlep-1 */) { /* bot>=rlep-1, i>=bot ==> i>=rlep-1 */
  1072. /* Equal number of A's ? */
  1073. if (!(rlep-1) || rle[i-(rlep-1)]==rlep) { /* 'head' matches */
  1074. /* rlep==1 ==> (rlep-1)==0 */
  1075. /* ivanova.run: 443517 rlep==1,
  1076. 709846 rle[i+1-rlep]==rlep */
  1077. /*
  1078. Check the hash values corresponding to the last
  1079. two bytes of the currently longest match and
  1080. the first new matching(?) byte. If the hash
  1081. values don't match, don't bother to check the
  1082. data itself.
  1083. */
  1084. if (indata[i+maxval-rlep+1] == valueCompare) {
  1085. unsigned char *a = indata + i+2; /* match */
  1086. unsigned char *b = indata + p+rlep-1+2;/* curpos */
  1087. int topindex = inlen-(p+rlep-1);
  1088. /* the 2 first bytes ARE the same.. */
  1089. j = 2;
  1090. while (j < topindex && *a++==((*b++ + rot) & 0xff))
  1091. j++;
  1092. if (j + rlep-1 > maxval) {
  1093. int tmplen = j+rlep-1, tmppos = p-i+rlep-1;
  1094. if (tmplen > maxlzlen)
  1095. tmplen = maxlzlen;
  1096. /* Accept only versions that really are shorter */
  1097. if (tmplen*8 - LenLz(tmplen, tmppos) >
  1098. maxval*8 - LenLz(maxval, maxpos)) {
  1099. maxval = tmplen;
  1100. maxpos = tmppos;
  1101. valueCompare = (indata[p+maxval] + rot) & 0xff;
  1102. }
  1103. if (maxval == maxlzlen)
  1104. break;
  1105. }
  1106. }
  1107. }
  1108. if (!backSkip[i])
  1109. break; /* No previous occurrances (near enough) */
  1110. i -= (int)backSkip[i];
  1111. }
  1112. if (p+maxval > inlen) {
  1113. fprintf(stderr,"Error @ %d, lzlen %d, pos %d - exceeds inlen\n",p, maxval, maxpos);
  1114. maxval = inlen - p;
  1115. }
  1116. if (maxval > 3 && maxpos <= 256 &&
  1117. (maxval > lzlen2[p] ||
  1118. (maxval == lzlen2[p] && maxpos < lzpos2[p]))) {
  1119. if (maxpos < 0)
  1120. fprintf(stderr, "Error @ %d, lzlen %d, pos %d\n",p, maxval, maxpos);
  1121. lzlen2[p] = (maxval<maxlzlen)?maxval:maxlzlen;
  1122. lzpos2[p] = maxpos;
  1123. }
  1124. }
  1125. }
  1126. if (lzlen2[p] <= lzlen[p] || lzlen2[p] <= rle[p]) {
  1127. lzlen2[p] = lzpos2[p] = 0;
  1128. }
  1129. }
  1130. /* Update the two-byte history ('hash table') &
  1131. backSkip ('linked list') */
  1132. if (p+1<inlen) {
  1133. int index = (indata[p]<<8) | indata[p+1];
  1134. int ptr = p - (lastPair[index]-1);
  1135. if (ptr > p || ptr > 0xffff)
  1136. ptr = 0;
  1137. backSkip[p] = ptr;
  1138. lastPair[index] = p+1;
  1139. }
  1140. }
  1141. if ((flags & F_NORLE)) {
  1142. for (p=1; p<inlen; p++) {
  1143. if (rle[p-1]-1 > lzlen[p]) {
  1144. lzlen[p] = (rle[p]<maxlzlen)?rle[p]:maxlzlen;
  1145. lzpos[p] = 1;
  1146. }
  1147. }
  1148. for (p=0; p<inlen; p++) {
  1149. rle[p] = 0;
  1150. }
  1151. }
  1152. if (flags & F_VERBOSE) {
  1153. fprintf(stderr, "\rChecked: %d \n", p);
  1154. fflush(stderr);
  1155. }
  1156. /* Initialize the RLE selections */
  1157. InitRle(flags);
  1158. /* Check the normal bytes / all ratio */
  1159. if ((flags & F_AUTO)) {
  1160. int mb, mv;
  1161. if (flags & F_VERBOSE) {
  1162. fprintf(stderr, "Selecting the number of escape bits.. ");
  1163. fflush(stderr);
  1164. }
  1165. /*
  1166. Absolute maximum number of escaped bytes with
  1167. the escape optimize is 2^-n, where n is the
  1168. number of escape bits used.
  1169. This worst case happens only on equal-
  1170. distributed normal bytes (01230123..).
  1171. This is why the typical values are so much smaller.
  1172. */
  1173. mb = 0;
  1174. mv = 8*OUT_SIZE;
  1175. for (escBits=1; escBits<9; escBits++) {
  1176. int escaped, other = 0, c;
  1177. escMask = (0xff00>>escBits) & 0xff;
  1178. /* Find the optimum path for selected escape bits (no optimize) */
  1179. OptimizeLength(0);
  1180. /* Optimize the escape selections for this path & escBits */
  1181. escaped = OptimizeEscape(&escape, &other);
  1182. /* Compare value: bits lost for escaping -- bits lost for prefix */
  1183. c = (escBits+3)*escaped + other*escBits;
  1184. if (flags & F_STATS) {
  1185. fprintf(stderr, " %d:%d", escBits, c);
  1186. fflush(stderr); /* for SAS/C */
  1187. }
  1188. if (c < mv) {
  1189. mb = escBits;
  1190. mv = c;
  1191. } else {
  1192. /* minimum found */
  1193. break;
  1194. }
  1195. if (escBits==4 && (flags & F_STATS)) fprintf(stderr, "\n");
  1196. }
  1197. if (mb==1) { /* Minimum was 1, check 0 */
  1198. int escaped;
  1199. escBits = 0;
  1200. escMask = 0;
  1201. /* Find the optimum path for selected escape bits (no optimize) */
  1202. OptimizeLength(0);
  1203. /* Optimize the escape selections for this path & escBits */
  1204. escaped = OptimizeEscape(&escape, NULL);
  1205. if ((flags & F_STATS)) {
  1206. fprintf(stderr, " %d:%d", escBits, 3*escaped);
  1207. fflush(stderr); /* for SAS/C */
  1208. }
  1209. if (3*escaped < mv) {
  1210. mb = 0;
  1211. /* mv = 3*escaped; */
  1212. }
  1213. }
  1214. if ((flags & F_STATS)) fprintf(stderr, "\n");
  1215. if (flags & F_VERBOSE) fprintf(stderr, "Selected %d-bit escapes\n", mb);
  1216. escBits = mb;
  1217. escMask = (0xff00>>escBits) & 0xff;
  1218. }
  1219. if (!(flags & F_NOOPT)) {
  1220. if (flags & F_VERBOSE) {
  1221. fprintf(stderr, "Optimizing LZ77 and RLE lengths...");
  1222. fflush(stderr);
  1223. }
  1224. }
  1225. /* Find the optimum path (optimize) */
  1226. OptimizeLength((flags & F_NOOPT)?0:1);
  1227. if (flags & F_STATS) {
  1228. if (!(flags & F_NOOPT)) fprintf(stderr, " gained %d units.\n", lzopt/8);
  1229. }
  1230. else {
  1231. if (flags & F_VERBOSE) fprintf(stderr, "\n");
  1232. }
  1233. if (1 || (flags & F_AUTOEX)) {
  1234. long lzstat[5] = {0,0,0,0,0}, i, cur = 0, old = extraLZPosBits;
  1235. if (flags & F_VERBOSE) {
  1236. fprintf(stderr, "Selecting LZPOS LO length.. ");
  1237. fflush(stderr);
  1238. }
  1239. for (p=0; p<inlen; ) {
  1240. switch (mode[p]) {
  1241. case LZ77:
  1242. extraLZPosBits = 0;
  1243. lzstat[0] += LenLz(lzlen[p], lzpos[p]);
  1244. extraLZPosBits = 1;
  1245. lzstat[1] += LenLz(lzlen[p], lzpos[p]);
  1246. extraLZPosBits = 2;
  1247. lzstat[2] += LenLz(lzlen[p], lzpos[p]);
  1248. extraLZPosBits = 3;
  1249. lzstat[3] += LenLz(lzlen[p], lzpos[p]);
  1250. extraLZPosBits = 4;
  1251. lzstat[4] += LenLz(lzlen[p], lzpos[p]);
  1252. p += lzlen[p];
  1253. break;
  1254. case DLZ:
  1255. p += lzlen2[p];
  1256. break;
  1257. case RLE:
  1258. p += rle[p];
  1259. break;
  1260. default:
  1261. p++;
  1262. break;
  1263. }
  1264. }
  1265. for (i=0; i<5; i++) {
  1266. if (flags & F_STATS) fprintf(stderr, " %ld:%ld", i + 8, lzstat[i]);
  1267. if (lzstat[i] < lzstat[cur]) cur = i;
  1268. }
  1269. extraLZPosBits = (flags & F_AUTOEX)?cur:old;
  1270. if (flags & F_STATS) fprintf(stderr, "\n");
  1271. if (flags & F_VERBOSE) {
  1272. fprintf(stderr, "Selected %d-bit LZPOS LO part\n",extraLZPosBits + 8);
  1273. if (cur != old) fprintf(stderr,"Note: Using option -p%ld you may get better results.\n",cur);
  1274. }
  1275. /* Find the optimum path (optimize) */
  1276. if (extraLZPosBits != old) OptimizeLength((flags & F_NOOPT)?0:1);
  1277. }
  1278. if (1) {
  1279. long stat[4] = {0,0,0,0};
  1280. for (p=0; p<inlen; ) {
  1281. switch (mode[p]) {
  1282. case LZ77:
  1283. if ((lzpos[p] >> 8)+1 > (1<<maxGamma))
  1284. stat[3]++;
  1285. if (lzlen[p] > (1<<maxGamma))
  1286. stat[0]++;
  1287. p += lzlen[p];
  1288. break;
  1289. case RLE:
  1290. if (rle[p] > (1<<(maxGamma-1))) {
  1291. if (rle[p] <= (1<<maxGamma))
  1292. stat[1]++;
  1293. }
  1294. p += rle[p];
  1295. break;
  1296. case DLZ:
  1297. p += lzlen2[p];
  1298. break;
  1299. default:
  1300. p++;
  1301. break;
  1302. }
  1303. }
  1304. /* TODO: better formula.. */
  1305. if (maxGamma < 7 && stat[0] + stat[1] + stat[3] > 10) {
  1306. if (flags & F_VERBOSE) fprintf(stderr,"Note: Using option -m%d you may get better results.\n",maxGamma+1);
  1307. }
  1308. if (maxGamma > 5 && stat[0] + stat[1] + stat[3] < 4) {
  1309. if (flags & F_VERBOSE) fprintf(stderr,"Note: Using option -m%d you may get better results.\n",maxGamma-1);
  1310. }
  1311. }
  1312. /* Optimize the escape selections */
  1313. OptimizeEscape(&escape, NULL);
  1314. if (startEscape) *startEscape = escape;
  1315. OptimizeRle(flags); /* Retune the RLE selections */
  1316. if (flags & F_VERBOSE) {
  1317. int oldEscape = escape;
  1318. if (flags & F_VERBOSE) printf("normal RLE LZLEN LZPOS(absolute)\n\n");
  1319. for (p=0; p<inlen; ) {
  1320. switch (mode[p]) {
  1321. case LZ77:
  1322. mode[p - lzpos[p]] |= MMARK; /* Was referred to by lz77 */
  1323. p += lzlen[p];
  1324. break;
  1325. case RLE:
  1326. p += rle[p];
  1327. break;
  1328. case DLZ:
  1329. mode[p - lzpos2[p]] |= MMARK; /* Was referred to by lz77 */
  1330. p += lzlen2[p];
  1331. break;
  1332. /* case LITERAL:
  1333. case MMARK:*/
  1334. default:
  1335. p++;
  1336. break;
  1337. }
  1338. }
  1339. j = 0;
  1340. for (p=0; p<inlen; p++) {
  1341. switch (mode[p]) {
  1342. case MMARK | DLZ:
  1343. case DLZ:
  1344. if (j==p) {
  1345. if (flags & F_VERBOSE) printf(">");
  1346. j += lzlen2[p];
  1347. } else
  1348. printf(" ");
  1349. if (lzpos2) {
  1350. if (flags & F_VERBOSE) printf(" %04x*%03d*+%02x", lzpos2[p], lzlen2[p],(indata[p] - indata[p-lzpos2[p]]) & 0xff);
  1351. }
  1352. if (flags & F_VERBOSE) printf(" 001 %03d %03d %04x(%04x) %02x %s\n",
  1353. rle[p],lzlen[p],lzpos[p],p-lzpos[p],indata[p],
  1354. (mode[p] & MMARK)?"#":" ");
  1355. break;
  1356. case MMARK | LITERAL:
  1357. case LITERAL:
  1358. if (flags & F_VERBOSE) {
  1359. if (j==p) printf(">");
  1360. else printf(" ");
  1361. if (lzpos2) {
  1362. printf(" %04x %03d +%02x", lzpos2[p], lzlen2[p],
  1363. (indata[p] - indata[p-lzpos2[p]]) & 0xff);
  1364. }
  1365. }
  1366. if (j==p) {
  1367. if (flags & F_VERBOSE) {
  1368. printf("*001* %03d %03d %04x(%04x) %02x %s %02x",
  1369. rle[p], lzlen[p], lzpos[p], p-lzpos[p], indata[p],
  1370. (mode[p] & MMARK)?"#":" ", newesc[p]);
  1371. }
  1372. if ((indata[p] & escMask) == escape) {
  1373. escape = newesc[p];
  1374. if (flags & F_VERBOSE) printf("«");
  1375. }
  1376. if (flags & F_VERBOSE) printf("\n");
  1377. j += 1;
  1378. } else {
  1379. if (flags & F_VERBOSE) printf("*001* %03d %03d %04x(%04x) %02x %s %02x\n",
  1380. rle[p], lzlen[p], lzpos[p], p-lzpos[p], indata[p],
  1381. (mode[p] & MMARK)?"#":" ", newesc[p]);
  1382. }
  1383. break;
  1384. case MMARK | LZ77:
  1385. case LZ77:
  1386. if (j==p) {
  1387. if (flags & F_VERBOSE) printf(">");
  1388. j += lzlen[p];
  1389. } else
  1390. if (flags & F_VERBOSE) printf(" ");
  1391. if (lzpos2) {
  1392. if (flags & F_VERBOSE) printf(" %04x %03d +%02x", lzpos2[p], lzlen2[p],
  1393. (indata[p] - indata[p-lzpos2[p]]) & 0xff);
  1394. }
  1395. if (flags & F_VERBOSE) printf(" 001 %03d *%03d* %04x(%04x) %02x %s\n",
  1396. rle[p], lzlen[p], lzpos[p], p-lzpos[p], indata[p],
  1397. (mode[p] & MMARK)?"#":" ");
  1398. break;
  1399. case MMARK | RLE:
  1400. case RLE:
  1401. if (j==p) {
  1402. if (flags & F_VERBOSE) printf(">");
  1403. j += rle[p];
  1404. } else
  1405. if (flags & F_VERBOSE) printf(" ");
  1406. if (lzpos2) {
  1407. if (flags & F_VERBOSE) printf(" %04x %03d +%02x", lzpos2[p], lzlen2[p],
  1408. (indata[p] - indata[p-lzpos2[p]]) & 0xff);
  1409. }
  1410. if (flags & F_VERBOSE) printf(" 001 *%03d* %03d %04x(%04x) %02x %s\n",
  1411. rle[p], lzlen[p], lzpos[p], p-lzpos[p], indata[p],
  1412. (mode[p] & MMARK)?"#":" ");
  1413. break;
  1414. default:
  1415. j++;
  1416. break;
  1417. }
  1418. mode[p] &= ~MMARK;
  1419. }
  1420. escape = oldEscape;
  1421. }
  1422. for (p=0; p<inlen; ) {
  1423. switch (mode[p]) {
  1424. case LITERAL: /* normal */
  1425. length[p] = outPointer;
  1426. OutputNormal(&escape, indata+p, newesc[p]);
  1427. p++;
  1428. break;
  1429. case DLZ:
  1430. for (i=0; i<lzlen2[p]; i++) length[p+i] = outPointer;
  1431. PutNBits((escape>>(8-escBits)), escBits);
  1432. PutValue(lzlen2[p]-1);
  1433. PutValue((2<<maxGamma)-1);
  1434. PutNBits((indata[p] - indata[p-lzpos2[p]]) & 0xff, 8);
  1435. PutNBits(((lzpos2[p]-1) & 0xff) ^ 0xff, 8);
  1436. gainedDLz += 8*lzlen2[p] -(escBits + LenValue(lzlen2[p]-1) + 2*maxGamma + 16);
  1437. timesDLz++;
  1438. p += lzlen2[p];
  1439. break;
  1440. case LZ77: /* lz77 */
  1441. /* Not possible for smaller backSkip table
  1442. (the table is overwritten during previous use) */
  1443. /* Re-search matches to get the closest one */
  1444. if (lzopt && lzlen[p] > 2 && lzlen[p] > rle[p]) {
  1445. int bot = p - lzpos[p] + 1, i;
  1446. unsigned short rlep = rle[p];
  1447. if (!rlep)
  1448. rlep = 1;
  1449. if (bot < 0)
  1450. bot = 0;
  1451. bot += (rlep-1);
  1452. i = p - (int)backSkip[p];
  1453. while (i>=bot /* && i>=rlep-1 */) {
  1454. /* Equal number of A's ? */
  1455. if (rlep==1 || rle[i-rlep+1]==rlep) { /* 'head' matches */
  1456. unsigned char *a = indata + i+1; /* match */
  1457. unsigned char *b = indata + p+rlep-1+1; /* curpos */
  1458. int topindex = inlen-(p+rlep-1);
  1459. j = 1;
  1460. while (j < topindex && *a++==*b++)
  1461. j++;
  1462. if (j + rlep-1 >= lzlen[p]) {
  1463. int tmppos = p-i+rlep-1;
  1464. rescan +=
  1465. LenLz(lzlen[p], lzpos[p]) -
  1466. LenLz(lzlen[p], tmppos);
  1467. lzpos[p] = tmppos;
  1468. break;
  1469. }
  1470. }
  1471. if (!backSkip[i])
  1472. break; /* No previous occurrances (near enough) */
  1473. i -= (int)backSkip[i];
  1474. }
  1475. }
  1476. for (i=0; i<lzlen[p]; i++)
  1477. length[p+i] = outPointer;
  1478. OutputLz(&escape, lzlen[p], lzpos[p], (char *)(indata+p-lzpos[p]), p);
  1479. p += lzlen[p];
  1480. break;
  1481. case RLE: /* rle */
  1482. for (i=0; i<rle[p]; i++)
  1483. length[p+i] = outPointer;
  1484. OutputRle(&escape, indata+p, rle[p]);
  1485. p += rle[p];
  1486. break;
  1487. default: /* Error Flynn :-) */
  1488. p++;
  1489. fprintf(stderr, "Internal error: mode %d\n", mode[p]);
  1490. break;
  1491. }
  1492. }
  1493. OutputEof(&escape);
  1494. i = inlen;
  1495. for (p=0; p<inlen; p++) {
  1496. int pos = (inlen - outPointer) + (int)length[p] - p;
  1497. i = min(i, pos);
  1498. }
  1499. if (i<0)
  1500. reservedBytes = -i + 2;
  1501. else
  1502. reservedBytes = 0;
  1503. // TOMTOM !!!
  1504. if ((type & FIXF_MACHMASK) == 0) {
  1505. headerSize = 16 + rleUsed;
  1506. } else
  1507. {
  1508. if (endAddr + reservedBytes + 3 > memEnd) {
  1509. type |= FIXF_WRAP;
  1510. } else {
  1511. type &= ~FIXF_WRAP;
  1512. }
  1513. headerSize = 47 + rleUsed - 31;
  1514. }
  1515. outlen = outPointer + headerSize; /* unpack code */
  1516. if (flags & F_VERBOSE) fprintf(stderr, "In: %d, out: %d, ratio: %5.2f%% (%4.2f[%4.2f] b/B)"
  1517. ", gained: %5.2f%%\n",
  1518. inlen, outlen, (double)outlen*100.0/(double)inlen + 0.005,
  1519. 8.0*(double)outlen/(double)inlen + 0.005,
  1520. 8.0*(double)(outlen-headerSize+rleUsed+4)/(double)inlen + 0.005,
  1521. 100.0 - (double)outlen*100.0/(double)inlen + 0.005);
  1522. if ((type & FIXF_DLZ)) {
  1523. if (flags & F_VERBOSE) {
  1524. fprintf(stderr, "Gained RLE: %d (S+L:%d+%d), DLZ: %d, LZ: %d, Esc: %d"
  1525. ", Decompressor: %d\n",
  1526. gainedRle/8, gainedSRle/8, gainedLRle/8, gainedDLz/8,
  1527. gainedLz/8, -gainedEscaped/8, -headerSize);
  1528. fprintf(stderr, "Times RLE: %d (%d+%d), DLZ: %d, LZ: %d, Esc: %d (normal: %d)"
  1529. ", %d escape bit%s\n",
  1530. timesRle, timesSRle, timesLRle, timesDLz,
  1531. timesLz, timesEscaped, timesNormal,
  1532. escBits, (escBits==1)?"":"s" );
  1533. }
  1534. }
  1535. else {
  1536. if (flags & F_VERBOSE) {
  1537. fprintf(stderr, "Gained RLE: %d (S+L:%d+%d), LZ: %d, Esc: %d"
  1538. ", Decompressor: %d\n",
  1539. gainedRle/8, gainedSRle/8, gainedLRle/8,
  1540. gainedLz/8, -gainedEscaped/8, -headerSize);
  1541. fprintf(stderr, "Times RLE: %d (%d+%d), LZ: %d, Esc: %d (normal: %d)"
  1542. ", %d escape bit%s\n",
  1543. timesRle, timesSRle, timesLRle,
  1544. timesLz, timesEscaped, timesNormal,
  1545. escBits, (escBits==1)?"":"s" );
  1546. }
  1547. }
  1548. if ((flags & F_STATS)) {
  1549. char *ll[] = {"2", "3-4", "5-8", "9-16", "17-32", "33-64",
  1550. "65-128", "129-256"};
  1551. fprintf(stderr, "(Gained by RLE Code: %d, LZPOS LO Bits %d"
  1552. ", maxLen: %d, tag bit/prim. %4.2f)\n",
  1553. gainedRlecode/8 - rleUsed,
  1554. extraLZPosBits + 8,
  1555. (2<<maxGamma),
  1556. (double)((timesRle+timesLz)*escBits +
  1557. timesEscaped*(escBits + 3))/
  1558. (double)(timesRle+timesLz+timesNormal) + 0.0049);
  1559. fprintf(stderr, " LZPOS HI+2 LZLEN S-RLE RLEcode\n");
  1560. fprintf(stderr, " ------------------------------\n");
  1561. for (i=0; i<=maxGamma; i++) {
  1562. fprintf(stderr, "%-7s %5d %5d", ll[i],
  1563. lenStat[i][0], lenStat[i][1]);
  1564. if (i<maxGamma)
  1565. fprintf(stderr, " %5d", lenStat[i][2]);
  1566. else
  1567. fprintf(stderr, " -");
  1568. if (i<6)
  1569. fprintf(stderr, " %5d%s\n", lenStat[i][3], (i==5)?"*":"");
  1570. else
  1571. fprintf(stderr, " -\n");
  1572. }
  1573. fprintf(stderr, "LZ77 rescan gained %d bytes\n", rescan/8);
  1574. }
  1575. errorexit:
  1576. if (rle) free(rle);
  1577. if (elr) free(elr);
  1578. if (lzlen) free(lzlen);
  1579. if (lzpos) free(lzpos);
  1580. if (length) free(length);
  1581. if (mode) free(mode);
  1582. if (newesc) free(newesc);
  1583. if (lastPair) free(lastPair);
  1584. if (backSkip) free(backSkip);
  1585. if (hashValue) free(hashValue);
  1586. return err_occured;
  1587. }
  1588. #define NO_HEX_CHARACTER 255
  1589. //=============================================================================
  1590. // converts hexdigit to number
  1591. //=============================================================================
  1592. unsigned char hex2int(unsigned char c) {
  1593. c = tolower(c);
  1594. if (c >= 'a' && c <= 'f') return c - 'a' + 10;
  1595. if (c >= '0' && c <= '9') return c - '0';
  1596. return NO_HEX_CHARACTER;
  1597. }
  1598. //=============================================================================
  1599. // converts hex text into binary
  1600. //=============================================================================
  1601. int ConvertText2Bin(unsigned char* ib,int origlen) {
  1602. int pos;
  1603. int cnt = 0;
  1604. int searchforendofline = 0;
  1605. int len_after_convert = 0;
  1606. unsigned char val = 0;
  1607. unsigned char actual;
  1608. len_after_convert = 0;
  1609. for (pos = 0; pos < origlen;pos++) {
  1610. if (searchforendofline) {
  1611. if (ib[pos] == '\n') searchforendofline = 0;
  1612. continue;
  1613. }
  1614. if (ib[pos] == '/') {
  1615. cnt = 0;
  1616. if (pos < origlen-1 && ib[pos+1] == '/') searchforendofline = 1;
  1617. continue;
  1618. }
  1619. actual = hex2int(ib[pos]);
  1620. if (actual == NO_HEX_CHARACTER) {
  1621. cnt = 0;
  1622. continue;
  1623. }
  1624. if (cnt == 0) {
  1625. val = actual*16;
  1626. cnt++;
  1627. }
  1628. else {
  1629. val += actual;
  1630. cnt=0;
  1631. ib[len_after_convert++] = val;
  1632. }
  1633. }
  1634. return(len_after_convert);
  1635. }
  1636. //=============================================================================
  1637. // as usual: the main, but a long one ...
  1638. //=============================================================================
  1639. #ifndef EMBEDDED_USE
  1640. int main(int argc, char *argv[]) {
  1641. #else
  1642. int TTPack(int argc,char *argv[]) {
  1643. #endif
  1644. int startAddr = 0x258;
  1645. int flags = F_AUTO | F_AUTOEX;
  1646. int lzlen = -1;
  1647. int buflen;
  1648. int newlen;
  1649. int startEscape;
  1650. int n;
  1651. char *fileIn = NULL;
  1652. char *fileOut = NULL;
  1653. FILE *infp;
  1654. unsigned long timeused = clock();
  1655. int memStart = 0x801;
  1656. int memEnd = 0x10000;
  1657. int type = 0;
  1658. quiet = 0;
  1659. TTPackInit();
  1660. lrange = LRANGE;
  1661. maxlzlen = MAXLZLEN;
  1662. maxrlelen = MAXRLELEN;
  1663. InitValueLen();
  1664. for (n=1; n<argc; n++) {
  1665. if (!strcmp(argv[n], "-fnorle")) flags |= F_NORLE;
  1666. else if (!strcmp(argv[n], "-fdelta")) type |= FIXF_DLZ;
  1667. else if (!strcmp(argv[n], "-hti")) flags |= F_TEXTINPUT;
  1668. else if (!strcmp(argv[n], "-hto")) flags |= F_TEXTOUTPUT;
  1669. else if (!strcmp(argv[n], "-quiet")) flags &= ~F_VERBOSE, quiet = 1;
  1670. else if (argv[n][0]=='-' || argv[n][0]=='/') {
  1671. int i = 1;
  1672. char *val, *tmp, c;
  1673. long tmpval;
  1674. while (argv[n][i]) {
  1675. switch (argv[n][i]) {
  1676. case 'n': /* noopt, no rle/lzlen optimization */
  1677. flags |= F_NOOPT;
  1678. break;
  1679. case 's':
  1680. flags |= F_STATS;
  1681. break;
  1682. case 'v':
  1683. flags |= F_VERBOSE;
  1684. quiet = 0;
  1685. break;
  1686. case 'h':
  1687. case '?':
  1688. flags |= F_ERROR;
  1689. break;
  1690. case 'r':
  1691. case 'm':
  1692. case 'e':
  1693. case 'p':
  1694. c = argv[n][i]; /* Remember the option */
  1695. if (argv[n][i+1]) {
  1696. val = argv[n]+i+1;
  1697. } else if (n+1 < argc) {
  1698. val = argv[n+1];
  1699. n++;
  1700. } else {
  1701. flags |= F_ERROR;
  1702. break;
  1703. }
  1704. i = strlen(argv[n])-1;
  1705. if (*val=='$') tmpval = strtol(val+1, &tmp, 16);
  1706. else tmpval = strtol(val, &tmp, 0);
  1707. if (*tmp) {
  1708. fprintf(stderr,"ERROR: invalid number: \"%s\"\n", val);
  1709. flags |= F_ERROR;
  1710. break;
  1711. }
  1712. switch (c) {
  1713. case 'r':
  1714. lzlen = tmpval;
  1715. break;
  1716. case 'm':
  1717. maxGamma = tmpval;
  1718. if (maxGamma < 5 || maxGamma > 7) {
  1719. fprintf(stderr, "ERROR: Max length must be 5..7!\n");
  1720. flags |= F_ERROR;
  1721. maxGamma = 7;
  1722. }
  1723. lrange = LRANGE;
  1724. maxlzlen = MAXLZLEN;
  1725. maxrlelen = MAXRLELEN;
  1726. InitValueLen();
  1727. break;
  1728. case 'e':
  1729. escBits = tmpval;
  1730. if (escBits < 0 || escBits > 8) {
  1731. fprintf(stderr, "ERROR: Escape bits must be 0..8!\n");
  1732. flags |= F_ERROR;
  1733. }
  1734. else flags &= ~F_AUTO;
  1735. escMask = (0xff00>>escBits) & 0xff;
  1736. break;
  1737. case 'p':
  1738. extraLZPosBits = tmpval;
  1739. if (extraLZPosBits < 0 || extraLZPosBits > 4) {
  1740. fprintf(stderr,"ERROR: Extra LZ-pos bits must be 0..4!\n");
  1741. flags |= F_ERROR;
  1742. }
  1743. else flags &= ~F_AUTOEX;
  1744. break;
  1745. }
  1746. break;
  1747. default:
  1748. fprintf(stderr, "ERROR: Unknown option \"%c\"\n",argv[n][i]);
  1749. flags |= F_ERROR;
  1750. }
  1751. i++;
  1752. }
  1753. } else {
  1754. if (!fileIn) {
  1755. fileIn = argv[n];
  1756. }
  1757. else if (!fileOut) {
  1758. fileOut = argv[n];
  1759. }
  1760. else {
  1761. fprintf(stderr, "ERROR: Only two filenames wanted!\n");
  1762. flags |= F_ERROR;
  1763. }
  1764. }
  1765. }
  1766. // input and output file
  1767. if ((flags & F_ERROR) || !fileIn || !fileOut) {
  1768. #ifndef EMBEDDED_USE
  1769. PrintUsage();
  1770. #endif
  1771. return 1;
  1772. }
  1773. #ifndef EMBEDDED_USE
  1774. if (!quiet) PRINT_ID("TTPack");
  1775. #endif
  1776. if (lzlen == -1) lzlen = DEFAULT_LZLEN;
  1777. if (fileIn) {
  1778. if (!(infp = fopen(fileIn, "rb"))) {
  1779. fprintf(stderr, "ERROR: Could not open %s for reading!\n", fileIn);
  1780. return 1;
  1781. }
  1782. }
  1783. else {
  1784. fprintf(stderr, "assuming stdin as text input.\nCtrl-C to abort, Ctrl-Z for EOF.\n");
  1785. infp = stdin;
  1786. }
  1787. /* Read in the data */
  1788. inlen = 0;
  1789. buflen = 0;
  1790. indata = NULL;
  1791. while (1) {
  1792. if (buflen < inlen + lrange) {
  1793. unsigned char *tmp = realloc(indata, buflen + lrange);
  1794. if (!tmp) {
  1795. free(indata);
  1796. fprintf(stderr, "ERROR: realloc failed!\n");
  1797. return 1;
  1798. }
  1799. indata = tmp;
  1800. buflen += lrange;
  1801. }
  1802. newlen = fread(indata + inlen, 1, lrange, infp);
  1803. if (newlen <= 0) break;
  1804. inlen += newlen;
  1805. }
  1806. //-----------------------------------------------------------
  1807. // convert the input buffer from hex text to binary
  1808. // if the user asks for it
  1809. //-----------------------------------------------------------
  1810. if (flags & F_TEXTINPUT) inlen = ConvertText2Bin(indata,inlen);
  1811. if (infp != stdin) fclose(infp);
  1812. if (startAddr + inlen -1 > 0xffff) {
  1813. fprintf(stderr,"ERROR: File is too large to handle (>64936 Bytes)");
  1814. if (indata) free(indata);
  1815. return 1;
  1816. }
  1817. if (flags & F_VERBOSE) {
  1818. fprintf(stderr, "Load address 0x%04x=%d, Last byte 0x%04x=%d\n",
  1819. startAddr, startAddr, startAddr+inlen-1, startAddr+inlen-1);
  1820. fprintf(stderr, "New load address 0x%04x=%d\n", memStart, memStart);
  1821. }
  1822. n = PackLz77(lzlen, flags, &startEscape, startAddr + inlen, memEnd, type);
  1823. if (!n) {
  1824. int endAddr = startAddr + inlen; /* end for uncompressed data */
  1825. if (endAddr - ((outPointer + 255) & ~255) < memStart + 3) {
  1826. /* would overwrite the decompressor, move a bit upwards */
  1827. if (flags & F_VERBOSE) fprintf(stderr,"$%x < $%x, decompressor overwrite possible, moving upwards\n",
  1828. endAddr - ((outPointer + 255) & ~255), memStart + 3);
  1829. endAddr = memStart + 3 + ((outPointer + 255) & ~255);
  1830. }
  1831. /* 3 bytes reserved for EOF */
  1832. /* bytes reserved for temporary data expansion (escaped chars) */
  1833. endAddr += 3 + reservedBytes;
  1834. if (!timesDLz) type &= ~FIXF_DLZ;
  1835. // type ... may vary
  1836. // outBuffer ... static global array (65536 Bytes)
  1837. SavePack(flags,type, outBuffer, outPointer, fileOut,
  1838. startAddr, startEscape, rleValues,
  1839. endAddr, extraLZPosBits,
  1840. memStart, memEnd);
  1841. timeused = clock()-timeused;
  1842. if (!timeused) timeused++;
  1843. if (flags & F_VERBOSE) fprintf(stderr,
  1844. "Compressed %d bytes in %4.2f seconds (%4.2f kB/sec)\n",
  1845. inlen,
  1846. (double)timeused/CLOCKS_PER_SEC,
  1847. (double)CLOCKS_PER_SEC*inlen/timeused/1024.0);
  1848. return 0;
  1849. }
  1850. if (indata) free(indata);
  1851. return n;
  1852. }
  1853. #endif
  1854. //#############################################################################
  1855. //###################### NO MORE FAKES BEYOND THIS LINE #######################
  1856. //#############################################################################
  1857. //
  1858. //=============================================================================
  1859. // Revision History
  1860. //=============================================================================
  1861. //
  1862. // Revision 1.8 2002/03/14 10:47:41 tnussb
  1863. // (1) new flag "-quiet" added (suppress standard messages)
  1864. // (2) some error messages rewritten
  1865. //
  1866. // Revision 1.7 2002/03/04 14:32:42 tnussb
  1867. // now tool can be used as embedded version from within other tools
  1868. // by defining EMBEDDED_VERSION before including the sourcefile
  1869. //
  1870. // Revision 1.6 2002/02/07 09:49:37 tnussb
  1871. // all local includes changed, because header files are now located in pctools folder
  1872. //
  1873. // Revision 1.5 2000/11/28 00:07:32 Thomas Nussbaumer
  1874. // using now USAGE_OUT stream for usage info
  1875. //
  1876. // Revision 1.4 2000/08/23 20:10:56 Thomas Nussbaumer
  1877. // header corrected
  1878. //
  1879. // Revision 1.3 2000/08/23 20:10:17 Thomas Nussbaumer
  1880. // adapted to automatic version display (revtools.h)
  1881. //
  1882. // Revision 1.2 2000/08/20 15:30:11 Thomas Nussbaumer
  1883. // minor correction of header
  1884. //
  1885. // Revision 1.1 2000/08/16 23:05:59 Thomas Nussbaumer
  1886. // initial version
  1887. //
  1888. //