sega_cmp 0.2.0

Library to compress data using Sega's CMP format
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
/*****************************************************************************/
/* compress_rtns.c - CMP-Compatible Compression Routines.                    */
/*                   CMP is really just a form of RLE compression.           */
/*****************************************************************************/


///////////////////////////////////////////////////////////////////////////////
// Data Compression Format                                                   //
// Two types of data are encountered: compressed and direct copy.            //
// Compression occurs using X-bit data types (X = 8, 16, or 32).             //
//                                                                           //
// ---------------------------------------------------------------------     //
// Compressed copy:  | (Length-2) # of X-bit matches   | X-bit pattern |     //
// ---------------------------------------------------------------------     //
// Note that compression requires at least 2 in-order matches.               //
// Length and pattern occupy X-bits                                          //
//                                                                           //
// ------------------------------------------------------------------------  //
// Direct copy:      | Neg length in #X-bit units | Data to directly copy |  //
// ------------------------------------------------------------------------  //
///////////////////////////////////////////////////////////////////////////////

/* Includes */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "compress_rtns.h"




/*****************************************************************************/
/* cmp_compress - Top Level Compression routine.                             */
/* Returns: 0 on success, -1 on failure.                                     */
/*****************************************************************************/
int cmp_compress(char* inputFname, unsigned int fileOffset, 
				 int reqDataSizeBytes, int cmprType, 
				 int* cmprSizeBytes, 
				 int* decmprSizeBytes, 
				 char** pCmprData)
{
    char* ibuffer = NULL;
    unsigned int fsize = 0;
	FILE* infile = NULL;
	int sizeBytes = 0;
	int rval = 0;

	/* Open the input file for reading */
	infile = fopen(inputFname,"rb");
	if(infile == NULL){
		printf("Error opening file %s\n",inputFname);
		return -1;
	}

	/* Allocate memory for the input data to be compressed */
	fseek(infile,0,SEEK_END);
	fsize = ftell(infile);
	if(reqDataSizeBytes == 0)
		sizeBytes = fsize-fileOffset;
	else
		sizeBytes = reqDataSizeBytes;
	ibuffer = (char*)malloc(sizeBytes);
	if(ibuffer == NULL){
		printf("Error allocing memory for input data\n");
		return -1;
	}

	/* Jump to starting offset of input file and read */
	/* the data to be compressed to a buffer */
	fseek(infile,fileOffset,SEEK_SET);
	sizeBytes = fread(ibuffer,1,sizeBytes,infile);
	fclose(infile);
	if(sizeBytes <= 0){
		printf("Error reading from input file\n");
		return -1;
	}
	*decmprSizeBytes = sizeBytes;


	/* Compress Based on Selected Pattern Length: 8/16/32-bit */
	switch(cmprType){

		case BYTE_CMP_TYPE:
		{
			if(cmpr_8bit(ibuffer,sizeBytes,pCmprData,cmprSizeBytes) < 0){
				printf("8-bit compression failed.\n");
				rval = -1;
			}
		}
		break;

		case SHORT_CMP_TYPE:
		{
			int numShorts = 0;
			numShorts = sizeBytes / 2;
			if((sizeBytes % 2) != 0)
				numShorts++;
			if(cmpr_16bit((short*)ibuffer,numShorts,
				(short**)pCmprData,cmprSizeBytes) < 0){
				printf("16-bit compression failed.\n");
				rval = -1;
			}
		}
		break;

		case LONG_CMP_TYPE:
		{
			int numLongs = 0;
			numLongs = sizeBytes / 4;
			if((sizeBytes % 4) != 0)
				numLongs++;
			if(cmpr_32bit((int*)ibuffer,numLongs,
				(int**)pCmprData,cmprSizeBytes) < 0){
				printf("32-bit compression failed.\n");
				rval = -1;
			}
		}
		break;

		default:
			printf("Error, incorrect compression type specified.\n");
			rval = -1;
	}

	/* Free Resources */
	if(ibuffer != NULL)
		free(ibuffer);

	return rval;
}




