PCX 多平面 RLE 解码为什么要先还原整行再拆分平面

10-10 6阅读

PCX 多平面 RLE 解码为什么要先还原整行再拆分平面

配图为AI模型独立生成的概念示意图,不是软件截图。

PCX 解码时,单色图片正常、多平面图片却出现错色或提前结束,值得先检查 RLE 的结束条件。正确的逻辑单位是一条完整扫描行:先展开 NPlanes × BytesPerLine 字节,再按平面步长切分。平面切换时不能丢弃尚未输出完的重复字节。

先分清存储边界与压缩边界

ZSoft 原厂技术手册 Revision 4 的 Packetizer 存档在“Decoding .PCX Files”一节给出了上述整行长度,并说明扫描行结束处有解码断点,行内平面边界没有这种保证。这里引用的是原厂文档的存档副本,不是现行厂商官网。

BytesPerLine 表示一个平面的一行占用多少未压缩字节,包含右侧填充。它既不是图片宽度,也不是整行所有平面的总长度。必须先验证头部的步长足以容纳像素,再使用该步长定位各个平面。

四个字节就能复现错误

设三个平面的步长均为二字节,压缩数据为 C3 11 C3 22。高两位为一的标记使用低六位表示重复次数,因此展开结果是 11 11 | 11 22 | 22 22,竖线表示平面边界。

第一个游程输出三个 11,自然跨过第一个平面的末尾。若每次只允许解码二字节,要么误报越界,要么截掉剩余的一个字节,导致后面平面整体错位。测试必须使用这种跨界输入;只测各平面恰好独立结束的文件,很容易漏掉错误。

完整 Python 实现

将下面两段代码依次保存为 test.py,执行 python3 test.py -v。只需标准库。函数读取完整 PCX 字节串,返回头部信息、保留填充的逐行平面数据,以及图像数据结束偏移;它处理原始平面,不负责调色板和全部颜色模式的解释。

代码限定每平面一、二、四或八位,以及一至四个平面;这是本实现的支持范围。它拒绝过短文件头、非法尺寸、不足或奇数步长、截断游程和跨扫描行游程,并在分配输出前限制解压数据量。零长度标记 C0 采用直接拒绝的严格策略。

"""PCX planar RLE tutorial. Run: python3 test.py -v"""
import struct
import unittest


def decode_pcx(data, max_output=64 * 1024 * 1024):
    """Return (metadata, padded plane rows, first byte after image data)."""
    if not isinstance(data, bytes):
        raise TypeError("data must be bytes")
    if type(max_output) is not int or max_output <= 0:
        raise ValueError("invalid output limit")
    if len(data) < 128:
        raise ValueError("truncated header")
    if data[0] != 10 or data[1] not in (0, 2, 3, 4, 5):
        raise ValueError("unsupported PCX header")
    if data[2] != 1:
        raise ValueError("only RLE encoding is supported")
    bits, planes = data[3], data[65]
    if bits not in (1, 2, 4, 8) or not 1 <= planes <= 4:
        raise ValueError("unsupported planar layout")
    xmin, ymin, xmax, ymax = struct.unpack_from("<4H", data, 4)
    if xmax < xmin or ymax < ymin:
        raise ValueError("invalid dimensions")
    width, height = xmax - xmin + 1, ymax - ymin + 1
    stride = struct.unpack_from("<H", data, 66)[0]
    used = (width * bits + 7) // 8
    if stride == 0 or stride % 2 or stride < used:
        raise ValueError("invalid BytesPerLine")
    row_size = planes * stride
    if row_size * height > max_output:
        raise ValueError("decoded image exceeds output limit")
    rows, pos = [], 128
    for y in range(height):
        row = bytearray()
        while len(row) < row_size:
            if pos >= len(data):
                raise ValueError(f"truncated row {y}")
            value = data[pos]
            pos += 1
            count = 1
            if value & 0xC0 == 0xC0:
                count = value & 0x3F
                if count == 0:
                    raise ValueError("zero-length RLE run")
                if pos >= len(data):
                    raise ValueError("missing RLE value")
                value = data[pos]
                pos += 1
            if count > row_size - len(row):
                raise ValueError(f"RLE run crosses row {y}")
            row.extend(bytes([value]) * count)
        rows.append(tuple(bytes(row[p * stride:(p + 1) * stride])
                          for p in range(planes)))
    meta = {"width": width, "height": height, "bits": bits,
            "planes": planes, "stride": stride}
    return meta, rows, pos

边界测试

测试同时覆盖跨一个平面、跨全部平面、填充裁剪、转义字节、六十三次重复、低位深平面,以及两行之间的边界。尤其注意:跨平面应成功,跨扫描行应失败。尾部保留测试验证解码器按声明高度停止,不会继续把附加数据当成像素。

def fixture(payload, width=2, height=1, bits=8, planes=3, stride=2):
    header = bytearray(128)
    header[:4] = bytes([10, 5, 1, bits])
    struct.pack_into("<4H", header, 4, 0, 0, width - 1, height - 1)
    header[65] = planes
    struct.pack_into("<H", header, 66, stride)
    return bytes(header) + payload


