summaryrefslogtreecommitdiff
path: root/support/dktools/dk4lzwe.ctr
blob: d38a83fbd8ae64eb9cbe2fd922f0dc7530d8b30d (plain)
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
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
%%	options

copyright owner	=	Dirk Krause
copyright year	=	2016-xxxx
license			=	bsd

%%	header

/**	@file	dk4lzwe.h	LZW encoder to produce PS level 2 output.

- The unit length (input data length) is 8 bits.
- Code 256 is used for table cleanup, 257 is the end of data marker.
- EarlyChange is in use: the number of bits per code is increased after
  creating table entries for codes 511, 1023 and 2047.
- Table entries are created for codes up to 4093. Instead of generating
  an entry for 4094, the table is cleared.
*/

#ifndef DK4ERROR_H_INCLUDED
#include <dk4error.h>
#endif

#ifndef	DK4BITSH_H_INCLUDED
#include <dk4bitsh.h>
#endif



/**	Table size.
	The table must be large enough to keep 4096 entries. Adding
	25 percent size significantly decreases the number of lookups.
	A prime number is required to ensure traversal of the entire
	table if necessary.
*/
enum {
	LZW_TABLE_SIZE = 5147	/**< Size of LZW compression table. */
};



/**	One table entry for LZW compression.
*/
typedef struct {
	unsigned short	os;		/**< Current (old) state or code. */
	unsigned short	ns;		/**< New state after applying input. */
	unsigned char	in;		/**< Input byte. */
} dk4_lzw_cell_t;



/**	LZW encoder structure.
*/
typedef struct {
	unsigned char	 ob[8];	/**< Output buffer. */
	dk4_bit_shift_t	 bs;	/**< Bit shifter. */
	dk4_lzw_cell_t	*p_tbl;	/**< Pointer to dynamically allocated table. */
	size_t			 obu;	/**< Used bytes in output buffer. */
	int				 mret;	/**< Flag: Must retrieve output data. */
	int				 hst;	/**< Flag: Have internal state. */
	unsigned short	 bits;	/**< Number of bits to use for output. */
	unsigned short	 cs;	/**< Current state. */
	unsigned short	 ns;	/**< Next state for new table entry. */
} dk4_lzwe_t;