/*****************************************************************************/
/* cmpr_8bit - 8-bit CMP Compression routine.                                */
/* Inputs: pData, pointer to uncompressed data stream                        */
/*         numBytes, number of 8-bit bytes in uncompr stream                 */
/*         outData, used to allocate compressed stream                       */
/*         comprSizeBytes, size of the compressed data stream                */
/* Returns: 0 on success, -1 on failure.                                     */
/*****************************************************************************/
int cmpr_8bit(char* pData, int numBytes, char** outData, int* cmprSizeBytes){

	int i, pattDetectFlg, maxCmprSizeBytes, unitSizeBytes, runtarget;
    unsigned int u_unmatchedCount;
	char unmatchedCount, pattern, runLength;
	char* pCmrData;
	char* startLoc   = pData;
	char* patternLoc = pData;
	pattDetectFlg = 0;
	unmatchedCount = 0;
	unitSizeBytes = 1;
	runtarget = 2;
	*cmprSizeBytes = 0;

	/* Allocate Memory for compressed data stream */
	/* Assume the compressed data will not exceed the original size  */
	/* If expansion does occur, the code that follows will abort out */
	maxCmprSizeBytes = numBytes*unitSizeBytes;
	*outData = (char*)malloc(maxCmprSizeBytes);
	if(*outData == NULL){
		printf("Error allocating memory for compressed data stream\n");
		return -1;
	}
	pCmrData = *outData;

	/* While data exists, continue to attempt compression */
	while(numBytes > 0){

	    /* For patterns, look for a run of at least 2   */
		/* Then determine how long the pattern runs for */
		i = 1;

	    if( (numBytes >= runtarget) && 
			( ((runtarget == 2) && (*patternLoc == *(patternLoc+i))) ||
			( ((runtarget == 3) && (*patternLoc == *(patternLoc+i)) && (*patternLoc == *(patternLoc+i+1))) )) ){

			numBytes-= runtarget;
			i+=runtarget-1; 
			runLength = runtarget-2;
			runtarget = 2;
			pattDetectFlg = 1;

			while((numBytes > 0) && (runLength < MAX_S_BYTE)){
				if(*patternLoc == *(patternLoc+i)){
					i++;
					runLength++;
					numBytes--;
				}
				else
					break;
			}
		}


		/* If a pattern was found, write out unmatched data to the */
		/* compression stream, followed by the pattern data        */
		if(pattDetectFlg){
			pattDetectFlg = 0;

			/* Compression Stream - Unmatched Data */
			if(startLoc != patternLoc){
				u_unmatchedCount = (unsigned int)(-1*unmatchedCount);
                *cmprSizeBytes += u_unmatchedCount*unitSizeBytes + unitSizeBytes;
				if(*cmprSizeBytes > maxCmprSizeBytes){
					printf("Error in compression, expansion occurred.\n");
					return -1;
				}
				memcpy(pCmrData,&unmatchedCount,unitSizeBytes);           pCmrData++;
				memcpy(pCmrData,startLoc,u_unmatchedCount*unitSizeBytes); pCmrData+=u_unmatchedCount;
                unmatchedCount = 0;
			}
            
			/* Compression Stream - Pattern Data */
			*cmprSizeBytes += (unitSizeBytes*2);
			if(*cmprSizeBytes > maxCmprSizeBytes){
				printf("Error in compression, expansion occurred.\n");
				return -1;
			}
			memcpy(pCmrData,&runLength,unitSizeBytes);   pCmrData++;
			pattern = *patternLoc;
			memcpy(pCmrData,&pattern,unitSizeBytes);     pCmrData++;

			patternLoc += i;
			startLoc = patternLoc;
		}
		else{

			/* No new pattern was found on this comparison */
			numBytes--;
			patternLoc++;

            /* If the number of unmatched units exceeds the maximum allowed */
            /* then write that data to the output stream now */
            unmatchedCount--;
			if(unmatchedCount == MIN_S_BYTE){
                u_unmatchedCount = (unsigned int)(-1*(unmatchedCount+(char)1)) + 1;
				*cmprSizeBytes += u_unmatchedCount*unitSizeBytes + unitSizeBytes;
				if(*cmprSizeBytes > maxCmprSizeBytes){
					printf("Error in compression, expansion occurred.\n");
					return -1;
				}
	       	    memcpy(pCmrData,&unmatchedCount,unitSizeBytes);           pCmrData++;
		        memcpy(pCmrData,startLoc,u_unmatchedCount*unitSizeBytes); pCmrData+=u_unmatchedCount;
   			    startLoc = patternLoc;
                unmatchedCount = 0;
				runtarget = 2;
			}
			else if(unmatchedCount == (MIN_S_BYTE+1))
				runtarget = 2;
			else
                runtarget = 3;
		}
	}

	/* Write out any remaining unmatched data to the compression stream */
	if(startLoc != patternLoc){
        u_unmatchedCount = (unsigned int)(-1*unmatchedCount);
		*cmprSizeBytes += u_unmatchedCount*unitSizeBytes + unitSizeBytes;
		if(*cmprSizeBytes > maxCmprSizeBytes){
			printf("Error in compression, expansion occurred.\n");
			return -1;
		}
		memcpy(pCmrData,&unmatchedCount,unitSizeBytes);           pCmrData++;
		memcpy(pCmrData,startLoc,u_unmatchedCount*unitSizeBytes); pCmrData+=u_unmatchedCount;
	}

	return 0;
}