class PcxTests(unittest.TestCase):
    def test_run_crosses_plane(self):
        _, rows, end = decode_pcx(fixture(b"\xC3\x11\xC3\x22"))
        self.assertEqual(rows, [(b"\x11\x11", b"\x11\x22", b"\x22\x22")])
        self.assertEqual(end, 132)

    def test_one_run_spans_all_planes(self):
        _, rows, _ = decode_pcx(fixture(b"\xC6\x7F"))
        self.assertEqual(rows, [(b"\x7F\x7F",) * 3])

    def test_padding_preserved_rgb_crop(self):
        meta, rows, _ = decode_pcx(fixture(b"\x10\xAA\x20\xBB\x30\x99", width=1))
        self.assertEqual(rows[0], (b"\x10\xAA", b"\x20\xBB", b"\x30\x99"))
        rgb = bytes(v for pixel in zip(*(p[:meta["width"]] for p in rows[0]))
                    for v in pixel)
        self.assertEqual(rgb, b"\x10\x20\x30")

    def test_rows_and_trailing_data(self):
        blob = fixture(b"\xC6\x01\xC6\x02TAIL", height=2)
        _, rows, end = decode_pcx(blob)
        self.assertEqual(rows, [(b"\x01\x01",) * 3, (b"\x02\x02",) * 3])
        self.assertEqual(blob[end:], b"TAIL")

    def test_literal_escape_and_max_run(self):
        _, rows, _ = decode_pcx(fixture(b"\xC1\xC0\x01", planes=1))
        self.assertEqual(rows, [(b"\xC0\x01",)])
        _, rows, _ = decode_pcx(fixture(b"\xFF\x07\x08", width=64, planes=1, stride=64))
        self.assertEqual(rows, [(b"\x07" * 63 + b"\x08",)])

    def test_low_bit_planes(self):
        _, rows, _ = decode_pcx(fixture(b"\xC8\x00", width=9, bits=1, planes=4))
        self.assertEqual(rows, [(b"\x00\x00",) * 4])

    def test_bad_streams(self):
        cases = [(b"", "truncated row"), (b"\x01", "truncated row"),
                 (b"\xC6", "missing RLE value"),
                 (b"\xC0\x00", "zero-length"),
                 (b"\xC7\x00", "crosses row")]
        for payload, message in cases:
            with self.subTest(payload=payload), self.assertRaisesRegex(ValueError, message):
                decode_pcx(fixture(payload))

    def test_run_cannot_continue_into_next_row(self):
        with self.assertRaisesRegex(ValueError, "crosses row"):
            decode_pcx(fixture(b"\xCC\x00", height=2))

    def test_bad_headers(self):
        for offset, value in ((0, 0), (1, 1), (2, 0), (3, 3), (65, 0), (65, 5)):
            blob = bytearray(fixture(b"\xC6\x00"))
            blob[offset] = value
            with self.subTest(offset=offset, value=value), self.assertRaises(ValueError):
                decode_pcx(bytes(blob))
        with self.assertRaisesRegex(ValueError, "truncated header"):
            decode_pcx(b"\x00" * 127)

    def test_invalid_dimensions(self):
        for offset in (4, 6):
            blob = bytearray(fixture(b"\xC6\x00"))
            struct.pack_into("<H", blob, offset, 10)
            with self.subTest(offset=offset), self.assertRaisesRegex(ValueError, "dimensions"):
                decode_pcx(bytes(blob))

    def test_invalid_stride(self):
        for stride in (0, 1, 3):
            with self.subTest(stride=stride), self.assertRaisesRegex(ValueError, "BytesPerLine"):
                decode_pcx(fixture(b"", stride=stride))
        with self.assertRaisesRegex(ValueError, "BytesPerLine"):
            decode_pcx(fixture(b"", width=3, stride=2))

    def test_limits_and_input_types(self):
        blob = fixture(b"\xC6\x00")
        with self.assertRaisesRegex(ValueError, "output limit"):
            decode_pcx(blob, max_output=5)
        self.assertEqual(decode_pcx(blob, max_output=6)[2], 130)
        for limit in (0, -1, True, 6.0):
            with self.subTest(limit=limit), self.assertRaises(ValueError):
                decode_pcx(blob, max_output=limit)
        with self.assertRaises(TypeError):
            decode_pcx(bytearray(blob))


if __name__ == "__main__":
    unittest.main()

运行结果与接入提醒

本次在 Python 3.12.14 环境实际运行上述完整文件,结果为 Ran 12 tests、OK。这些是包含多组子用例的合成边界测试,不代表已覆盖所有历史 PCX 变体。

对八位三平面 RGB,先分别取每个平面的前 width 字节,再交错成 RGB;低位深数据还需要逐位解包。不要只删除整行末尾的填充,否则前两个平面的填充仍会混入像素。返回偏移后的调色板等内容应交给下一层单独校验,成功展开像素不等于验证了整个文件。

如果需要流式输出,也可以逐平面填充目标缓冲区,但必须跨平面保留游程的剩余次数和字节值,同时坚持扫描行边界检查。整行缓存只是最容易审查的实现方式。这里的六十四 MiB 上限限制的是解压字节量,并非 Python 对象的总内存。

可对照 Pillow 的 PCX 解码源码:它在行缓冲区填满后进行像素转换;对应插件源码将平面数乘以步长传给解码器。两者可辅助理解处理层次,本文严格校验策略不宣称与 Pillow 的兼容性策略相同。

文章版权声明:除非注明,否则均为云鹊BLOG原创文章,转载或复制请以超链接形式并注明出处。