#ifdef	__cplusplus
extern "C" {
#endif


/**	Initialize LZW encoder, allocate memory for resources.
	@param	lzwptr	Encoder to initialize.
	@param	erp		Error report, may be NULL.
	@return	1 on success, 0 on error.

	Error codes:
	- DK4_E_INVALID_ARGUMENTS<br>
	  if lzwptr is NULL,
	- DK4_E_MATH_OVERFLOW<br>
	  on numeric overflow when calculating the
	  product of elsize and nelem,
	- DK4_E_MEMORY_ALLOCATION_FAILED<br>
	  with mem.elsize and mem.nelem
	  set if there is not enough memory available,
	- DK4_E_BUG<br>
	  if the dk4bit_shift_add() call indicates an error
	  (should not happen as we provide a valid address to the function),
	- DK4_E_BUFFER_TOO_SMALL<br>
	  if the output buffer is already full. Typically this means
	  that output was not retrieved as expected by the library.
*/

int
dk4lzwe_init(
	dk4_lzwe_t	*lzwptr,
	dk4_er_t	*erp
);


/**	Add one byte to the encoder.
	@param	lzwptr	Encoder to use.
	@param	uc		Byte to add.
	@param	erp		Error report, may be NULL.
	@return	Operation result, one from:
	- DK4_EDSTM_ACCEPT<br>
	  if the input byte was successfully stored in the internal data
	  structures without completing a run. No further action
	  necessary.
	- DK4_EDSTM_FINISHED<br>
	  if output was created. Use dk4lzwe_output() to obtain the
	  output data.
	- DK4_EDSTM_ERROR<br>
	  if an error occured.
*/

int
dk4lzwe_add(
	dk4_lzwe_t		*lzwptr,
	unsigned char	 uc,
	dk4_er_t		*erp
);


/**	Finish encoded data stream, flush internal state and bits from
	the bit shifter to output buffer and release dynamic memory.
	@param	lzwptr	Encoder to use.
	@param	erp		Error report, may be NULL.
	@return	Operation result, one from:
	- DK4_EDSTM_ACCEPT<br>
	  if the input byte was successfully stored in the internal data
	  structures without completing a run. No further action
	  necessary.
	- DK4_EDSTM_FINISHED<br>
	  if output was created. Use dk4lzwe_output() to obtain the
	  output data.
	- DK4_EDSTM_ERROR<br>
	  if an error occured.
	
	Error codes:
	- DK4_E_INVALID_ARGUMENTS<br>
	  if lzwptr is NULL or lzwptr->s_tbl or lzwptr->i_tbl is NULL,
	- DK4_E_BUG<br>
	  if the dk4bit_shift_add() call indicates an error
	  (should not happen as we provide a valid address to the function),
	- DK4_E_BUFFER_TOO_SMALL<br>
	  if the output buffer is already full. Typically this means
	  that output was not retrieved as expected by the library.
*/

int
dk4lzwe_finish(
	dk4_lzwe_t		*lzwptr,
	dk4_er_t		*erp
);


/**	Retrieve output from encoder.
	@param	dptr	Address of result pointer.
	@param	szptr	Address of result size variable.
	@param	lzwptr	Encoder to use.
	@param	erp		Error report, may be NULL.
	@return	1 if data available, 0 otherwise.
*/

int
dk4lzwe_output(
	const unsigned char	**dptr,
	size_t				 *szptr,
	dk4_lzwe_t			 *lzwptr,
	dk4_er_t			 *erp
);


#ifdef	__cplusplus
}
#endif

/* vim: set ai sw=4 ts=4 : */
%%	module


#include "dk4lzwe.h"
#include "dk4mem.h"
#include "dk4edstm.h"



$!trace-include



/**	Code to clear tables.
*/
#define	LZW_CLT		((unsigned short)256U)



/**	Code to indicate end of data.
*/
#define	LZW_EOD		((unsigned short)257U)



/**	First user-made state.
*/
#define	LZW_START	((unsigned short)258U)



/**	Bitmask values.
*/
static const unsigned short	bit_values[]  = {
	0x0001U, 0x0002U, 0x0004U, 0x0008U, 0x0010U, 0x0020U, 0x0040U, 0x0080U,
	0x0100U, 0x0200U, 0x0400U, 0x0800U, 0x1000U, 0x2000U, 0x4000U, 0x8000U
};



/**	Write bit sequence to output buffer.
	@param	lzwptr	LZW compression structure.
	@param	val		Bit sequence to write.
	@param	erp		Error report, may be NULL.
	@return	1 on success, 0 on error.

	Error codes:
	- DK4_E_BUFFER_TOO_SMALL<br>
	  if the output buffer is full before finishing,
	- DK4_E_INVALID_ARGUMENTS<br>
	  should not happen.
*/
static
int
dk4lzwe_shipout(
	dk4_lzwe_t		*lzwptr,
	unsigned short	 val,
	dk4_er_t		*erp
)
{
	int				 back	= 1;
	int				 res;
	unsigned short	 i;
	unsigned char	 uc;
	
	$? "+ dk4lzwe_shipout %u/%u", (unsigned)val, (unsigned)(lzwptr->bits)
	i = lzwptr->bits;
	while (0 < i--) {
		res = dk4bit_shift_add(
			&(lzwptr->bs),
			((((unsigned short)0) != (val & bit_values[i])) ? (1) : (0)),
			NULL
		);
		switch (res) {
			case DK4_EDSTM_ERROR : {			$? "! dk4bit_shift_add"
				back = 0;
				dk4error_set_simple_error_code(erp, DK4_E_BUG);
			} break;
			case DK4_EDSTM_FINISHED : {			$? ". byte completed"
				uc = dk4bit_shift_output(&(lzwptr->bs), NULL);
				if (8 > lzwptr->obu) {			$? ". saved to buffer"
					lzwptr->ob[lzwptr->obu] = uc;
					lzwptr->obu += 1;
				}
				else {							$? "! buffer full"
					back = 0;
					dk4error_set_simple_error_code(erp, DK4_E_BUFFER_TOO_SMALL);
				}
			} break;
		}
	}
	$? "- dk4lzwe_shipout %d", back
	return back;
}