/*****************************************************************************/
/* cmpr_16bit - 16-bit CMP Compression routine.                              */
/* Inputs: pData, pointer to uncompressed data stream                        */
/*         numShorts, number of 16-bit shorts in uncompr stream (round up)   */
/*         outData, used to allocate compressed stream                       */
/*         comprSizeBytes, size of the compressed data stream                */
/* Returns: 0 on success, -1 on failure.                                     */
/*****************************************************************************/
int cmpr_16bit(short* pData, int numShorts, short** outData, int* cmprSizeBytes){

	int i, pattDetectFlg, unitSizeBytes, maxCmprSizeBytes, runtarget;
	unsigned int u_unmatchedCount;
	short pattern, runLength, unmatchedCount;
	short* pCmrData;
	short* startLoc   = pData;
	short* patternLoc = pData;
	pattDetectFlg = 0;
	unmatchedCount = 0;
	unitSizeBytes = 2;
	runtarget = 2;
	*cmprSizeBytes = 0;

	/* Allocate Memory for compressed data stream */
	/* Assume the compressed data will not exceed the original size  */
	/* If expansion does occur, the code that follows will abort out */
	maxCmprSizeBytes = numShorts*unitSizeBytes;
	*outData = (short*)malloc(maxCmprSizeBytes);
	if(*outData == NULL){
		printf("Error allocating memory for compressed data stream\n");
		return -1;
	}
	pCmrData = *outData;


	/* While data exists, continue to attempt compression */
	while(numShorts > 0){

	    /* For patterns, look for a run of at least 2   */
		/* Then determine how long the pattern runs for */
		i = 1;

        if( (numShorts >= runtarget) && 
			( ((runtarget == 2) && (*patternLoc == *(patternLoc+i))) ||
			( ((runtarget == 3) && (*patternLoc == *(patternLoc+i)) && (*patternLoc == *(patternLoc+i+1))) )) ){

			numShorts -= runtarget;
			i+=runtarget-1; 
			runLength = runtarget-2;
			runtarget = 2;
			pattDetectFlg = 1;
			
			while((numShorts > 0) && (runLength < MAX_S_SHORT)){
				if(*patternLoc == *(patternLoc+i)){
					i++;
					runLength++;
					numShorts--;
				}
				else
					break;
			}
		}


		/* If a pattern was found, write out unmatched data to the */
		/* compression stream, followed by the pattern data        */
		if(pattDetectFlg){
			pattDetectFlg = 0;

			/* Compression Stream - Unmatched Data */
			if(startLoc != patternLoc){
				u_unmatchedCount = (unsigned int)(-1*unmatchedCount);
				*cmprSizeBytes += u_unmatchedCount*unitSizeBytes + unitSizeBytes;
				if(*cmprSizeBytes > maxCmprSizeBytes){
					printf("Error in compression, expansion occurred.\n");
					return -1;
				}
				swap16(&unmatchedCount);
				memcpy(pCmrData,&unmatchedCount,unitSizeBytes);           pCmrData++;
				memcpy(pCmrData,startLoc,u_unmatchedCount*unitSizeBytes); pCmrData+=u_unmatchedCount;
				unmatchedCount = 0;
			}

			/* Compression Stream - Pattern Data */
			*cmprSizeBytes += (unitSizeBytes*2);
			if(*cmprSizeBytes > maxCmprSizeBytes){
				printf("Error in compression, expansion occurred.\n");
				return -1;
			}

			swap16(&runLength);
			memcpy((char*)pCmrData,(char*)&runLength,unitSizeBytes);   pCmrData++;
			pattern = *patternLoc;
			memcpy((char*)pCmrData,(char*)&pattern,unitSizeBytes);     pCmrData++;
			patternLoc += i;
			startLoc = patternLoc;
		}
		else{

			/* No new pattern was found on this comparison */
			numShorts--;
			patternLoc++;

            /* If the number of unmatched units exceeds the maximum allowed */
            /* then write that data to the output stream now */
			unmatchedCount--;
			if(unmatchedCount == MIN_S_SHORT){
				u_unmatchedCount = (unsigned int)(-1*(unmatchedCount+(short)1)) + 1;
				*cmprSizeBytes += u_unmatchedCount*unitSizeBytes + unitSizeBytes;
				if(*cmprSizeBytes > maxCmprSizeBytes){
					printf("Error in compression, expansion occurred.\n");
					return -1;
				}
		        swap16(&unmatchedCount);
	       	    memcpy(pCmrData,&unmatchedCount,unitSizeBytes);           pCmrData++;
		        memcpy(pCmrData,startLoc,u_unmatchedCount*unitSizeBytes); pCmrData+=u_unmatchedCount;
   			    startLoc = patternLoc;
				unmatchedCount = 0;
				runtarget = 2;
			}
			else if(unmatchedCount == (MIN_S_SHORT+1))
				runtarget = 2;
			else
				runtarget = 3;
		}
	}

	/* Write out any remaining unmatched data to the compression stream */
	if(startLoc != patternLoc){
		u_unmatchedCount = (unsigned int)(-1*unmatchedCount);
		*cmprSizeBytes += u_unmatchedCount*unitSizeBytes + unitSizeBytes;
		if(*cmprSizeBytes > maxCmprSizeBytes){
			printf("Error in compression, expansion occurred.\n");
			return -1;
		}
		swap16(&unmatchedCount);
		memcpy(pCmrData,&unmatchedCount,unitSizeBytes);           pCmrData++;
		memcpy(pCmrData,startLoc,u_unmatchedCount*unitSizeBytes); pCmrData+=u_unmatchedCount;
	}

	return 0;
}




