我正在编写一个 C 库来将 SDL_Surfaces 导出为各种格式作为练习,到目前为止,我已经掌握了 BMP、TGA 和 PCX 格式。现在我正在研究 GIF 格式,我觉得我非常接近让它工作。我的实现是这个的修改版本。
我目前的问题是编写 GIF LZW 压缩图像数据子块。一切顺利,直到第一个子块中的位置 208。原始文件中的三个字节是(从位置 207 开始):十六进制的“B8 29 B2”,我的是“B8 41 B2”。之后,字节再次“同步”。在压缩流的下方,我可以找到类似的差异,这可能是由第一个错误引起的。我的文件也比原来的短。
我应该注意,我将 lzw_entry 结构的类型从 uint16_t 更改为 int 以允许 -1 作为“空”条目,因为 0 是有效条目。不过,它并没有真正对压缩流产生影响。最初的实现使用未初始化的数据来标记一个空条目。
我想我读错了我的字典值,这就是为什么我得到的位置 208 的另一个代码比预期的要好。否则,我的位打包不正确。
我添加了压缩代码的精简版本。可能是什么问题?另外,我如何才能使我的“字典”数据结构更好或使比特流写入更快?
最后,我也知道我可以在这里和那里优化一些代码:)
static Uint8 bit_count = 0;
static Uint8 block_pos = 0;
int LZW_PackBits(SDL_RWops *dst, Uint8 *block, int code, Uint8 bits) {
Uint8 out = 0;
while (out != bits) {
if (bit_count == 8) {
bit_count = 0;
if (block_pos == 254) { // Thus 254 * 8 + 8 == 2040 -> 2040 / 8 = 255 -> buffer full
++block_pos;
SDL_RWwrite(dst, &block_pos, 1, 1);
SDL_RWwrite(dst, &block[0], 1, block_pos);
memset(block, 0, block_pos);
block_pos = 0;
} else
++block_pos;
}
block[block_pos] |= (code >> out & 0x1) << bit_count;
++bit_count; ++out;
}
return 1;
}
#define LZW_MAX_BITS 12
#define LZW_START_BITS 9
#define LZW_CLEAR_CODE 256
#define LZW_END_CODE 257
#define LZW_ALPHABET_SIZE 256
typedef struct {
int next[LZW_ALPHABET_SIZE]; // int so that -1 is allowed
} lzw_entry;
int table_size = 1 << LZW_MAX_BITS; // 2^12 = 4096
lzw_entry *lzw_table = (lzw_entry*)malloc(sizeof(lzw_entry) * table_size);
for (i = 0; i < table_size; ++i)
memset(&lzw_table[i].next[0], -1, sizeof(int) * LZW_ALPHABET_SIZE);
Uint8 block[255];
memset(&block[0], 0, 255);
Uint16 next_entry = LZW_END_CODE + 1;
Uint8 out_len = LZW_START_BITS;
Uint8 next_byte = 0;
int input = 0;
int nc = 0;
LZW_PackBits(dst, block, clear_code, out_len);
Uint8 *pos = ... // Start of image data
Uint8 *end = ... // End of image data
input = *pos++;
while (pos < end) {
next_byte = *pos++;
nc = lzw_table[input].next[next_byte];
if (nc >= 0) {
input = nc;
continue;
} else {
LZW_PackBits(dst, block, input, out_len);
nc = lzw_table[input].next[next_byte] = next_entry++;
input = next_byte;
}
if (next_entry == (1 << out_len)) { // Next code requires more bits
++out_len;
if (out_len > LZW_MAX_BITS) {
// Reset table
LZW_PackBits(dst, block, clear_code, out_len - 1);
out_len = LZW_START_BITS;
next_entry = LZW_END_CODE + 1;
for (i = 0; i < table_size; ++i)
memset(&lzw_table[i].next[0], -1, sizeof(int) * LZW_ALPHABET_SIZE);
}
}
}
// Write remaining stuff including current code (not shown)
LZW_PackBits(dst, block, end_code, out_len);
++block_pos;
SDL_RWwrite(dst, &block[0], 1, block_pos);
SDL_RWwrite(dst, &zero_byte, 1, 1);
const Uint8 trailer = 0x3b; // ';'
SDL_RWwrite(dst, &trailer, 1, 1);
更新:我做了更多的测试,并实现了 Aki Suihkonen 建议的位打包算法。它没有明显的区别,它告诉我我在我的 lzw_table 结构中以某种方式错误地查找/存储代码,并且错误在主循环中。