4 * Copyright 2004 Develer S.r.l. (http://www.develer.com/)
5 * Copyright 1999, 2000, 2001 Bernardo Innocenti <bernie@develer.com>
6 * This file is part of DevLib - See devlib/README for information.
9 * \brief General-purpose run-length {en,de}coding algorithm (implementation)
11 * Original source code from http://www.compuphase.com/compress.htm
14 * \author Bernardo Innocenti <bernie@develer.com>
19 * Revision 1.1 2004/08/04 02:35:54 bernie
20 * Import simple RLE algorithm.
28 * Run-length encode \a len bytes from the \a input buffer
29 * to the \a output buffer.
31 int rle(unsigned char *output, const unsigned char *input, int len)
43 first = input[index++];
45 /* Scan for bytes identical to the first one */
46 while ((index < len) && (index - count < 127) && (input[index] == first))
49 if (index - count == 1)
51 /* Failed to "replicate" the current byte. See how many to copy.
53 while ((index < len) && (index - count < 127))
55 /* Avoid a replicate run of only 2-bytes after a literal run.
56 * There is no gain in this, and there is a risc of loss if the
57 * run after the two identical bytes is another literal run.
58 * So search for 3 identical bytes.
60 if ((input[index] == input[index - 1]) &&
61 ((index > 1) && (input[index] == input[index - 2])))
63 /* Reset the index so we can back up these three identical
64 * bytes in the next run.
73 /* Output a run of uncompressed bytes: write length and values */
74 *out++ = (unsigned char)(count - index);
75 for (i = count; i < index; i++)
80 /* Output a compressed run: write length and value */
81 *out++ = (unsigned char)(index - count);
88 /* Output EOF marker */
91 return (out - output);
96 * Run-length decode from the \a input buffer to the \a output
99 * \note The output buffer must be large enough to accomodate
100 * all decoded output.
102 int unrle(unsigned char *output, const unsigned char *input)
113 count = (signed char)*input++;
132 return (out - output);