/**	Clear all table entries.
	@param	lzwptr	Encoder to clean up.
*/
static
void
dk4lzwe_clear_table_entries(
	dk4_lzwe_t	*lzwptr
)
{
	dk4_lzw_cell_t	*cptr;
	size_t			 i;
	$? "+ dk4lzwe_clear_table_entries"
	cptr = lzwptr->p_tbl;
	for (i = 0; i < LZW_TABLE_SIZE; i++) {
		cptr[i].os = (unsigned short)0U;
		cptr[i].ns = (unsigned short)0U;
		cptr[i].in = (unsigned char)0x00;
	}
	$? "- dk4lzwe_clear_table_entries"
}



int
dk4lzwe_init(
	dk4_lzwe_t	*lzwptr,
	dk4_er_t	*erp
)
{
	int		 back	= 0;
	$? "+ dk4lzwe_init %d", TR_IPTR(lzwptr)
	if (NULL != lzwptr) {					$? ". lzwptr"
		/*
			Default values for al components
		*/
		dk4mem_reset(lzwptr, sizeof(dk4_lzwe_t), NULL);
		lzwptr->p_tbl	= NULL;
		lzwptr->obu		= 0;
		lzwptr->mret	= 0;
		lzwptr->hst		= 0;
		lzwptr->bits	= 9;
		lzwptr->cs		= 0U;
		lzwptr->ns		= LZW_START;
		dk4bit_shift_init(&(lzwptr->bs), NULL);
		/*
			Allocate memory for state transition table
		*/
		lzwptr->p_tbl	= dk4mem_new(dk4_lzw_cell_t,LZW_TABLE_SIZE,erp);
		/*
			On success ship out initial clear table marker
		*/
		if (NULL != lzwptr->p_tbl) {		$? ". p_tbl"
			dk4lzwe_clear_table_entries(lzwptr);
			back = dk4lzwe_shipout(lzwptr, LZW_CLT, erp);
		}
#if	TRACE_DEBUG
		else {								$? "! p_tbl"
		}
#endif
	}
	else {									$? "! lzwptr"
		dk4error_set_simple_error_code(erp, DK4_E_INVALID_ARGUMENTS);
	}
	$? "- dk4lzwe_init %d", back
	return back;
}