/*****************************************************************************/
/* cmpr_32bit - 32-bit CMP Compression routine.                              */
/* Inputs: pData, pointer to uncompressed data stream                        */
/*         numLongs, number of 32-bit longs in uncompr stream (round up)     */
/*         outData, used to allocate compressed stream                       */
/*         comprSizeBytes, size of the compressed data stream                */
/* Returns: 0 on success, -1 on failure.                                     */
/*****************************************************************************/
int cmpr_32bit(int* pData, int numLongs, int** outData, int* cmprSizeBytes){

	int pattern, unitSizeBytes, unmatchedCount;
	int i, runLength, runtarget, pattDetectFlg, maxCmprSizeBytes;
    unsigned int u_unmatchedCount;
	int* pCmrData;
	int* startLoc   = pData;
	int* patternLoc = pData;
	pattDetectFlg = 0;
	unmatchedCount = 0;
	unitSizeBytes = 4;
	runtarget = 2;
	*cmprSizeBytes = 0;

	/* Allocate Memory for compressed data stream */
	/* Assume the compressed data will not exceed the original size  */
	/* If expansion does occur, the code that follows will abort out */
	maxCmprSizeBytes = numLongs*unitSizeBytes;
	*outData = (int*)malloc(maxCmprSizeBytes);
	if(*outData == NULL){
		printf("Error allocating memory for compressed data stream\n");
		return -1;
	}
	pCmrData = *outData;


	/* While data exists, continue to attempt compression */
	while(numLongs > 0){

	    /* For patterns, look for a run of at least 2   */
		/* Then determine how long the pattern runs for */
		i = 1;
		
        if( (numLongs >= runtarget) && 
            ( ((runtarget == 2) && (*patternLoc == *(patternLoc+i))) ||
            ( ((runtarget == 3) && (*patternLoc == *(patternLoc+i)) && (*patternLoc == *(patternLoc+i+1))) )) ){

			numLongs-= runtarget;
			i+=runtarget-1; 
			runLength = runtarget-2;
			runtarget = 2;
			pattDetectFlg = 1;

			while((numLongs > 0) && (runLength < MAX_S_LONG)){
				if(*patternLoc == *(patternLoc+i)){
					i++;
					runLength++;
					numLongs--;
				}
				else
					break;
			}
		}


		/* If a pattern was found, write out unmatched data to the */
		/* compression stream, followed by the pattern data        */
		if(pattDetectFlg){
			pattDetectFlg = 0;

			/* Compression Stream - Unmatched Data */
			if(startLoc != patternLoc){
				u_unmatchedCount = (unsigned int)(-1*unmatchedCount);
				*cmprSizeBytes += u_unmatchedCount*unitSizeBytes + unitSizeBytes;
				if(*cmprSizeBytes > maxCmprSizeBytes){
					printf("Error in compression, expansion occurred.\n");
					return -1;
				}

				swap32(&unmatchedCount);
				memcpy(pCmrData,&unmatchedCount,unitSizeBytes);           pCmrData++;
				memcpy(pCmrData,startLoc,u_unmatchedCount*unitSizeBytes); pCmrData+=u_unmatchedCount;
				unmatchedCount = 0;
			}

			/* Compression Stream - Pattern Data */
			*cmprSizeBytes += (unitSizeBytes*2);
			if(*cmprSizeBytes > maxCmprSizeBytes){
				printf("Error in compression, expansion occurred.\n");
				return -1;
			}

			swap32(&runLength);
			memcpy(pCmrData,&runLength,unitSizeBytes);   pCmrData++;
			pattern = *patternLoc;
			memcpy(pCmrData,&pattern,unitSizeBytes);     pCmrData++;

			patternLoc += i;
			startLoc = patternLoc;
		}
		else{

			/* No new pattern was found on this comparison */
			numLongs--;
			patternLoc++;

            /* If the number of unmatched units exceeds the maximum allowed */
            /* then write that data to the output stream now */
			unmatchedCount--;
			if(unmatchedCount == MIN_S_LONG){
				u_unmatchedCount = (unsigned int)(-1*(unmatchedCount+(int)1)) + 1;
				*cmprSizeBytes += u_unmatchedCount*unitSizeBytes + unitSizeBytes;
				if(*cmprSizeBytes > maxCmprSizeBytes){
					printf("Error in compression, expansion occurred.\n");
					return -1;
				}

		        swap32(&unmatchedCount);
	       	    memcpy(pCmrData,&unmatchedCount,unitSizeBytes);           pCmrData++;
		        memcpy(pCmrData,startLoc,u_unmatchedCount*unitSizeBytes); pCmrData+=u_unmatchedCount;
   			    startLoc = patternLoc;
				unmatchedCount = 0;
				runtarget = 2;
			}
			else if(unmatchedCount == (MIN_S_LONG+1))
                runtarget = 2;
			else
                runtarget = 3;
		}
	}

	/* Write out any remaining unmatched data to the compression stream */
	if(startLoc != patternLoc){
		u_unmatchedCount = (unsigned int)(-1*unmatchedCount);
		*cmprSizeBytes += u_unmatchedCount*unitSizeBytes + unitSizeBytes;
		if(*cmprSizeBytes > maxCmprSizeBytes){
			printf("Error in compression, expansion occurred.\n");
			return -1;
		}
		swap32(&unmatchedCount);
		memcpy(pCmrData,&unmatchedCount,unitSizeBytes);           pCmrData++;
		memcpy(pCmrData,startLoc,u_unmatchedCount*unitSizeBytes); pCmrData+=u_unmatchedCount;
	}

	return 0;
}