static
int
dk4lzwe_i_add(
	dk4_lzwe_t		*lzwptr,
	unsigned char	 uc,
	dk4_er_t		*erp
)
{
	int				 back	= DK4_EDSTM_ERROR;
#if	TRACE_DEBUG
	int				 passno	= 0;
#endif
	int				 cc;
	int				 found;
	unsigned short	 ind;
	unsigned short	 offs;
	$? "+ dk4lzwe_i_add"
	if (0 != lzwptr->hst) {								$? ". already input"
		/*
			Already input available, so we have to check the table
			for a matching rule
		*/
		ind =	(lzwptr->cs)
				^ ((((unsigned short)uc) << 4) & ((unsigned short)0x0FF0U));
#if 0
		ind = ind % LZW_TABLE_SIZE;
#endif
		offs = ((((unsigned short)0U) != ind) ? (LZW_TABLE_SIZE - ind) : (1));
		cc = 1;
		found = 0;										$? ". start loop"
		do {											$? ". new pass"
			if ((unsigned short)0U != (lzwptr->p_tbl)[ind].ns) {	$? ". rule"
				if (lzwptr->cs == (lzwptr->p_tbl)[ind].os) {
					if (uc == (lzwptr->p_tbl)[ind].in) {
						found = 1;						$? ". matching rule"
					}
				}
				if (0 != found) {
					cc = 0;
				}
				else {									$? ". next rule"
					ind += offs;
					ind = (ind % LZW_TABLE_SIZE);
				}
			}
			else {										$? ". empty rule"
				cc = 0;
			}
#if	TRACE_DEBUG
			passno++;
#endif
		} while (0 < cc);								$? ". loop finished"
#if	TRACE_DEBUG
		$? ". passes=%d", passno
#endif
		if (0 != found) {								$? ". rule found"
			/*
				A matching rule was found, so we just change state.
			*/
			lzwptr->cs = (lzwptr->p_tbl)[ind].ns;
			back = DK4_EDSTM_ACCEPT;
		}
		else {											$? ". no rule found"
			/*	No matching rule was found.
				We check whether or not we can add further entries to
				the table.
			*/
			if ((unsigned short)4094U <= lzwptr->ns) {	$? ". table full, clean"
				/*
					Table is full, so we ship out the current state,
					clean we table and keep the input as new current state.
				*/
				if (0 != dk4lzwe_shipout(lzwptr, lzwptr->cs, erp)) {
					if (0 != dk4lzwe_shipout(lzwptr, LZW_CLT, erp)) {
						back =  DK4_EDSTM_FINISHED;		$? ". shipout ok"
						lzwptr->mret = 1;
					}
				}
				lzwptr->cs = (((unsigned short)0x00FFU) & ((unsigned short)uc));
				lzwptr->bits = 9;
				lzwptr->ns = LZW_START;
				dk4lzwe_clear_table_entries(lzwptr);
			}
			else {										$? ". add rule"
				/*	There is still room in the table.
					Ship out current state, create new rule in the
					table and keep input as new current state.
				*/
				if (0 != dk4lzwe_shipout(lzwptr, lzwptr->cs, erp)) {
					back = DK4_EDSTM_FINISHED;			$? ". shipout ok"
					lzwptr->mret = 1;
				}
				(lzwptr->p_tbl)[ind].os = lzwptr->cs;
				(lzwptr->p_tbl)[ind].ns = lzwptr->ns;
				(lzwptr->p_tbl)[ind].in = uc;
				$? ". rule %u, %u => %u", (unsigned)((lzwptr->p_tbl)[ind].os), (unsigned)((lzwptr->p_tbl)[ind].in), (unsigned)((lzwptr->p_tbl)[ind].ns)
				/*
					Increase number of bits if necessary.
				*/
				switch ( (int)(lzwptr->ns) ) {
					case 511 : {						$? ". bits=10"
						lzwptr->bits = 10;
					} break;
					case 1023 : {
						lzwptr->bits = 11;				$? ". bits=11"
					} break;
					case 2047 : {
						lzwptr->bits = 12;				$? ". bits=12"
					} break;
				}
				lzwptr->ns += 1U;
				lzwptr->cs = (((unsigned short)0x00FFU) & ((unsigned short)uc));
			}
		}
	}
	else {												$? ". no input yet"
		/*	No current state yet (no input yet).
			Just store the input as current state.
		*/
		lzwptr->cs	= (((unsigned short)0x00FFU) & ((unsigned short)uc));
		lzwptr->hst	= 1;
		back		= DK4_EDSTM_ACCEPT;
	}
	$? "- dk4lzwe_i_add %d", back
	return back;
}



int
dk4lzwe_add(
	dk4_lzwe_t		*lzwptr,
	unsigned char	 uc,
	dk4_er_t		*erp
)
{
	int		 back	= DK4_EDSTM_ERROR;
	$? "+ dk4lzwe_add"
	if (NULL != lzwptr) {
		if (NULL != lzwptr->p_tbl) {
			if (0 == lzwptr->mret) {
				back = dk4lzwe_i_add(lzwptr, uc, erp);
			}
			else {
				dk4error_set_simple_error_code(erp, DK4_E_INVALID_ARGUMENTS);
			}
		}
		else {
			dk4error_set_simple_error_code(erp, DK4_E_INVALID_ARGUMENTS);
		}
	}
	else {
		dk4error_set_simple_error_code(erp, DK4_E_INVALID_ARGUMENTS);
	}
	$? "- dk4lzwe_add %d", back
	return back;
}



int
dk4lzwe_finish(
	dk4_lzwe_t		*lzwptr,
	dk4_er_t		*erp
)
{
	int		 		back	= DK4_EDSTM_ERROR;
	unsigned char	uc;
	$? "+ dk4lzwe_finish"
	if (NULL != lzwptr) {
		if (NULL != lzwptr->p_tbl) {
			if (0 == lzwptr->mret) {
				back = DK4_EDSTM_ACCEPT;
				/*
					Ship out current state, if any.
				*/
				if (0 != lzwptr->hst) {				$? ". have input"
					if (0 == dk4lzwe_shipout(lzwptr, lzwptr->cs, erp)) {
						back = DK4_EDSTM_ERROR;		$? "! shipout"
					}
				}
				/*	Ship out end of data marker.
				*/
				if (0 == dk4lzwe_shipout(lzwptr, LZW_EOD, erp)) {
					back = DK4_EDSTM_ERROR;			$? "! shipout"
				}
				/*	Apply final byte from bit shifter to output.
				*/
				switch ( dk4bit_shift_finish(&(lzwptr->bs), erp)) {
					case DK4_EDSTM_ERROR : {
						back = DK4_EDSTM_ERROR;		$? "! bug"
					} break;
					case DK4_EDSTM_FINISHED : {
						uc = dk4bit_shift_output(&(lzwptr->bs), NULL);
						if (8 > lzwptr->obu) {		$? ". shipout"
							lzwptr->ob[lzwptr->obu] = uc;
							lzwptr->obu += 1;
						}
						else {						$? "! shipout"
							back = DK4_EDSTM_ERROR;
							dk4error_set_simple_error_code(
								erp, DK4_E_BUFFER_TOO_SMALL
							);
						}
					} break;
				}
				/*	Check whether the caller must retrieve final output.
				*/
				if ((DK4_EDSTM_ACCEPT == back) && (0 < lzwptr->obu)) {
					back = DK4_EDSTM_FINISHED;		$? ". output available"
					lzwptr->mret = 1;
				}
			}
			else {
				dk4error_set_simple_error_code(erp, DK4_E_INVALID_ARGUMENTS);
			}
			dk4mem_free(lzwptr->p_tbl);
			lzwptr->p_tbl = NULL;
		}
		else {
			dk4error_set_simple_error_code(erp, DK4_E_INVALID_ARGUMENTS);
		}
	}
	else {
		dk4error_set_simple_error_code(erp, DK4_E_INVALID_ARGUMENTS);
	}
	$? "- dk4lzwe_finish %d", back
	return back;
}



int
dk4lzwe_output(
	const unsigned char	**dptr,
	size_t				 *szptr,
	dk4_lzwe_t			 *lzwptr,
	dk4_er_t			 *erp
)
{
	int		 back	= 0;
	$? "+ dk4lzwe_output"
	if ((NULL != dptr) && (NULL != szptr) && (NULL != lzwptr)) {
		/*
			All arguments ok, do normal output operation.
		*/
		*dptr  = &(lzwptr->ob[0]);
		*szptr = lzwptr->obu;
		back   = ((0 < lzwptr->obu) ? (1) : (0));
		lzwptr->mret = 0;			$? ". args"
		lzwptr->obu = 0;
	}
	else {							$? "! args"
		/*
			Argument error, indicate no data available.
		*/
		if (NULL != dptr) {
			*dptr = NULL;
		}
		if (NULL != szptr) {
			*szptr = 0;
		}
		dk4error_set_simple_error_code(erp, DK4_E_INVALID_ARGUMENTS);
	}
	$? "- dk4lzwe_output %d", back
	return back;
}


/* vim: set ai sw=4 ts=4 : */