diff --git a/meshterm/core/mcoimg.py b/meshterm/core/mcoimg.py index 17ba985..e906d16 100644 --- a/meshterm/core/mcoimg.py +++ b/meshterm/core/mcoimg.py @@ -7,9 +7,14 @@ message, it is a prefix and then Base91 text: ``im:`` for the versions 1 and 2, for version 3. A client that does not know the format shows that text as noise. The reference is ``docs/mcoimg_v3_reference.md`` in the HDDen/meshcore-open repository (MIT). -This module does not decode the pixels. It finds that a body is an image, and for a -version 3 image it reads the header: the size and the number of colours of the palette. -Thus the chat can show a short line in place of the noise. +The module has two levels: + +- :func:`recognize` finds that a body is an image, and for a version 3 image it reads the + header: the size and the number of colours of the palette. Thus the chat can show a + short line in place of the noise. It is fast, and it does not decode the pixels. +- :func:`decode` decodes all the pixels of a version 3 image into colours. It knows all + the containers, block algorithms, scan orders, palette profiles, and local palettes of + the reference. It does not decode the versions 1 and 2. Version 3 data, after the Base91 decode:: @@ -18,19 +23,24 @@ Version 3 data, after the Base91 decode:: header: u8 bit 7 transparent, bit 6 white background, bits 5..4 scan, bits 3..0 palette profile dimensions bit-packed, LSB first (refer to :func:`_dimensions`) - ... the pixels, which this module does not read + container: 8 bits bits 7..5 the container, bits 4..0 its context + transparent colour a colour reference, only when header bit 7 is set + container body bit-packed, then zero bits to the end of the last byte + +The palette colours are in :mod:`meshterm.core.mcoimg_palettes`. """ from __future__ import annotations import re from dataclasses import dataclass +from functools import cache +from typing import NamedTuple #: The Base91 alphabet of MCOimg, in the order of its values. It is the alphabet of #: basE91, which has no space, no ``'``, no ``-``, and no ``\\``. _ALPHABET = ( - "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789" - '!#$%&()*+,./:;<=>?@[]^_`{|}~"' + 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!#$%&()*+,./:;<=>?@[]^_`{|}~"' ) _VALUE = {char: index for index, char in enumerate(_ALPHABET)} @@ -136,7 +146,11 @@ def base91_decode(text: str) -> bytes | None: class _Bits: - """A reader of bit fields, LSB first, from a byte string.""" + """A reader of bit fields, LSB first, from a byte string. + + :func:`recognize` uses it. :func:`decode` uses the subclass :class:`_Reader`, which + adds the integer forms of the format. + """ def __init__(self, data: bytes) -> None: self._value = int.from_bytes(data, "little") @@ -181,3 +195,1223 @@ def _dimensions(bits: _Bits) -> tuple[int, int] | None: if width is None or height is None: return None return width + 1, height + 1 + + +@dataclass(frozen=True) +class Picture: + """The decoded pixels of a version 3 image. + + Attributes: + width: The width in pixels, 1 to 256. + height: The height in pixels, 1 to 256. + pixels: The colour of each pixel as (red, green, blue), row by row from the top + left (``pixels[y * width + x]``). ``None`` is a transparent pixel. + """ + + width: int + height: int + pixels: tuple[tuple[int, int, int] | None, ...] + + +def decode(body: str) -> Picture | None: + """Decode the pixels of the version 3 image that ``body`` carries. + + The body must be the image and nothing else, as for :func:`recognize`. The function + does not raise an error. A body that is not a version 3 image, or that has an error at + any point in its data, gives ``None``. The data comes from a stranger on the mesh, so + the decoder also limits its work (refer to :data:`_MAX_TEXT` and :data:`_WORK`). + + Args: + body: The text of a message, without the ``Name: `` of a channel sender. + + Returns: + The picture, or ``None``. + """ + indexed = _decode_refs(body) + if indexed is None: + return None + lookup = _profiles()[indexed.profile].rgb + clear = indexed.transparent + pixels = tuple(None if ref == clear else lookup[ref] for ref in indexed.refs) + return Picture(indexed.width, indexed.height, pixels) + + +class _Indexed(NamedTuple): + """A decoded image before its colours: the palette reference of each pixel. + + For a dynamic profile, a reference is an index in ``GLOBAL_512``. For a fixed profile, + it is a colour id of the profile. These are the numbers of the reference codec and of + its test vectors. + """ + + width: int + height: int + #: The palette profile id, 0 to 15 (refer to :data:`_PROFILE_COLOURS`). + profile: int + #: The references, row by row from the top left. + refs: list[int] + #: The reference that is transparent, or ``None``. + transparent: int | None + + +def _decode_refs(body: str) -> _Indexed | None: + """Decode a version 3 image to palette references, or return ``None`` for any error.""" + try: + return _decode_indexed(body) + except Exception: # noqa: BLE001 - hostile data can fail in many ways. Each one is "no image". + return None + + +class _Bad(Exception): + """The data of an image does not obey a rule of the format.""" + + +#: The longest Base91 text that :func:`decode` reads. A message on the mesh is much +#: shorter. The limit stops a long hostile text before it can make the decode slow. +_MAX_TEXT = 4096 + +#: The work limit of a decode, in pixels for each pixel of the image. Each block that the +#: decoder reads uses the pixels of its rectangle. The regions of a real image do not +#: overlap, so they use one pixel for each pixel of the image. Hostile regions can overlap +#: as much as they want, and this limit stops them. +_WORK = 4 + +#: The block algorithms that use the compact block header: ``rawGlobal`` (0), ``rawLocal`` +#: (1), and ``biColorMask`` (4). They have no scan order, so the scan is always ``h``. +_COMPACT_HEADER = frozenset({0, 1, 4}) + +#: The block algorithms that have a background colour: ``compactSparse`` (3), +#: ``biColorMask`` (4), and ``varUintSparse`` (15). +_WITH_BACKGROUND = frozenset({3, 4, 15}) + +#: The block algorithms that cannot use a shared region palette, because they have no +#: local palette: ``rawGlobal`` (0), ``directBitplanes`` (10), and ``directRowDelta`` (12). +_NO_SHARED_PALETTE = frozenset({0, 10, 12}) + +#: The ids of the grey palette profiles. +_GREY_PROFILES = frozenset({6, 7, 8}) + +#: The marker of a hybrid common header in a regions stream. It is not an algorithm id. +_HYBRID = 31 + +_WHITE = (255, 255, 255) + + +class _Profile(NamedTuple): + """A palette profile of version 3, as the decoder uses it. + + In the decoder, each colour is a colour id of the profile: 0 to ``size - 1``. Only the + last step changes the ids of a dynamic profile into ``GLOBAL_512`` indices. + """ + + size: int + #: The number of bits of one colour id in the data. + bits: int + #: The colour id of white, for the implicit white background. + white: int + grey: bool + #: For a dynamic profile, the ``GLOBAL_512`` index of each colour id. For a fixed + #: profile, ``None``. + table: tuple[int, ...] | None + #: The RGB value of each output reference (refer to :class:`_Indexed`). + rgb: tuple[tuple[int, int, int], ...] + + +@cache +def _profiles() -> tuple[_Profile, ...]: + """The 16 palette profiles, by profile id. + + The import of the colour tables occurs here, at the first decode, and not when the + module loads. Thus the chat can call :func:`recognize` and not load the tables. + """ + from meshterm.core import mcoimg_palettes as tables + + fixed = ( + tables.MONO, + tables.MASTER_4, + tables.MASTER_8, + tables.MASTER_16, + tables.MASTER_32, + tables.MASTER_64, + tables.GREY_16, + tables.GREY_32, + tables.GREY_8, + ) + dynamic = ( + tables.DYNAMIC_8, + tables.DYNAMIC_16, + tables.DYNAMIC_32, + tables.DYNAMIC_64, + tables.DYNAMIC_128, + tables.DYNAMIC_256, + tables.DYNAMIC_512, + ) + profiles = [] + for ident, colours in enumerate(fixed): + size = len(colours) + bits = (size - 1).bit_length() + profiles.append(_Profile(size, bits, 0, ident in _GREY_PROFILES, None, colours)) + for table in dynamic: + size = len(table) + bits = (size - 1).bit_length() + white = next(i for i, index in enumerate(table) if tables.GLOBAL_512[index] == _WHITE) + profiles.append(_Profile(size, bits, white, False, table, tables.GLOBAL_512)) + return tuple(profiles) + + +def _decode_indexed(body: str) -> _Indexed | None: + """Decode a version 3 image to palette references. + + Returns: + The image, or ``None`` when the body is not a version 3 image. + + Raises: + _Bad: The data does not obey the format. Other errors can also occur for hostile + data. :func:`_decode_refs` catches all of them. + """ + match = _IMAGE.fullmatch(body.strip()) + if match is None or match.group(1) != "3" or len(match.group(2)) > _MAX_TEXT: + return None + data = base91_decode(match.group(2)) + if data is None or len(data) < 5 or data[0] != _V3: + return None + header = data[2] + profile_id = header & 0x0F + profile = _profiles()[profile_id] + scan = (header >> 4) & 0x03 + implicit_white = bool(header & 0x40) + reader = _Reader(data[3:]) + size = _dimensions(reader) + if size is None: + raise _Bad + width, height = size + if reader.pos != _canonical_dimension_bits(width, height): + raise _Bad + container_byte = reader.bits(8) + container, context = container_byte >> 5, container_byte & 0x1F + algorithm = _algorithm(context) if container <= 3 else 0 + _check_top_level(container, algorithm, scan, implicit_white) + transparent = reader.bits(profile.bits) if header & 0x80 else None + + decoder = _Decoder(reader, profile, implicit_white, width * height * _WORK) + if container <= 1: + # block (0) and compactBlock (1). The checks above made the scan of a compact + # block h. + refs = _unscan(decoder.block(width, height, algorithm, scan), width, height, scan) + elif container <= 3: + refs = decoder.bounds(width, height, algorithm, scan, compact=container == 3) + elif container <= 5: + refs = decoder.regions(width, height, context + 1, compact=container == 5) + elif container == 6: + refs = [decoder.solid_colour(context)] * (width * height) + else: + refs = decoder.solid_rects(width, height, context) + reader.finish() + + if profile.table is not None: + table = profile.table + refs = [table[ref] for ref in refs] + if transparent is not None: + transparent = table[transparent] + return _Indexed(width, height, profile_id, refs, transparent) + + +def _canonical_dimension_bits(width: int, height: int) -> int: + """The number of bits of the canonical dimensions of a size. + + The format permits only the shortest mode for a size. Each mode has its own number of + bits, so a different number of bits after :func:`_dimensions` shows a mode that is + not canonical. + """ + if width == height and width <= 64: + return 8 # mode 0 + if width <= 32 and height <= 32: + return 12 # mode 1 + if width <= 64 and height <= 64: + return 14 # mode 2 + return 11 if width == height else 19 # mode 3, square or rectangle + + +def _algorithm(ident: int) -> int: + """Check a block algorithm id (0 to 15) and return it.""" + if ident > 15: + raise _Bad + return ident + + +def _check_top_level(container: int, algorithm: int, scan: int, implicit_white: bool) -> None: + """Check that the header, the container, and the algorithm agree. + + - A ``block`` cannot hold an algorithm of the compact header, and a ``compactBlock`` + can hold only those algorithms. + - Some containers and the ``quadtree`` algorithm (7) permit only the scan ``h``. + - The implicit white background is valid only where there is a background colour. + """ + if container == 0 and algorithm in _COMPACT_HEADER: + raise _Bad + if container == 1 and algorithm not in _COMPACT_HEADER: + raise _Bad + horizontal = container in (1, 4, 5, 6, 7) or (container == 3 and algorithm in _COMPACT_HEADER) + if (horizontal or algorithm == 7) and scan != 0: + raise _Bad + if implicit_white and container <= 1 and algorithm not in _WITH_BACKGROUND: + raise _Bad + + +def _local_bits(colours: int) -> int: + """The number of bits of one index in a local palette of ``colours`` colours.""" + return (colours - 1).bit_length() if colours > 1 else 0 + + +def _row_length(scan: int, width: int, height: int) -> int: + """The length of one row of the scan sequence: a row for ``h`` and ``s``, else a column.""" + return width if scan in (0, 2) else height + + +def _scan_positions(width: int, height: int, scan: int) -> list[int]: + """The row-major position of each item of the scan sequence. + + - 0 ``h``: rows from the top, each row from the left. + - 1 ``v``: columns from the left, each column from the top. + - 2 ``s``: as ``h``, but the odd rows go from the right. + - 3 ``sv``: as ``v``, but the odd columns go from the bottom. + """ + if scan == 0: + return list(range(width * height)) + if scan == 1: + return [y * width + x for x in range(width) for y in range(height)] + if scan == 2: + return [ + y * width + x + for y in range(height) + for x in (range(width) if y % 2 == 0 else range(width - 1, -1, -1)) + ] + return [ + y * width + x + for x in range(width) + for y in (range(height) if x % 2 == 0 else range(height - 1, -1, -1)) + ] + + +def _unscan(linear: list[int], width: int, height: int, scan: int) -> list[int]: + """Put the items of a scan sequence back in row-major order.""" + if len(linear) != width * height: + raise _Bad + if scan == 0: + return linear + result = [0] * len(linear) + for item, position in zip(linear, _scan_positions(width, height, scan), strict=True): + result[position] = item + return result + + +def _pick(palette: list[int], index: int) -> int: + """The colour at ``index`` in a local palette, or :class:`_Bad` past its end.""" + if index >= len(palette): + raise _Bad + return palette[index] + + +def _pick_all(palette: list[int], indices: list[int]) -> list[int]: + """The colours of a list of local palette indices.""" + if indices and max(indices) >= len(palette): + raise _Bad + return [palette[index] for index in indices] + + +class _Reader(_Bits): + """A reader of the bit fields of version 3, which raises :class:`_Bad` past the end. + + It also reads the integer forms of the format. The data is short (a message), so one + Python integer holds all of it. + """ + + @property + def pos(self) -> int: + """The number of bits that the reader has read.""" + return self._pos + + def bits(self, count: int) -> int: + """The next ``count`` bits as an unsigned number.""" + if self._pos + count > self._left: + raise _Bad + value = (self._value >> self._pos) & ((1 << count) - 1) + self._pos += count + return value + + def flags(self, count: int) -> list[bool]: + """The next ``count`` bits, one flag each, in the order of the data.""" + if count == 0: + return [] + text = format(self.bits(count), "b").zfill(count) + return [char == "1" for char in reversed(text)] + + def varuint(self) -> int: + """A ``bitVarUint``: 7 bits in each byte, and bit 7 set when a byte follows.""" + value = 0 + for shift in range(0, 35, 7): + byte = self.bits(8) + value |= (byte & 0x7F) << shift + if not byte & 0x80: + return value + raise _Bad + + def compact(self) -> int: + """A ``compactUint``: a short prefix, then 2, 4, or 8 bits, or a ``bitVarUint``. + + The ``bitVarUint`` holds the value itself, not the value minus 276. The reference + encoder writes it that way. + """ + if not self.bits(1): + return self.bits(2) + if not self.bits(1): + return self.bits(4) + 4 + if not self.bits(1): + return self.bits(8) + 20 + return self.varuint() + + def range_compact(self, maximum: int) -> int: + """A ``rangeCompactUint``: fixed bits up to a maximum of 7, else a ``compactUint``.""" + if maximum < 0: + raise _Bad + value = self.bits(maximum.bit_length()) if maximum <= 7 else self.compact() + if value > maximum: + raise _Bad + return value + + def bounded(self, maximum: int) -> int: + """A ``boundedCompactUint``: as ``compactUint``, but its last form has fixed bits.""" + if maximum < 0: + raise _Bad + if maximum <= 7: + value = self.bits(maximum.bit_length()) + elif not self.bits(1): + value = self.bits(2) + elif not self.bits(1): + value = self.bits(4) + 4 + elif not self.bits(1): + value = self.bits(8) + 20 + elif maximum < 276: + raise _Bad + else: + value = self.bits((maximum - 276).bit_length()) + 276 + if value > maximum: + raise _Bad + return value + + def signed(self) -> int: + """A ``signedCompactInt``: a zigzag value in a ``compactUint``.""" + code = self.compact() + return code // 2 if code % 2 == 0 else -((code + 1) // 2) + + def finish(self) -> None: + """Check the end: only zero bits to the end of the last byte, and no more bytes.""" + if (self._pos + 7) // 8 * 8 != self._left or self._value >> self._pos: + raise _Bad + + +class _Decoder: + """The decoder of the body of one image: the containers and the block algorithms. + + All colours here are colour ids of the profile (refer to :class:`_Profile`). + """ + + def __init__(self, reader: _Reader, profile: _Profile, implicit_white: bool, work: int): + self.reader = reader + self.profile = profile + self.implicit_white = implicit_white + #: The pixels that the blocks can still use (refer to :data:`_WORK`). + self.work = work + + # The containers. + + def background(self) -> int: + """The background colour of a container or a block: white, or a colour in the data.""" + if self.implicit_white: + return self.profile.white + return self.reader.bits(self.profile.bits) + + def solid_colour(self, context: int) -> int: + """The colour of a ``solidBackground`` image. + + The low bits of the colour id are in the context. A colour id of more than 5 bits + has its high bits in the body. + """ + if self.implicit_white: + if context: + raise _Bad + return self.profile.white + bits = self.profile.bits + low = min(bits, 5) + if context >> low: + raise _Bad + return context | (self.reader.bits(bits - low) << low) + + def solid_rects(self, width: int, height: int, context: int) -> list[int]: + """A ``solidRects`` image: a background, then up to 64 rectangles of one colour.""" + background = self.background() + palette = self.palette() + bits = _local_bits(len(palette)) + count = context + (self.reader.bits(1) << 5) + 1 + refs = [background] * (width * height) + for _ in range(count): + x, y, w, h = self.geometry(width, height, compact=True) + colour = _pick(palette, self.reader.bits(bits)) + for row in range(y, y + h): + start = row * width + x + refs[start : start + w] = [colour] * w + return refs + + def bounds( + self, width: int, height: int, algorithm: int, scan: int, *, compact: bool + ) -> list[int]: + """A ``boundsBlock`` or ``compactBoundsBlock``: one block on a background.""" + background = self.background() + x, y, w, h = self.geometry(width, height, compact=compact) + linear = self.block(w, h, algorithm, scan, background=background) + refs = [background] * (width * height) + _paste(refs, width, (x, y, w, h), _unscan(linear, w, h, scan)) + return refs + + def regions(self, width: int, height: int, count: int, *, compact: bool) -> list[int]: + """A ``regions`` or ``compactRegionsStream`` image: blocks on a background. + + A compact stream starts with three flags: a common block header, delta geometry, + and a shared local palette. A common header with the id 31 is a hybrid header: + the real id follows, and each region has one bit that selects its own header. + """ + reader = self.reader + background = self.background() + common = delta = shared = False + if compact: + common, delta, shared = (bool(reader.bits(1)) for _ in range(3)) + hybrid = False + common_algorithm = common_scan = 0 + if common: + ident = reader.bits(5) + hybrid = ident == _HYBRID + common_algorithm = _algorithm(reader.bits(5) if hybrid else ident) + common_scan = self.region_scan(common_algorithm) + palette = self.palette() if shared else None + refs = [background] * (width * height) + box: tuple[int, int, int, int] | None = None + for _ in range(count): + if delta and box is not None: + box = self.delta_geometry(box, width, height) + else: + box = self.geometry(width, height, compact=compact) + own_header = bool(reader.bits(1)) if hybrid else not common + if own_header: + algorithm = _algorithm(reader.bits(5)) + scan = self.region_scan(algorithm) + else: + algorithm, scan = common_algorithm, common_scan + _x, _y, w, h = box + linear = self.block(w, h, algorithm, scan, shared=palette, background=background) + _paste(refs, width, box, _unscan(linear, w, h, scan)) + return refs + + def region_scan(self, algorithm: int) -> int: + """The scan of a region header: ``h`` for a compact header algorithm, else 2 bits.""" + return 0 if algorithm in _COMPACT_HEADER else self.reader.bits(2) + + def geometry(self, width: int, height: int, *, compact: bool) -> tuple[int, int, int, int]: + """A rectangle (x, y, width, height) in the image. + + Plain geometry has 8 bits for each field. Compact geometry has only the bits that + the image size, and then the space to the right and below, make necessary. + """ + reader = self.reader + x = reader.bits((width - 1).bit_length() if compact else 8) + y = reader.bits((height - 1).bit_length() if compact else 8) + if x >= width or y >= height: + raise _Bad + w = reader.bits((width - x - 1).bit_length() if compact else 8) + 1 + h = reader.bits((height - y - 1).bit_length() if compact else 8) + 1 + if x + w > width or y + h > height: + raise _Bad + return x, y, w, h + + def delta_geometry( + self, previous: tuple[int, int, int, int], width: int, height: int + ) -> tuple[int, int, int, int]: + """A rectangle as four signed differences from the previous rectangle.""" + x, y, w, h = (value + self.reader.signed() for value in previous) + if x < 0 or y < 0 or w <= 0 or h <= 0 or x + w > width or y + h > height: + raise _Bad + return x, y, w, h + + # The local palettes. + + def palette(self) -> list[int]: + """A local palette: a list of colour ids with no duplicates. + + A flat palette gives a length and then each colour id. A descriptor palette + gives the colour ids in a shorter form (refer to :meth:`descriptor`). + """ + reader = self.reader + size, bits = self.profile.size, self.profile.bits + if size <= 64: + if reader.bits(1): + return self.descriptor(reader.bits(2)) + length = reader.bits(bits) + 1 + elif not reader.bits(1): + length = reader.bits(6) + 1 + elif not reader.bits(1): + length = reader.bits(6) + 65 + elif not reader.bits(1): + length = reader.bits(8) + 129 + elif not reader.bits(1): + length = reader.bits(7) + 385 + else: + return self.descriptor(reader.bits(2)) + if length > size: + raise _Bad + colours = [reader.bits(bits) for _ in range(length)] + if len(set(colours)) != length: + raise _Bad + return colours + + def palette_length(self) -> int: + """The length of a sorted-delta or ordered-banked palette.""" + reader = self.reader + size = self.profile.size + if size <= 64: + return reader.bits(self.profile.bits) + 1 + if not reader.bits(1): + return reader.bits(6) + 1 + if not reader.bits(1): + return reader.bits(6) + 65 + if size <= 128: + raise _Bad + length = reader.bits((size - 129).bit_length()) + 129 + if length > size: + raise _Bad + return length + + def descriptor(self, kind: int) -> list[int]: + """A descriptor palette. + + - 0 bitmap: one bit for each colour of the profile. + - 1 sorted delta: the length, the first colour id, then the gap to each next one. + - 2 range runs: runs of consecutive colour ids. + - 3 banked (only for ``dynamicGlobal512``): one bit selects bank bitmaps or the + ordered form. Refer to :meth:`banked`. + + All forms except the ordered form give the colour ids in ascending order. + """ + reader = self.reader + size, bits = self.profile.size, self.profile.bits + if kind == 0: + refs = [ref for ref, flag in enumerate(reader.flags(size)) if flag] + elif kind == 1: + length = self.palette_length() + refs = [reader.bits(bits)] + while len(refs) < length: + refs.append(refs[-1] + reader.compact() + 1) + elif kind == 2: + runs = reader.range_compact(size - 1) + 1 + refs = [] + previous_end = -1 + for _ in range(runs): + start = reader.bits(bits) + length = reader.compact() + 1 + end = start + length - 1 + if start <= previous_end or end >= size or len(refs) + length > size: + raise _Bad + refs.extend(range(start, end + 1)) + previous_end = end + else: + refs = self.banked() + if not refs or len(refs) > size or len(set(refs)) != len(refs): + raise _Bad + if max(refs) >= size: + raise _Bad + return refs + + def banked(self) -> list[int]: + """A banked palette of ``dynamicGlobal512``: 8 banks of 64 colours. + + - Bank bitmaps (bit 0): a mask of 8 banks, then 64 bits for each selected bank. + - Ordered (bit 1): the length, then for each colour its bank and its offset in + the bank. A single bank has 3 bits once. Several banks have a mask of 8 bits, + and each colour has the index of its bank in the list of selected banks. + + Each selected bank must have one colour or more. + """ + reader = self.reader + if self.profile.size != 512: + raise _Bad + if not reader.bits(1): + mask = reader.bits(8) + if not mask: + raise _Bad + refs: list[int] = [] + for bank in range(8): + if mask >> bank & 1: + chosen = [ + bank << 6 | offset for offset, flag in enumerate(reader.flags(64)) if flag + ] + if not chosen: + raise _Bad + refs.extend(chosen) + return refs + length = self.palette_length() + if not reader.bits(1): + if length > 64: + raise _Bad + bank = reader.bits(3) + return [bank << 6 | reader.bits(6) for _ in range(length)] + mask = reader.bits(8) + banks = [bank for bank in range(8) if mask >> bank & 1] + if len(banks) <= 1 or length > len(banks) * 64: + raise _Bad + bank_bits = (len(banks) - 1).bit_length() + refs = [] + used = set() + for _ in range(length): + index = reader.bits(bank_bits) + if index >= len(banks): + raise _Bad + used.add(index) + refs.append(banks[index] << 6 | reader.bits(6)) + if len(used) != len(banks): + raise _Bad + return refs + + # The block algorithms. + + def block( + self, + width: int, + height: int, + algorithm: int, + scan: int, + *, + shared: list[int] | None = None, + background: int | None = None, + ) -> list[int]: + """Decode one block. Return its colours in the order of its scan. + + Args: + width: The width of the block. + height: The height of the block. + algorithm: The block algorithm id, 0 to 15. + scan: The scan id, 0 to 3. + shared: The shared palette of a regions stream. A block that has a shared + palette does not read its own palette. + background: The background of the container. A block that has a background + uses it, and does not read its own background. + """ + count = width * height + self.work -= count + if self.work < 0: + raise _Bad + reader = self.reader + profile = self.profile + if shared is not None and algorithm in _NO_SHARED_PALETTE: + raise _Bad + if algorithm == 0: # rawGlobal + return [reader.bits(profile.bits) for _ in range(count)] + if algorithm in _WITH_BACKGROUND: + if background is None: + background = self.background() + return self.with_background(count, algorithm, shared, background) + if algorithm in (10, 12): # directBitplanes, directRowDelta + if not (profile.grey or profile.table is not None): + raise _Bad + if algorithm == 10: + return self.adaptive_bitplanes(count, list(range(profile.size))) + return self.compact_row_delta( + count, + _row_length(scan, width, height), + profile.bits, + profile.size - 1, + residual=profile.grey, + ) + + palette = shared if shared is not None else self.palette() + bits = _local_bits(len(palette)) + if algorithm == 1: # rawLocal + return _pick_all(palette, [reader.bits(bits) for _ in range(count)]) + if algorithm in (2, 14): # compactRle, varUintRle + return self.rle(count, palette, varuint=algorithm == 14) + if algorithm == 6: + return self.lz_pixels(count, palette) + if algorithm == 7: + if scan != 0: + raise _Bad + return self.quadtree(width, height, palette) + if algorithm == 8: + return _pick_all(palette, self.bitplanes(count, bits)) + if algorithm == 9: + return self.adaptive_bitplanes(count, palette) + row_length = _row_length(scan, width, height) + if algorithm == 13: + values = self.row_delta(count, row_length, bits, len(palette) - 1) + elif algorithm == 11: + values = self.compact_row_delta( + count, row_length, bits, len(palette) - 1, residual=False + ) + else: # 5, rowRepeat + values = self.row_repeat(count, row_length, bits) + return _pick_all(palette, values) + + def with_background( + self, count: int, algorithm: int, shared: list[int] | None, background: int + ) -> list[int]: + """Decode ``biColorMask`` (4), ``compactSparse`` (3), or ``varUintSparse`` (15). + + With its own palette, a sparse block must not have the background in the palette. + With a shared palette, each segment must not use the background. A bicolour block + has one foreground colour: a colour id, or an index in the shared palette. + """ + reader = self.reader + if algorithm == 4: + if shared is None: + foreground = reader.bits(self.profile.bits) + else: + foreground = _pick(shared, reader.bits(_local_bits(len(shared)))) + if foreground == background: + raise _Bad + return [foreground if flag else background for flag in reader.flags(count)] + + palette = shared + if palette is None: + palette = self.palette() + if background in palette: + raise _Bad + bits = _local_bits(len(palette)) + varuint = algorithm == 15 + refs = [background] * count + if varuint: + segments = reader.varuint() + if segments <= 0 or segments > count: + raise _Bad + else: + segments = reader.bounded(count - 1) + 1 + position = 0 + for _ in range(segments): + if varuint: + skip = reader.varuint() + if skip > count - position: + raise _Bad + position += skip + if position >= count: + raise _Bad + else: + if position >= count: + raise _Bad + position += reader.bounded(count - position - 1) + colour = _pick(palette, reader.bits(bits)) + if colour == background: + raise _Bad + if varuint: + length = reader.varuint() + if length <= 0 or position + length > count: + raise _Bad + else: + length = reader.bounded(count - position - 1) + 1 + refs[position : position + length] = [colour] * length + position += length + return refs + + def rle(self, count: int, palette: list[int], *, varuint: bool) -> list[int]: + """Decode ``compactRle`` or ``varUintRle``: runs of one colour each.""" + reader = self.reader + bits = _local_bits(len(palette)) + refs: list[int] = [] + while len(refs) < count: + colour = _pick(palette, reader.bits(bits)) + if varuint: + length = reader.varuint() + if length <= 0 or len(refs) + length > count: + raise _Bad + else: + length = reader.bounded(count - len(refs) - 1) + 1 + refs.extend([colour] * length) + return refs + + def lz_pixels(self, count: int, palette: list[int]) -> list[int]: + """Decode ``lzPixels``: literal runs, and copies of earlier pixels (3 or more).""" + reader = self.reader + bits = _local_bits(len(palette)) + refs: list[int] = [] + while len(refs) < count: + done = len(refs) + if reader.bits(1): + remaining = count - done + if done == 0 or remaining < 3: + raise _Bad + distance = reader.range_compact(done - 1) + 1 + length = reader.range_compact(remaining - 3) + 3 + start = done - distance + if distance >= length: + refs.extend(refs[start : start + length]) + else: + # The copy overlaps the pixels that it makes, so copy one at a time. + for index in range(start, start + length): + refs.append(refs[index]) + else: + length = reader.range_compact(count - done - 1) + 1 + refs.extend(_pick(palette, reader.bits(bits)) for _ in range(length)) + return refs + + def quadtree(self, width: int, height: int, palette: list[int]) -> list[int]: + """Decode ``quadtree``: a node is one colour, or it splits in two or four. + + A node one pixel wide splits into a top and a bottom half. A node one pixel high + splits into a left and a right half. Other nodes split into four, in the order top + left, top right, bottom left, bottom right. The first half is the smaller one. + """ + reader = self.reader + bits = _local_bits(len(palette)) + refs = [palette[0]] * (width * height) + + def node(x: int, y: int, w: int, h: int) -> None: + if reader.bits(1): + colour = _pick(palette, reader.bits(bits)) + for row in range(y, y + h): + start = row * width + x + refs[start : start + w] = [colour] * w + return + if w == 1 and h == 1: + raise _Bad + if w == 1: + top = h // 2 + node(x, y, 1, top) + node(x, y + top, 1, h - top) + elif h == 1: + left = w // 2 + node(x, y, left, 1) + node(x + left, y, w - left, 1) + else: + left, top = w // 2, h // 2 + node(x, y, left, top) + node(x + left, y, w - left, top) + node(x, y + top, left, h - top) + node(x + left, y + top, w - left, h - top) + + node(0, 0, width, height) + return refs + + def bitplanes(self, count: int, bits: int) -> list[int]: + """Decode ``bitplanes`` to local indices: each bit plane raw or in runs.""" + reader = self.reader + values = [0] * count + for plane in range(bits): + mask = 1 << plane + if not reader.bits(1): + values = _set_flags(values, reader.flags(count), mask) + else: + self.plane_runs(values, count, mask, short=False) + return values + + def adaptive_bitplanes(self, count: int, palette: list[int]) -> list[int]: + """Decode ``adaptiveBitplanes``. Each bit plane has a prefix that gives its form. + + The prefixes, in the order of the data: 0 raw, 10 runs, 110 short runs, 11100 all + zero, 11110 all one, 11101 a list of the one bits, 11111 a list of the zero bits. + """ + reader = self.reader + values = [0] * count + for plane in range(_local_bits(len(palette))): + mask = 1 << plane + if not reader.bits(1): + values = _set_flags(values, reader.flags(count), mask) + elif not reader.bits(1): + self.plane_runs(values, count, mask, short=False) + elif not reader.bits(1): + self.plane_runs(values, count, mask, short=True) + else: + form = reader.bits(2) + if form & 1: # all one, or all one and then a list of the zero bits + values = [value | mask for value in values] + if form & 2: + self.plane_positions(values, count, mask, set_bit=form == 2) + return _pick_all(palette, values) + + def plane_runs(self, values: list[int], count: int, mask: int, *, short: bool) -> None: + """Read the runs of one bit plane. The bit value changes after each run.""" + reader = self.reader + bit = reader.bits(1) + position = 0 + while position < count: + remaining = count - position + length = self.short_run(remaining) if short else reader.range_compact(remaining - 1) + 1 + if bit: + values[position : position + length] = [ + value | mask for value in values[position : position + length] + ] + position += length + bit ^= 1 + + def short_run(self, remaining: int) -> int: + """The length of a short run: 0 is 1, 10 is 2, 110 is 3, 111 and a number is 4 or more.""" + reader = self.reader + for length in (1, 2, 3): + if not reader.bits(1): + if length > remaining: + raise _Bad + return length + return reader.range_compact(remaining - 4) + 4 + + def plane_positions(self, values: list[int], count: int, mask: int, *, set_bit: bool) -> None: + """Read the list of positions of a sparse bit plane, and set or clear their bit.""" + reader = self.reader + total = reader.range_compact(count - 1) + 1 + previous = -1 + for index in range(total): + later = total - index - 1 + position = previous + reader.range_compact(count - previous - later - 2) + 1 + if set_bit: + values[position] |= mask + else: + values[position] &= ~mask + previous = position + + def row_repeat(self, count: int, row_length: int, bits: int) -> list[int]: + """Decode ``rowRepeat``: the first row, then each row is a copy (bit 1) or raw.""" + reader = self.reader + values = [reader.bits(bits) for _ in range(row_length)] + for _ in range(count // row_length - 1): + if reader.bits(1): + values.extend(values[-row_length:]) + else: + values.extend(reader.bits(bits) for _ in range(row_length)) + return values + + def row_delta(self, count: int, row_length: int, bits: int, maximum: int) -> list[int]: + """Decode ``rowDelta``: each row is raw, or a change of the predicted row. + + Operations (2 bits): 0 raw, 1 repeat, 2 changes at listed positions, 3 extended. + Extended operations (2 bits): 0 a mask and a value for each set bit, 1 segments, + 2 a mask and one value for all set bits, 3 a run of repeated rows. + """ + reader = self.reader + rows = count // row_length + virtual = bool(reader.bits(1)) + shifts = bool(reader.bits(1)) + values: list[int] = [] + + def value() -> int: + result = reader.bits(bits) + if result > maximum: + raise _Bad + return result + + def predictor(row: int) -> int: + if not shifts: + return 0 + return self.predictor(row, virtual) + + if not virtual: + values.extend(value() for _ in range(row_length)) + position_bits = (row_length - 1).bit_length() + while len(values) < count: + row = len(values) // row_length + op = reader.bits(2) + if op == 0: + values.extend(value() for _ in range(row_length)) + continue + if op == 1: + values.extend(_predicted(values, row_length, row, 0, virtual)) + continue + if op == 2: + current = _predicted(values, row_length, row, predictor(row), virtual) + changes = reader.bits(row_length.bit_length()) + if changes > row_length: + raise _Bad + previous = -1 + for _ in range(changes): + x = reader.bits(position_bits) + if x >= row_length or x <= previous: + raise _Bad + current[x] = value() + previous = x + values.extend(current) + continue + extended = reader.bits(2) + if extended == 3: + if row + 2 > rows: + raise _Bad + for _ in range(reader.range_compact(rows - row - 2) + 2): + values.extend(_predicted(values, row_length, row, 0, virtual)) + row += 1 + continue + current = _predicted(values, row_length, row, predictor(row), virtual) + if extended == 1: + segments = reader.bits(position_bits) + 1 + previous_end = -1 + for _ in range(segments): + start = reader.bits(position_bits) + length = reader.bits(position_bits) + 1 + if start <= previous_end or start + length > row_length: + raise _Bad + for x in range(start, start + length): + current[x] = value() + previous_end = start + length - 1 + else: + positions = [x for x, flag in enumerate(reader.flags(row_length)) if flag] + if not positions: + raise _Bad + shared = value() if extended == 2 else None + for x in positions: + current[x] = value() if shared is None else shared + values.extend(current) + return values + + def compact_row_delta( + self, count: int, row_length: int, bits: int, maximum: int, *, residual: bool + ) -> list[int]: + """Decode ``compactRowDelta`` or ``directRowDelta``. + + Operations (3 bits): 0 repeat, 1 raw, 2 changes at listed positions, 3 one value + at listed positions, 4 segments, 5 a trimmed mask, 6 a run of repeated rows, 7 the + predicted row with no change. A grey ``directRowDelta`` has ``residual``: then + operations 2 to 5 have one bit that selects values as differences from the + predicted row. + + For operation 3 with differences, the value at the first position is the value at + all positions. The reference decoder does this. + """ + reader = self.reader + rows = count // row_length + virtual = bool(reader.bits(1)) + values: list[int] = [] + + def raw_value() -> int: + result = reader.bits(bits) + if result > maximum: + raise _Bad + return result + + if not virtual: + values.extend(raw_value() for _ in range(row_length)) + while len(values) < count: + row = len(values) // row_length + op = reader.bits(3) + if op in (0, 6): + repeats = 1 if op == 0 else reader.range_compact(rows - row - 2) + 2 + for _ in range(repeats): + values.extend(_predicted(values, row_length, row, 0, virtual)) + row += 1 + continue + if op == 1: + values.extend(raw_value() for _ in range(row_length)) + continue + guess = _predicted(values, row_length, row, self.predictor(row, virtual), virtual) + current = list(guess) + if op == 7: + values.extend(current) + continue + differences = residual and bool(reader.bits(1)) + + def changed(x: int, differences: bool = differences, guess: list[int] = guess) -> int: + if not differences: + return raw_value() + code = reader.compact() + 1 + result = guess[x] + ((code + 1) // 2 if code % 2 else -(code // 2)) + if result < 0 or result > maximum: + raise _Bad + return result + + if op in (2, 3): + positions = self.change_positions(row_length) + if op == 3: + one = changed(positions[0]) + for x in positions: + current[x] = one + else: + for x in positions: + current[x] = changed(x) + else: + positions = ( + self.segment_positions(row_length) + if op == 4 + else self.mask_positions(row_length) + ) + for x in positions: + current[x] = changed(x) + values.extend(current) + return values + + def predictor(self, row: int, virtual: bool) -> int: + """A row predictor: 0 is ``same``, 10 is ``left``, 11 is ``right``. + + The first row on the virtual row of zeros permits only ``same``. + """ + reader = self.reader + result = 0 if not reader.bits(1) else 1 + reader.bits(1) + if result and row == 0 and virtual: + raise _Bad + return result + + def change_positions(self, row_length: int) -> list[int]: + """The positions of ``compactRowDelta`` operations 2 and 3: a count, then gaps.""" + reader = self.reader + total = reader.range_compact(row_length - 1) + 1 + positions = [] + previous = -1 + for index in range(total): + later = total - index - 1 + previous += 1 + reader.range_compact(row_length - previous - later - 2) + positions.append(previous) + return positions + + def segment_positions(self, row_length: int) -> list[int]: + """The positions of ``compactRowDelta`` operation 4: segments, each a gap and a length.""" + reader = self.reader + total = reader.range_compact(row_length - 1) + 1 + positions: list[int] = [] + previous_end = 0 + for index in range(total): + later = total - index - 1 + start = previous_end + reader.range_compact(row_length - previous_end - later - 1) + length = reader.range_compact(row_length - start - later - 1) + 1 + if start + length > row_length: + raise _Bad + positions.extend(range(start, start + length)) + previous_end = start + length + return positions + + def mask_positions(self, row_length: int) -> list[int]: + """The positions of ``compactRowDelta`` operation 5: a start, a span, and a mask.""" + reader = self.reader + start = reader.range_compact(row_length - 1) + span = reader.range_compact(row_length - start - 1) + 1 + positions = [start + offset for offset, flag in enumerate(reader.flags(span)) if flag] + if not positions: + raise _Bad + return positions + + +def _predicted( + values: list[int], row_length: int, row: int, predictor: int, virtual: bool +) -> list[int]: + """The predicted row: the previous row, moved one place left or right with wrap. + + ``left[x]`` is ``previous[x - 1]``, and ``right[x]`` is ``previous[x + 1]``. Row 0 on a + virtual base has only zeros before it. + """ + if row == 0 and virtual: + return [0] * row_length + previous = values[(row - 1) * row_length : row * row_length] + if predictor == 1: + return previous[-1:] + previous[:-1] + if predictor == 2: + return previous[1:] + previous[:1] + return previous + + +def _set_flags(values: list[int], flags: list[bool], mask: int) -> list[int]: + """Set the ``mask`` bit in each value whose flag is set.""" + return [value | mask if flag else value for value, flag in zip(values, flags, strict=True)] + + +def _paste(refs: list[int], width: int, box: tuple[int, int, int, int], block: list[int]) -> None: + """Copy a row-major block into the image at its rectangle.""" + x, y, w, h = box + for row in range(h): + start = (y + row) * width + x + refs[start : start + w] = block[row * w : (row + 1) * w] diff --git a/meshterm/core/mcoimg_palettes.py b/meshterm/core/mcoimg_palettes.py new file mode 100644 index 0000000..1523d89 --- /dev/null +++ b/meshterm/core/mcoimg_palettes.py @@ -0,0 +1,279 @@ +# SPDX-License-Identifier: Apache-2.0 +"""The colour tables of the MCOimg palette profiles. + +This module is data for interoperability, and has no code. A script made it from the +files ``lib/helpers/mcoimg_palette.dart`` and ``lib/helpers/mcoimg_dynamic_palettes.dart`` +of the meshcore-open repository (HDDen/meshcore-open, a fork of zjs81/meshcore-open, MIT). +Do not edit the values by hand. A different value changes the colour of a pixel. + +- The fixed profiles are tuples of (red, green, blue), in the order of the colour ids. +- ``GLOBAL_512`` is the dynamic global palette of 512 colours. +- Each ``DYNAMIC_n`` tuple gives the index in ``GLOBAL_512`` of each colour id of the + dynamic profile of n colours. +""" + +from __future__ import annotations + +# The tables keep several values on each line, so the formatter must not change them. +# fmt: off + +MONO: tuple[tuple[int, int, int], ...] = ( + (255, 255, 255), (0, 0, 0), +) + +MASTER_4: tuple[tuple[int, int, int], ...] = ( + (255, 255, 255), (192, 192, 192), (86, 86, 86), (0, 0, 0), +) + +MASTER_8: tuple[tuple[int, int, int], ...] = ( + (255, 255, 255), (141, 141, 141), (0, 0, 0), (254, 36, 0), (241, 209, 0), + (71, 192, 0), (61, 105, 255), (121, 0, 255), +) + +MASTER_16: tuple[tuple[int, int, int], ...] = ( + (255, 255, 255), (164, 164, 164), (0, 0, 0), (209, 30, 1), (98, 14, 1), + (255, 132, 0), (123, 64, 0), (241, 209, 0), (144, 124, 2), (65, 176, 0), + (40, 110, 0), (127, 220, 255), (0, 58, 255), (0, 34, 150), (106, 0, 227), + (47, 0, 100), +) + +MASTER_32: tuple[tuple[int, int, int], ...] = ( + (255, 255, 255), (179, 179, 179), (102, 102, 102), (0, 0, 0), (255, 176, 163), + (255, 85, 65), (254, 36, 0), (98, 14, 1), (255, 179, 99), (255, 132, 0), + (197, 102, 1), (142, 73, 0), (245, 222, 91), (241, 209, 0), (181, 157, 2), + (120, 105, 2), (149, 218, 118), (71, 192, 0), (40, 110, 0), (29, 79, 0), + (196, 241, 255), (1, 195, 255), (3, 141, 184), (1, 109, 143), (117, 150, 255), + (0, 58, 255), (2, 46, 202), (0, 34, 150), (215, 178, 255), (178, 135, 255), + (133, 61, 255), (47, 0, 100), +) + +MASTER_64: tuple[tuple[int, int, int], ...] = ( + (255, 255, 255), (217, 217, 217), (179, 179, 179), (138, 139, 138), (111, 111, 111), + (79, 79, 79), (36, 36, 36), (0, 0, 0), (255, 176, 163), (255, 154, 137), + (255, 85, 65), (254, 36, 0), (209, 30, 1), (145, 21, 0), (98, 14, 1), + (69, 10, 0), (255, 179, 99), (255, 168, 85), (255, 147, 51), (255, 132, 0), + (228, 118, 1), (197, 102, 1), (142, 73, 0), (123, 64, 0), (247, 229, 114), + (245, 222, 91), (241, 209, 0), (223, 193, 2), (203, 177, 1), (181, 157, 2), + (144, 124, 2), (120, 105, 2), (183, 230, 155), (149, 218, 118), (109, 205, 75), + (71, 192, 0), (65, 176, 0), (54, 148, 1), (40, 110, 0), (29, 79, 0), + (196, 241, 255), (171, 233, 255), (127, 220, 255), (1, 195, 255), (0, 182, 238), + (1, 170, 223), (3, 141, 184), (1, 109, 143), (145, 170, 255), (117, 150, 255), + (59, 100, 255), (0, 58, 255), (2, 51, 225), (2, 46, 202), (1, 40, 176), + (0, 34, 150), (215, 178, 255), (178, 135, 255), (154, 101, 255), (133, 61, 255), + (121, 0, 255), (105, 2, 221), (83, 1, 175), (47, 0, 100), +) + +GREY_16: tuple[tuple[int, int, int], ...] = ( + (255, 255, 255), (238, 238, 238), (221, 221, 221), (204, 204, 204), (187, 187, 187), + (170, 170, 170), (153, 153, 153), (136, 136, 136), (119, 119, 119), (102, 102, 102), + (85, 85, 85), (68, 68, 68), (51, 51, 51), (34, 34, 34), (17, 17, 17), + (0, 0, 0), +) + +GREY_32: tuple[tuple[int, int, int], ...] = ( + (255, 255, 255), (247, 247, 247), (239, 239, 239), (230, 230, 230), (222, 222, 222), + (214, 214, 214), (206, 206, 206), (197, 197, 197), (189, 189, 189), (181, 181, 181), + (173, 173, 173), (165, 165, 165), (156, 156, 156), (148, 148, 148), (140, 140, 140), + (132, 132, 132), (123, 123, 123), (115, 115, 115), (107, 107, 107), (99, 99, 99), + (90, 90, 90), (82, 82, 82), (74, 74, 74), (66, 66, 66), (57, 57, 57), + (49, 49, 49), (41, 41, 41), (33, 33, 33), (24, 24, 24), (16, 16, 16), + (8, 8, 8), (0, 0, 0), +) + +GREY_8: tuple[tuple[int, int, int], ...] = ( + (255, 255, 255), (219, 219, 219), (182, 182, 182), (145, 145, 145), (109, 109, 109), + (72, 72, 72), (36, 36, 36), (0, 0, 0), +) + +GLOBAL_512: tuple[tuple[int, int, int], ...] = ( + (255, 255, 255), (241, 211, 179), (215, 174, 131), (187, 135, 93), (155, 99, 62), + (124, 73, 45), (94, 51, 31), (65, 33, 22), (37, 17, 11), (217, 217, 217), + (255, 237, 229), (255, 229, 211), (255, 216, 198), (248, 204, 191), (244, 191, 165), + (235, 184, 143), (224, 169, 132), (210, 151, 123), (179, 179, 179), (255, 214, 224), + (255, 220, 200), (255, 242, 184), (205, 236, 207), (201, 238, 240), (206, 221, 250), + (224, 210, 244), (234, 207, 227), (138, 139, 138), (228, 224, 174), (202, 199, 131), + (170, 169, 95), (137, 139, 67), (109, 113, 52), (83, 86, 41), (58, 60, 30), + (35, 36, 22), (111, 111, 111), (255, 241, 184), (255, 224, 138), (244, 201, 93), + (221, 175, 55), (196, 147, 36), (157, 113, 24), (116, 80, 15), (73, 48, 8), + (79, 79, 79), (185, 243, 232), (130, 221, 207), (78, 195, 181), (39, 164, 151), + (22, 132, 121), (14, 99, 92), (8, 68, 63), (3, 38, 34), (36, 36, 36), + (244, 192, 168), (231, 155, 124), (212, 118, 87), (185, 86, 62), (150, 61, 45), + (114, 43, 34), (79, 28, 24), (43, 14, 13), (0, 0, 0), (255, 176, 163), + (250, 243, 232), (239, 227, 210), (226, 209, 185), (211, 191, 162), (194, 169, 135), + (170, 144, 111), (141, 118, 92), (111, 92, 73), (255, 154, 137), (255, 224, 194), + (244, 194, 159), (223, 165, 126), (200, 137, 98), (170, 107, 73), (130, 80, 58), + (91, 53, 42), (53, 32, 27), (255, 85, 65), (141, 141, 141), (164, 164, 164), + (102, 102, 102), (255, 63, 36), (254, 58, 29), (254, 52, 22), (254, 47, 14), + (254, 41, 7), (254, 36, 0), (249, 35, 0), (244, 35, 0), (239, 34, 0), + (234, 33, 0), (229, 33, 1), (224, 32, 1), (219, 31, 1), (214, 31, 1), + (209, 30, 1), (202, 29, 1), (195, 28, 1), (188, 27, 1), (181, 26, 1), + (173, 25, 0), (166, 24, 0), (159, 23, 0), (152, 22, 0), (145, 21, 0), + (140, 20, 0), (135, 19, 0), (129, 19, 0), (124, 18, 0), (119, 17, 1), + (114, 16, 1), (108, 16, 1), (103, 15, 1), (98, 14, 1), (95, 14, 1), + (92, 13, 1), (88, 13, 1), (85, 12, 1), (82, 12, 0), (79, 11, 0), + (75, 11, 0), (72, 10, 0), (69, 10, 0), (255, 179, 99), (255, 178, 97), + (255, 177, 96), (255, 175, 94), (255, 174, 93), (255, 173, 91), (255, 172, 90), + (255, 170, 88), (255, 169, 87), (255, 168, 85), (255, 166, 81), (255, 163, 77), + (255, 161, 74), (255, 159, 70), (255, 156, 66), (255, 154, 62), (255, 152, 59), + (255, 149, 55), (255, 147, 51), (255, 145, 45), (255, 144, 40), (255, 142, 34), + (255, 140, 28), (255, 139, 23), (255, 137, 17), (255, 135, 11), (255, 134, 6), + (255, 132, 0), (252, 130, 0), (249, 129, 0), (246, 127, 0), (243, 126, 0), + (240, 124, 1), (237, 123, 1), (234, 121, 1), (231, 120, 1), (228, 118, 1), + (225, 116, 1), (221, 114, 1), (218, 113, 1), (214, 111, 1), (211, 109, 1), + (207, 107, 1), (204, 106, 1), (200, 104, 1), (197, 102, 1), (191, 99, 1), + (185, 96, 1), (179, 92, 1), (173, 89, 1), (166, 86, 0), (160, 83, 0), + (154, 79, 0), (148, 76, 0), (142, 73, 0), (140, 72, 0), (138, 71, 0), + (136, 70, 0), (134, 69, 0), (131, 68, 0), (129, 67, 0), (127, 66, 0), + (125, 65, 0), (123, 64, 0), (247, 229, 114), (247, 228, 111), (247, 227, 109), + (246, 227, 106), (246, 226, 104), (246, 225, 101), (246, 224, 99), (245, 224, 96), + (245, 223, 94), (245, 222, 91), (245, 221, 81), (244, 219, 71), (244, 218, 61), + (243, 216, 51), (243, 215, 40), (242, 213, 30), (242, 212, 20), (241, 210, 10), + (241, 209, 0), (239, 207, 0), (237, 205, 0), (235, 204, 1), (233, 202, 1), + (231, 200, 1), (229, 198, 1), (227, 197, 2), (225, 195, 2), (223, 193, 2), + (221, 191, 2), (219, 189, 2), (216, 188, 2), (214, 186, 2), (212, 184, 1), + (210, 182, 1), (207, 181, 1), (205, 179, 1), (203, 177, 1), (201, 175, 1), + (198, 173, 1), (196, 170, 1), (193, 168, 1), (191, 166, 2), (188, 164, 2), + (186, 161, 2), (183, 159, 2), (181, 157, 2), (177, 153, 2), (173, 150, 2), + (169, 146, 2), (165, 142, 2), (160, 139, 2), (156, 135, 2), (152, 131, 2), + (148, 128, 2), (144, 124, 2), (141, 122, 2), (139, 120, 2), (136, 118, 2), + (133, 116, 2), (131, 113, 2), (128, 111, 2), (125, 109, 2), (123, 107, 2), + (120, 105, 2), (183, 230, 155), (179, 229, 151), (175, 227, 147), (172, 226, 143), + (168, 225, 139), (164, 223, 134), (160, 222, 130), (157, 221, 126), (153, 219, 122), + (149, 218, 118), (145, 217, 113), (140, 215, 108), (136, 214, 104), (131, 212, 99), + (127, 211, 94), (122, 209, 89), (118, 208, 85), (113, 206, 80), (109, 205, 75), + (105, 204, 67), (101, 202, 58), (96, 201, 50), (92, 199, 42), (88, 198, 33), + (84, 196, 25), (79, 195, 17), (75, 193, 8), (71, 192, 0), (70, 190, 0), + (70, 188, 0), (69, 187, 0), (68, 185, 0), (68, 183, 0), (67, 181, 0), + (66, 180, 0), (66, 178, 0), (65, 176, 0), (64, 173, 0), (63, 170, 0), + (61, 167, 0), (60, 164, 0), (59, 160, 1), (58, 157, 1), (56, 154, 1), + (55, 151, 1), (54, 148, 1), (52, 144, 1), (51, 140, 1), (49, 135, 1), + (48, 131, 1), (46, 127, 0), (45, 123, 0), (43, 118, 0), (42, 114, 0), + (40, 110, 0), (39, 107, 0), (38, 103, 0), (36, 100, 0), (35, 96, 0), + (34, 93, 0), (33, 89, 0), (31, 86, 0), (30, 82, 0), (29, 79, 0), + (196, 241, 255), (193, 240, 255), (190, 239, 255), (188, 238, 255), (185, 237, 255), + (182, 237, 255), (179, 236, 255), (177, 235, 255), (174, 234, 255), (171, 233, 255), + (166, 232, 255), (161, 230, 255), (156, 229, 255), (151, 227, 255), (147, 226, 255), + (142, 224, 255), (137, 223, 255), (132, 221, 255), (127, 220, 255), (113, 217, 255), + (99, 214, 255), (85, 212, 255), (71, 209, 255), (57, 206, 255), (43, 203, 255), + (29, 201, 255), (15, 198, 255), (1, 195, 255), (1, 194, 253), (1, 192, 251), + (1, 191, 249), (1, 189, 247), (0, 188, 246), (0, 186, 244), (0, 185, 242), + (0, 183, 240), (0, 182, 238), (0, 181, 236), (0, 179, 235), (0, 178, 233), + (0, 177, 231), (1, 175, 230), (1, 174, 228), (1, 173, 226), (1, 171, 225), + (1, 170, 223), (1, 167, 219), (1, 164, 214), (2, 160, 210), (2, 157, 206), + (2, 154, 201), (2, 151, 197), (3, 147, 193), (3, 144, 188), (3, 141, 184), + (3, 137, 179), (3, 134, 175), (2, 130, 170), (2, 127, 166), (2, 123, 161), + (2, 120, 157), (1, 116, 152), (1, 113, 148), (1, 109, 143), (145, 170, 255), + (142, 168, 255), (139, 166, 255), (136, 163, 255), (133, 161, 255), (129, 159, 255), + (126, 157, 255), (123, 154, 255), (120, 152, 255), (117, 150, 255), (111, 144, 255), + (104, 139, 255), (98, 133, 255), (91, 128, 255), (85, 122, 255), (78, 117, 255), + (72, 111, 255), (61, 105, 255), (59, 100, 255), (52, 95, 255), (46, 91, 255), + (39, 86, 255), (33, 81, 255), (26, 77, 255), (20, 72, 255), (13, 67, 255), + (7, 63, 255), (0, 58, 255), (0, 57, 252), (0, 56, 248), (1, 56, 245), + (1, 55, 242), (1, 54, 238), (1, 53, 235), (2, 53, 232), (2, 52, 228), + (2, 51, 225), (2, 50, 222), (2, 50, 220), (2, 49, 217), (2, 49, 215), + (2, 48, 212), (2, 48, 210), (2, 47, 207), (2, 47, 205), (2, 46, 202), + (2, 45, 199), (2, 45, 196), (2, 44, 193), (2, 43, 190), (1, 43, 188), + (1, 42, 185), (1, 41, 182), (1, 41, 179), (1, 40, 176), (1, 39, 173), + (1, 39, 170), (1, 38, 167), (1, 37, 164), (0, 37, 162), (0, 36, 159), + (0, 35, 156), (0, 35, 153), (0, 34, 150), (215, 178, 255), (211, 173, 255), + (207, 168, 255), (203, 164, 255), (199, 159, 255), (194, 154, 255), (190, 149, 255), + (186, 145, 255), (182, 140, 255), (178, 135, 255), (175, 131, 255), (173, 127, 255), + (170, 124, 255), (167, 120, 255), (165, 116, 255), (162, 112, 255), (159, 109, 255), + (157, 105, 255), (154, 101, 255), (152, 97, 255), (149, 92, 255), (147, 88, 255), + (145, 83, 255), (142, 79, 255), (140, 74, 255), (138, 70, 255), (135, 65, 255), + (133, 61, 255), (132, 54, 255), (130, 47, 255), (129, 41, 255), (128, 34, 255), + (126, 27, 255), (125, 20, 255), (124, 14, 255), (122, 7, 255), (121, 0, 255), + (119, 0, 251), (117, 0, 247), (116, 1, 244), (114, 1, 240), (112, 1, 236), + (110, 1, 232), (109, 2, 229), (106, 0, 227), (105, 2, 221), (103, 2, 216), + (100, 2, 211), (98, 2, 206), (95, 2, 201), (93, 1, 195), (90, 1, 190), + (88, 1, 185), (85, 1, 180), (83, 1, 175), (79, 1, 167), (75, 1, 158), + (71, 1, 150), (67, 1, 142), (63, 0, 133), (59, 0, 125), (55, 0, 117), + (51, 0, 108), (47, 0, 100), +) + +DYNAMIC_8: tuple[int, ...] = ( + 0, 83, 63, 91, 210, 283, 401, 484, +) + +DYNAMIC_16: tuple[int, ...] = ( + 0, 84, 63, 100, 118, 155, 191, 210, 246, 292, 310, 338, 411, 447, 492, 511, +) + +DYNAMIC_32: tuple[int, ...] = ( + 0, 18, 85, 63, 64, 82, 91, 118, 128, 155, 173, 182, 201, 210, 237, 255, + 265, 283, 310, 319, 320, 347, 374, 383, 393, 411, 429, 447, 448, 457, 475, 511, +) + +DYNAMIC_64: tuple[int, ...] = ( + 0, 9, 18, 27, 36, 45, 54, 63, 64, 73, 82, 91, 100, 109, 118, 127, + 128, 137, 146, 155, 164, 173, 182, 191, 192, 201, 210, 219, 228, 237, 246, 255, + 256, 265, 274, 283, 292, 301, 310, 319, 320, 329, 338, 347, 356, 365, 374, 383, + 384, 393, 402, 411, 420, 429, 438, 447, 448, 457, 466, 475, 484, 493, 502, 511, +) + +DYNAMIC_128: tuple[int, ...] = ( + 0, 9, 18, 27, 36, 45, 54, 63, 64, 73, 82, 91, 100, 109, 118, 127, + 128, 137, 146, 155, 164, 173, 182, 191, 192, 201, 210, 219, 228, 237, 246, 255, + 256, 265, 274, 283, 292, 301, 310, 319, 320, 329, 338, 347, 356, 365, 374, 383, + 384, 393, 402, 411, 420, 429, 438, 447, 448, 457, 466, 475, 484, 493, 502, 511, + 1, 2, 3, 4, 5, 6, 7, 8, 10, 11, 12, 13, 14, 15, 16, 17, + 19, 20, 21, 22, 23, 24, 25, 26, 28, 29, 30, 31, 32, 33, 34, 35, + 37, 38, 39, 40, 41, 42, 43, 44, 46, 47, 48, 49, 50, 51, 52, 53, + 55, 56, 57, 58, 59, 60, 61, 62, 65, 66, 67, 68, 69, 70, 71, 72, +) + +DYNAMIC_256: tuple[int, ...] = ( + 0, 9, 18, 27, 36, 45, 54, 63, 64, 73, 82, 91, 100, 109, 118, 127, + 128, 137, 146, 155, 164, 173, 182, 191, 192, 201, 210, 219, 228, 237, 246, 255, + 256, 265, 274, 283, 292, 301, 310, 319, 320, 329, 338, 347, 356, 365, 374, 383, + 384, 393, 402, 411, 420, 429, 438, 447, 448, 457, 466, 475, 484, 493, 502, 511, + 1, 2, 3, 4, 5, 6, 7, 8, 10, 11, 12, 13, 14, 15, 16, 17, + 19, 20, 21, 22, 23, 24, 25, 26, 28, 29, 30, 31, 32, 33, 34, 35, + 37, 38, 39, 40, 41, 42, 43, 44, 46, 47, 48, 49, 50, 51, 52, 53, + 55, 56, 57, 58, 59, 60, 61, 62, 65, 66, 67, 68, 69, 70, 71, 72, + 74, 75, 76, 77, 78, 79, 80, 81, 83, 84, 85, 86, 87, 88, 89, 90, + 92, 93, 94, 95, 96, 97, 98, 99, 101, 102, 103, 104, 105, 106, 107, 108, + 110, 111, 112, 113, 114, 115, 116, 117, 119, 120, 121, 122, 123, 124, 125, 126, + 129, 130, 131, 132, 133, 134, 135, 136, 138, 139, 140, 141, 142, 143, 144, 145, + 147, 148, 149, 150, 151, 152, 153, 154, 156, 157, 158, 159, 160, 161, 162, 163, + 165, 166, 167, 168, 169, 170, 171, 172, 174, 175, 176, 177, 178, 179, 180, 181, + 183, 184, 185, 186, 187, 188, 189, 190, 193, 194, 195, 196, 197, 198, 199, 200, + 202, 203, 204, 205, 206, 207, 208, 209, 211, 212, 213, 214, 215, 216, 217, 218, +) + +DYNAMIC_512: tuple[int, ...] = ( + 0, 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, +) + +# fmt: on diff --git a/meshterm/tools/chat.py b/meshterm/tools/chat.py index d645432..209a309 100644 --- a/meshterm/tools/chat.py +++ b/meshterm/tools/chat.py @@ -1219,7 +1219,9 @@ def _names_us(last: ChatMessage, us: tuple[str | None, str | None]) -> bool: name = us[0] if not name: return False - body = split_channel_sender(last.text)[1] if last.is_channel and not last.outbound else last.text + body = ( + split_channel_sender(last.text)[1] if last.is_channel and not last.outbound else last.text + ) if mcoimg.recognize(body) is not None: return False # the Base91 text of an image can hold an ``@[`` by chance return any(match.group(1) == name for match in MENTION.finditer(body)) diff --git a/meshterm/ui/chat.py b/meshterm/ui/chat.py index c18fe4d..4446527 100644 --- a/meshterm/ui/chat.py +++ b/meshterm/ui/chat.py @@ -40,6 +40,7 @@ from ..core.models import ( ) from ..core.regions import WILDCARD from ..platforms import Platform, on_platform +from . import pixelart from .compose import MentionEditor from .pathline import PATH_INK, PathHop from .qr import QrScreen, qr_strip @@ -901,6 +902,10 @@ class ChatScreen(Screen): :func:`~meshterm.ui.tui.render.render_hanging`). This is because a terminal opens a link, and a user copies one, only while it is on one line. + A body that is a pixel image (MCOimg) shows a short line with its size, and the + image under it in half blocks, at the indent of the body (refer to + :mod:`~meshterm.ui.pixelart`). + Where the platform draws them (:data:`_URL_CODES`, the PicoCalc), each URL in the body gets a QR code under it. The codes are side by side, at the indent of the body. Thus the user can open a link from the handheld on a phone, and does not @@ -945,6 +950,12 @@ class ChatScreen(Screen): ) indent = prefix.cell_len lines += render_hanging(Text(" " * indent), note, width, indent=indent) + if image is not None: + picture = pixelart.decoded(body) + if picture is not None: + indent = prefix.cell_len + art = pixelart.picture_text(picture, width - indent, indent=indent) + lines += render_lines(art, width, no_wrap=True) urls = links.urls(body) if _URL_CODES and image is None else [] if urls: lines += render_lines(qr_strip(urls, width, indent=prefix.cell_len), width) diff --git a/meshterm/ui/pixelart.py b/meshterm/ui/pixelart.py new file mode 100644 index 0000000..62dcd67 --- /dev/null +++ b/meshterm/ui/pixelart.py @@ -0,0 +1,124 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Draw a pixel image (MCOimg) in the terminal with half blocks. + +A cell is approximately two times as tall as it is wide. Thus a cell holds two pixels, one +above the other, and each pixel is square: ``▀`` with the top pixel as its colour and the +bottom pixel as its background. A transparent pixel shows the page. A cell with only the +bottom pixel is ``▄`` in that colour, and a cell with no pixel is a space. + +An image that is wider than the lane, or taller than the rows that the platform can give +it, becomes smaller (refer to :func:`fit`). Pixel art loses detail when it becomes smaller, +but an image that is cut loses more: the user sees only a part of it. +""" + +from __future__ import annotations + +from functools import lru_cache +from typing import TYPE_CHECKING + +from rich.style import Style +from rich.text import Text + +from ..core import mcoimg +from ..platforms import Platform, on_platform + +if TYPE_CHECKING: + from ..core.mcoimg import Picture + +RGB = tuple[int, int, int] + +#: The most rows that an image can use under a message, on the active platform. The frame +#: takes some rows (the title bar, the footer, a header, the sender chip), so an image of +#: this height and its message are visible together. +_max_rows = 20 + +#: The rows of a frame that an image does not get: the title bar, the header or footer, +#: the sender chip, and the line of the message. +_CHROME_ROWS = 4 + + +def _bind(platform: Platform) -> None: + global _max_rows + _max_rows = max(4, platform.readable_rows - _CHROME_ROWS) + + +on_platform(_bind) + + +@lru_cache(maxsize=128) +def decoded(body: str) -> Picture | None: + """The image of a message body, or ``None``. It keeps the last results. + + A transcript paints many times while a message is visible. Each paint asks again, and + the cache answers without a second decode. + """ + return mcoimg.decode(body) + + +def fit(width: int, height: int, max_cols: int, max_rows: int) -> tuple[int, int]: + """The size in pixels at which to draw an image of ``width`` × ``height``. + + The image keeps its proportions. It never becomes larger, and it becomes smaller only + to fit ``max_cols`` cells and ``max_rows`` rows (two pixels in each row). + """ + scale = min(1.0, max_cols / width, (max_rows * 2) / height) + return max(1, int(width * scale)), max(1, int(height * scale)) + + +def picture_text(picture: Picture, max_cols: int, *, indent: int = 0) -> Text: + """Draw ``picture`` as lines of half blocks, each after ``indent`` spaces. + + Args: + picture: The decoded image. + max_cols: The most cells that the image can use, after the indent. + indent: The cells of page before each line (the indent of the body of a message). + + Returns: + One :class:`~rich.text.Text` with a line for each two rows of pixels. It has no + newline after the last line. + """ + cols, rows = fit(picture.width, picture.height, max(1, max_cols), _max_rows) + pixel = _sampler(picture, cols, rows) + text = Text(no_wrap=True) + for y in range(0, rows, 2): + if y: + text.append("\n") + text.append(" " * indent) + for x in range(cols): + top = pixel(x, y) + bottom = pixel(x, y + 1) if y + 1 < rows else None + text.append(*_cell(top, bottom)) + return text + + +def _sampler(picture: Picture, cols: int, rows: int): # noqa: ANN202 + """A function that gives the pixel at ``(x, y)`` of the image drawn at ``cols`` × ``rows``. + + A smaller image takes the nearest pixel of the original, so the colours stay the + colours of the palette. A mix of colours makes pixel art look blurred. + """ + width, height, pixels = picture.width, picture.height, picture.pixels + + def pixel(x: int, y: int) -> RGB | None: + return pixels[(y * height // rows) * width + (x * width // cols)] + + return pixel + + +def _cell(top: RGB | None, bottom: RGB | None) -> tuple[str, Style | None]: + """The character and the style of one cell, for its top and bottom pixels.""" + if top is None and bottom is None: + return " ", None + if top is None: + return "▄", Style(color=_hex(bottom)) + if bottom is None: + return "▀", Style(color=_hex(top)) + if top == bottom: + return "█", Style(color=_hex(top)) + return "▀", Style(color=_hex(top), bgcolor=_hex(bottom)) + + +def _hex(rgb: RGB | None) -> str: + """The colour of a pixel as ``#rrggbb``.""" + r, g, b = rgb # type: ignore[misc] + return f"#{r:02x}{g:02x}{b:02x}" diff --git a/tests/data/mcoimg/README.md b/tests/data/mcoimg/README.md new file mode 100644 index 0000000..676ffb6 --- /dev/null +++ b/tests/data/mcoimg/README.md @@ -0,0 +1,42 @@ +# MCOimg test vectors + +These two files are the test vectors of version 3 of the MCOimg pixel image format. They +come without change from the folder `docs/mcoimg-js/tests/` of the meshcore-open repository +([HDDen/meshcore-open](https://github.com/HDDen/meshcore-open), a fork of +[zjs81/meshcore-open](https://github.com/zjs81/meshcore-open)): + +- `v3-js-decoder-fixtures.json`: 39 images, one or more for each container, block + algorithm, scan order, and local palette form. +- `v3-js-encoder-fixtures.json`: 6 images that the JavaScript encoder of the format made. + +Each vector has the `im3:` text of an image, its size, its palette profile, and the palette +reference of each pixel. `tests/test_mcoimg.py` decodes each text and compares the result. +MeshTerm does not include these files in its package. + +The files are under the MIT licence of the meshcore-open repository: + + + +MIT License + +Copyright (c) 2025 zjs81 + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + diff --git a/tests/data/mcoimg/v3-js-decoder-fixtures.json b/tests/data/mcoimg/v3-js-decoder-fixtures.json new file mode 100644 index 0000000..b8a3f6f --- /dev/null +++ b/tests/data/mcoimg/v3-js-decoder-fixtures.json @@ -0,0 +1,847 @@ +{ + "schema": 1, + "generator": "docs/mcoimg-js/tests/v3-decoder-fixtures.js", + "fixtures": [ + { + "name": "rawGlobal", + "bodyBase64": "egGNAEK+AQ==", + "appPayloadBase64": "E3oBjQBCvgE=", + "text": "im3:g/5WjAL`NA", + "width": 4, + "height": 2, + "paletteProfile": "master4", + "pixels": [ + 0, + 1, + 2, + 3, + 3, + 2, + 1, + 0 + ], + "transparentColor": null, + "container": "compactBlock", + "algorithm": "rawGlobal" + }, + { + "name": "rawLocal", + "bodyBase64": "egGNECLWAg==", + "appPayloadBase64": "E3oBjRAi1gI=", + "text": "im3:g/5W6LuitA", + "width": 4, + "height": 2, + "paletteProfile": "master4", + "pixels": [ + 0, + 3, + 0, + 3, + 3, + 0, + 3, + 0 + ], + "transparentColor": null, + "container": "compactBlock", + "algorithm": "rawLocal" + }, + { + "name": "compactRle", + "bodyBase64": "egGNICCmIQ==", + "appPayloadBase64": "E3oBjSAgpiE=", + "text": "im3:g/5W[Wqi^F", + "width": 4, + "height": 2, + "paletteProfile": "master4", + "pixels": [ + 0, + 0, + 0, + 3, + 3, + 0, + 0, + 0 + ], + "transparentColor": null, + "container": "block", + "algorithm": "compactRle" + }, + { + "name": "compactSparse", + "bodyBase64": "egGNMABOIgA=", + "appPayloadBase64": "E3oBjTAATiIA", + "text": "im3:g/5WNi+>CGA", + "width": 4, + "height": 2, + "paletteProfile": "master4", + "pixels": [ + 0, + 3, + 3, + 0, + 0, + 3, + 0, + 0 + ], + "transparentColor": null, + "container": "block", + "algorithm": "compactSparse" + }, + { + "name": "biColorMask", + "bodyBase64": "egGNQMJa", + "appPayloadBase64": "E3oBjUDCWg==", + "text": "im3:g/5Wktw8F", + "width": 4, + "height": 2, + "paletteProfile": "master4", + "pixels": [ + 0, + 3, + 0, + 3, + 3, + 0, + 3, + 0 + ], + "transparentColor": null, + "container": "compactBlock", + "algorithm": "biColorMask" + }, + { + "name": "rowRepeat", + "bodyBase64": "egGNUCDW", + "appPayloadBase64": "E3oBjVAg1g==", + "text": "im3:g/5W74qiN", + "width": 4, + "height": 2, + "paletteProfile": "master4", + "pixels": [ + 0, + 3, + 0, + 3, + 0, + 3, + 0, + 3 + ], + "transparentColor": null, + "container": "block", + "algorithm": "rowRepeat" + }, + { + "name": "lzPixels", + "bodyBase64": "egGNYCAWHw==", + "appPayloadBase64": "E3oBjWAgFh8=", + "text": "im3:g/5W](qiqF", + "width": 4, + "height": 2, + "paletteProfile": "master4", + "pixels": [ + 0, + 3, + 0, + 3, + 0, + 3, + 0, + 3 + ], + "transparentColor": null, + "container": "block", + "algorithm": "lzPixels" + }, + { + "name": "quadtree", + "bodyBase64": "egEEB2J9", + "appPayloadBase64": "E3oBBAdifQ==", + "text": "im3:g/N\"qC8]D", + "width": 2, + "height": 2, + "paletteProfile": "master4", + "pixels": [ + 0, + 3, + 3, + 0 + ], + "transparentColor": null, + "container": "block", + "algorithm": "quadtree" + }, + { + "name": "bitplanesRawAndRle", + "bodyBase64": "egGNgGByqm0=", + "appPayloadBase64": "E3oBjYBgcqpt", + "text": "im3:g/5Wl\"#zslb", + "width": 4, + "height": 2, + "paletteProfile": "master4", + "pixels": [ + 0, + 1, + 0, + 1, + 2, + 3, + 2, + 3 + ], + "transparentColor": null, + "container": "block", + "algorithm": "bitplanes" + }, + { + "name": "adaptiveBitplanesRaw", + "bodyBase64": "egGNkCCmBQ==", + "appPayloadBase64": "E3oBjZAgpgU=", + "text": "im3:g/5W6Lri\"A", + "width": 4, + "height": 2, + "paletteProfile": "master4", + "pixels": [ + 0, + 3, + 0, + 3, + 3, + 0, + 3, + 0 + ], + "transparentColor": null, + "container": "block", + "algorithm": "adaptiveBitplanes" + }, + { + "name": "directBitplanes", + "bodyBase64": "egiNoEAVM3g=", + "appPayloadBase64": "E3oIjaBAFTN4", + "text": "im3:g/WX[Wyd~I8", + "width": 4, + "height": 2, + "paletteProfile": "grayscale8", + "pixels": [ + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7 + ], + "transparentColor": null, + "container": "block", + "algorithm": "directBitplanes" + }, + { + "name": "compactRowDelta", + "bodyBase64": "egGNsCCmAA==", + "appPayloadBase64": "E3oBjbAgpgA=", + "text": "im3:g/5WNiriKA", + "width": 4, + "height": 2, + "paletteProfile": "master4", + "pixels": [ + 0, + 3, + 0, + 3, + 0, + 3, + 0, + 3 + ], + "transparentColor": null, + "container": "block", + "algorithm": "compactRowDelta" + }, + { + "name": "directRowDelta", + "bodyBase64": "egiNwADRAA==", + "appPayloadBase64": "E3oIjcAA0QA=", + "text": "im3:g/WXkt6FNA", + "width": 4, + "height": 2, + "paletteProfile": "grayscale8", + "pixels": [ + 0, + 1, + 2, + 3, + 0, + 1, + 2, + 3 + ], + "transparentColor": null, + "container": "block", + "algorithm": "directRowDelta" + }, + { + "name": "rowDelta", + "bodyBase64": "egGN0CBGAw==", + "appPayloadBase64": "E3oBjdAgRgM=", + "text": "im3:g/5W74ri0A", + "width": 4, + "height": 2, + "paletteProfile": "master4", + "pixels": [ + 0, + 3, + 0, + 3, + 0, + 3, + 0, + 3 + ], + "transparentColor": null, + "container": "block", + "algorithm": "rowDelta" + }, + { + "name": "varUintRle", + "bodyBase64": "egGN4CA2UMAA", + "appPayloadBase64": "E3oBjeAgNlDAAA==", + "text": "im3:g/5W](riJOFBA", + "width": 4, + "height": 2, + "paletteProfile": "master4", + "pixels": [ + 0, + 0, + 0, + 3, + 3, + 0, + 0, + 0 + ], + "transparentColor": null, + "container": "block", + "algorithm": "varUintRle" + }, + { + "name": "varUintSparse", + "bodyBase64": "egGN8AAWCBAQCAA=", + "appPayloadBase64": "E3oBjfAAFggQEAgA", + "text": "im3:g/5WO?+hmB2WgAA", + "width": 4, + "height": 2, + "paletteProfile": "master4", + "pixels": [ + 0, + 3, + 3, + 0, + 0, + 3, + 0, + 0 + ], + "transparentColor": null, + "container": "block", + "algorithm": "varUintSparse" + }, + { + "name": "adaptiveLegacyRle", + "bodyBase64": "egEdkCDOBg==", + "appPayloadBase64": "E3oBHZAgzgY=", + "text": "im3:g/5WeLs?RB", + "width": 8, + "height": 1, + "paletteProfile": "master4", + "pixels": [ + 0, + 0, + 0, + 0, + 3, + 3, + 3, + 3 + ], + "transparentColor": null, + "container": "block", + "algorithm": "adaptiveBitplanes" + }, + { + "name": "adaptiveShortRle", + "bodyBase64": "egEdkCCeNg==", + "appPayloadBase64": "E3oBHZAgnjY=", + "text": "im3:g/5WeLs?2J", + "width": 8, + "height": 1, + "paletteProfile": "master4", + "pixels": [ + 0, + 0, + 3, + 3, + 3, + 0, + 0, + 0 + ], + "transparentColor": null, + "container": "block", + "algorithm": "adaptiveBitplanes" + }, + { + "name": "adaptiveConstantZero", + "bodyBase64": "egEdkCA+", + "appPayloadBase64": "E3oBHZAgPg==", + "text": "im3:g/5WeLs?D", + "width": 8, + "height": 1, + "paletteProfile": "master4", + "pixels": [ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0 + ], + "transparentColor": null, + "container": "block", + "algorithm": "adaptiveBitplanes" + }, + { + "name": "adaptiveConstantOne", + "bodyBase64": "egEdkCB+", + "appPayloadBase64": "E3oBHZAgfg==", + "text": "im3:g/5WeLs?H", + "width": 8, + "height": 1, + "paletteProfile": "master4", + "pixels": [ + 3, + 3, + 3, + 3, + 3, + 3, + 3, + 3 + ], + "transparentColor": null, + "container": "block", + "algorithm": "adaptiveBitplanes" + }, + { + "name": "adaptiveSparseOne", + "bodyBase64": "egEdkCC+CQE=", + "appPayloadBase64": "E3oBHZAgvgkB", + "text": "im3:g/5WeLs?%uA", + "width": 8, + "height": 1, + "paletteProfile": "master4", + "pixels": [ + 0, + 3, + 0, + 0, + 0, + 0, + 3, + 0 + ], + "transparentColor": null, + "container": "block", + "algorithm": "adaptiveBitplanes" + }, + { + "name": "adaptiveSparseZero", + "bodyBase64": "egEdkCD+CQE=", + "appPayloadBase64": "E3oBHZAg/gkB", + "text": "im3:g/5WeLs?*uA", + "width": 8, + "height": 1, + "paletteProfile": "master4", + "pixels": [ + 3, + 0, + 3, + 3, + 3, + 3, + 0, + 3 + ], + "transparentColor": null, + "container": "block", + "algorithm": "adaptiveBitplanes" + }, + { + "name": "boundsBlock", + "bodyBase64": "egEMQgQEBATgAQ==", + "appPayloadBase64": "E3oBDEIEBAQE4AE=", + "text": "im3:g/N\"UXbLi\"+>BA", + "width": 4, + "height": 4, + "paletteProfile": "master4", + "pixels": [ + 0, + 0, + 0, + 0, + 0, + 3, + 3, + 0, + 0, + 3, + 3, + 0, + 0, + 0, + 0, + 0 + ], + "transparentColor": null, + "container": "boundsBlock", + "algorithm": "compactRle" + }, + { + "name": "compactBoundsBlock", + "bodyBase64": "egEMYFTlAQ==", + "appPayloadBase64": "E3oBDGBU5QE=", + "text": "im3:g/N\"+h\"OPA", + "width": 4, + "height": 4, + "paletteProfile": "master4", + "pixels": [ + 0, + 0, + 0, + 0, + 0, + 1, + 2, + 0, + 0, + 3, + 1, + 0, + 0, + 0, + 0, + 0 + ], + "transparentColor": null, + "container": "compactBoundsBlock", + "algorithm": "rawGlobal" + }, + { + "name": "regions", + "bodyBase64": "egEMgAQEBAQEtQE=", + "appPayloadBase64": "E3oBDIAEBAQEBLUB", + "text": "im3:g/N\"CtbLi\"lB/EA", + "width": 4, + "height": 4, + "paletteProfile": "master4", + "pixels": [ + 0, + 0, + 0, + 0, + 0, + 1, + 3, + 0, + 0, + 3, + 1, + 0, + 0, + 0, + 0, + 0 + ], + "transparentColor": null, + "container": "regions", + "algorithm": "rawGlobal" + }, + { + "name": "compactRegionsSharedDelta", + "bodyBase64": "egGNEMqDGrUAQAI=", + "appPayloadBase64": "E3oBjRDKgxq1AEAC", + "text": "im3:g/5W6LdV9x\"AdZA", + "width": 4, + "height": 2, + "paletteProfile": "master4", + "pixels": [ + 1, + 3, + 3, + 1, + 3, + 1, + 1, + 3 + ], + "transparentColor": null, + "container": "compactRegionsStream", + "algorithm": "rawGlobal" + }, + { + "name": "solidBackground", + "bodyBase64": "egEAwg==", + "appPayloadBase64": "E3oBAMI=", + "text": "im3:g/LAU)", + "width": 1, + "height": 1, + "paletteProfile": "master4", + "pixels": [ + 2 + ], + "transparentColor": null, + "container": "solidBackground", + "algorithm": "rawGlobal" + }, + { + "name": "solidRects", + "bodyBase64": "egEM4GBV", + "appPayloadBase64": "E3oBDOBgVQ==", + "text": "im3:g/N\",>M8C", + "width": 4, + "height": 4, + "paletteProfile": "master4", + "pixels": [ + 0, + 0, + 0, + 0, + 0, + 3, + 3, + 0, + 0, + 3, + 3, + 0, + 0, + 0, + 0, + 0 + ], + "transparentColor": null, + "container": "solidRects", + "algorithm": "rawGlobal" + }, + { + "name": "implicitWhiteSolid", + "bodyBase64": "ekEEwA==", + "appPayloadBase64": "E3pBBMA=", + "text": "im3:g/)FCtB", + "width": 2, + "height": 2, + "paletteProfile": "master4", + "pixels": [ + 0, + 0, + 0, + 0 + ], + "transparentColor": null, + "container": "solidBackground", + "algorithm": "rawGlobal" + }, + { + "name": "transparentSolid", + "bodyBase64": "eoEEwgM=", + "appPayloadBase64": "E3qBBMID", + "text": "im3:g/iLnuHA", + "width": 2, + "height": 2, + "paletteProfile": "master4", + "pixels": [ + 2, + 2, + 2, + 2 + ], + "transparentColor": 3, + "container": "solidBackground", + "algorithm": "rawGlobal" + }, + { + "name": "scanV", + "bodyBase64": "ehGJIGByEGQQ", + "appPayloadBase64": "E3oRiSBgchBkEA==", + "text": "im3:g/DY@WhN[CFXA", + "width": 3, + "height": 2, + "paletteProfile": "master4", + "pixels": [ + 0, + 2, + 0, + 1, + 3, + 1 + ], + "transparentColor": null, + "container": "block", + "algorithm": "compactRle" + }, + { + "name": "scanS", + "bodyBase64": "eiGJIGByEGQQ", + "appPayloadBase64": "E3ohiSBgchBkEA==", + "text": "im3:g/oZ@WhN[CFXA", + "width": 3, + "height": 2, + "paletteProfile": "master4", + "pixels": [ + 0, + 1, + 2, + 1, + 0, + 3 + ], + "transparentColor": null, + "container": "block", + "algorithm": "compactRle" + }, + { + "name": "scanSV", + "bodyBase64": "ejGJIGByEGQQ", + "appPayloadBase64": "E3oxiSBgchBkEA==", + "text": "im3:g/=a@WhN[CFXA", + "width": 3, + "height": 2, + "paletteProfile": "master4", + "pixels": [ + 0, + 3, + 0, + 1, + 2, + 1 + ], + "transparentColor": null, + "container": "block", + "algorithm": "compactRle" + }, + { + "name": "paletteBitmap", + "bodyBase64": "egENEJI0", + "appPayloadBase64": "E3oBDRCSNA==", + "text": "im3:g/5WaL%ZD", + "width": 4, + "height": 1, + "paletteProfile": "master4", + "pixels": [ + 0, + 3, + 3, + 0 + ], + "transparentColor": null, + "container": "compactBlock", + "algorithm": "rawLocal" + }, + { + "name": "paletteSortedDelta", + "bodyBase64": "egINEDJBIgM=", + "appPayloadBase64": "E3oCDRAyQSID", + "text": "im3:g/%WaL&GDzB", + "width": 4, + "height": 1, + "paletteProfile": "master8", + "pixels": [ + 0, + 2, + 4, + 2 + ], + "transparentColor": null, + "container": "compactBlock", + "algorithm": "rawLocal" + }, + { + "name": "paletteRangeRuns", + "bodyBase64": "egINENJAFTk=", + "appPayloadBase64": "E3oCDRDSQBU5", + "text": "im3:g/%WaL4E)wc", + "width": 4, + "height": 1, + "paletteProfile": "master8", + "pixels": [ + 0, + 1, + 5, + 6 + ], + "transparentColor": null, + "container": "compactBlock", + "algorithm": "rawLocal" + }, + { + "name": "paletteBankBitmaps", + "bodyBase64": "eg8NEPIrEAAAAAAAAAAgAAAAAAAAAFA=", + "appPayloadBase64": "E3oPDRDyKxAAAAAAAAAAIAAAAAAAAABQ", + "text": "im3:g/>XaLT(XaL$stPmGlE", + "width": 4, + "height": 1, + "paletteProfile": "dynamicGlobal512", + "pixels": [ + 193, + 201, + 209, + 201 + ], + "transparentColor": null, + "container": "compactBlock", + "algorithm": "rawLocal" + }, + { + "name": "paletteOrderedMultiBank", + "bodyBase64": "eg8NEPI3LBAUDAly", + "appPayloadBase64": "E3oPDRDyNywQFAwJcg==", + "text": "im3:g/>XaL$s+HUc,LJo", + "width": 4, + "height": 1, + "paletteProfile": "dynamicGlobal512", + "pixels": [ + 1, + 130, + 3, + 132 + ], + "transparentColor": null, + "container": "compactBlock", + "algorithm": "rawLocal" + } + ] +} diff --git a/tests/data/mcoimg/v3-js-encoder-fixtures.json b/tests/data/mcoimg/v3-js-encoder-fixtures.json new file mode 100644 index 0000000..8128b6d --- /dev/null +++ b/tests/data/mcoimg/v3-js-encoder-fixtures.json @@ -0,0 +1,792 @@ +{ + "schema": 1, + "generator": "mcoimg-v3-codec.global.js Normal/High encoder", + "fixtures": [ + { + "name": "mono-checker-normal", + "width": 9, + "height": 7, + "paletteProfile": "mono", + "pixels": [ + 0, + 1, + 0, + 1, + 0, + 1, + 0, + 1, + 0, + 1, + 0, + 1, + 0, + 1, + 0, + 1, + 0, + 1, + 0, + 1, + 0, + 1, + 0, + 1, + 0, + 1, + 0, + 1, + 0, + 1, + 0, + 1, + 0, + 1, + 0, + 1, + 0, + 1, + 0, + 1, + 0, + 1, + 0, + 1, + 0, + 1, + 0, + 1, + 0, + 1, + 0, + 1, + 0, + 1, + 0, + 1, + 0, + 1, + 0, + 1, + 0, + 1, + 0 + ], + "compressionLevel": "normal", + "maxRegions": 16, + "bodyBase64": "QAAhY6DkMwE=", + "appPayloadBase64": "E0AAIWOg5DMB", + "text": "im3:TAYL>iBNGbA", + "byteLength": 8, + "charLength": 15, + "subtypeVersion": 19, + "packetNonce": 64, + "mode": "extended", + "scan": "h", + "container": "block", + "algorithm": "lzPixels", + "backgroundColor": 0, + "regionCount": 0 + }, + { + "name": "master8-sparse-high", + "width": 12, + "height": 10, + "paletteProfile": "master8", + "pixels": [ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 1, + 1, + 1, + 1, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 1, + 2, + 2, + 1, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 1, + 2, + 2, + 1, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 1, + 1, + 1, + 1, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 3, + 3, + 3, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 3, + 4, + 3, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 3, + 3, + 3, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0 + ], + "compressionLevel": "high", + "maxRegions": 32, + "bodyBase64": "QUKtFJoQMSMRmAGWkhEC", + "appPayloadBase64": "E0FCrRSaEDEjEZgBlpIRAg==", + "text": "im3:CDecxOjD61JY`R)0nxQA", + "byteLength": 15, + "charLength": 24, + "subtypeVersion": 19, + "packetNonce": 65, + "mode": "regionsBg", + "scan": "h", + "container": "compactRegionsStream", + "algorithm": "rawGlobal", + "backgroundColor": 0, + "regionCount": 2 + }, + { + "name": "master16-regions-high", + "width": 16, + "height": 12, + "paletteProfile": "master16", + "pixels": [ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 1, + 1, + 1, + 1, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 2, + 2, + 0, + 0, + 0, + 1, + 3, + 3, + 1, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 2, + 2, + 0, + 0, + 0, + 1, + 3, + 3, + 1, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 1, + 1, + 1, + 1, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 4, + 4, + 4, + 4, + 4, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 4, + 5, + 5, + 5, + 4, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 4, + 5, + 6, + 5, + 4, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 4, + 5, + 5, + 5, + 4, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 4, + 4, + 4, + 4, + 4, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0 + ], + "compressionLevel": "high", + "maxRegions": 32, + "bodyBase64": "QkO9JZpExIyIAWbAUQApIxZEwCkHLkI=", + "appPayloadBase64": "E0JDvSWaRMSMiAFmwFEAKSMWRMApBy5C", + "text": "im3: None: def test_a_pixel_image_shows_a_short_line_not_its_text() -> None: - """A body that is an MCOimg image shows its size in place of its Base91 text.""" + """A body that is an MCOimg image shows its size and the image, not its Base91 text.""" text = "im3:g/5WjAL`NA" messages = [ChatMessage(text=text, peer="d4e5f6a7")] screen = _screen(_StubSession(), send=None, messages=messages) lines = [_strip_ansi(ln) for ln in screen._body_lines(text, messages[0], 60)] - assert len(lines) == 1 assert lines[0].endswith("image · 4×2 · 4 colours") - assert "g/5W" not in lines[0] + assert not any("g/5W" in line for line in lines) + # Under the line, the 4 x 2 image is one row of four half blocks at the body indent. + assert len(lines) == 2 + assert lines[1].strip() and set(lines[1].strip()) <= set("▀▄█") def test_wrapped_body_hangs_under_the_first_line() -> None: @@ -3909,4 +3911,4 @@ def test_public_offer_add_writes_slot_zero(monkeypatch: pytest.MonkeyPatch) -> N ctx, writes = _offer_ctx(True, monkeypatch) added = asyncio.run(_add_public_channel(ctx)) assert writes == [(0, "Public", DEFAULT_PUBLIC_SECRET)] - assert added is not None and added.on_device and added.channel_idx == 0 \ No newline at end of file + assert added is not None and added.on_device and added.channel_idx == 0 diff --git a/tests/test_mcoimg.py b/tests/test_mcoimg.py index 6b299e9..5450472 100644 --- a/tests/test_mcoimg.py +++ b/tests/test_mcoimg.py @@ -9,9 +9,15 @@ the palette profile that its encoder used. from __future__ import annotations +import json +import random +import time +from pathlib import Path + import pytest -from meshterm.core.mcoimg import PixelImage, base91_decode, recognize +from meshterm.core import mcoimg, mcoimg_palettes +from meshterm.core.mcoimg import PixelImage, _decode_refs, base91_decode, decode, recognize #: (text, width, height, colours) from the version 3 vectors: one case for each mode of #: the dimensions and for each palette profile that the vectors use. @@ -27,6 +33,7 @@ _V3_CASES = [ def test_a_version_3_image_gives_its_size_and_colours( text: str, width: int, height: int, colours: int ) -> None: + """The header of a version 3 image gives its size and the colours of its profile.""" assert recognize(text) == PixelImage(3, width, height, colours) @@ -36,10 +43,12 @@ def test_base91_decodes_to_the_payload_of_the_vector() -> None: def test_a_version_1_or_2_image_has_no_header_to_read() -> None: + """An ``im:`` image is an image, but MeshTerm cannot read its header.""" assert recognize("im:CC&tj68MFSB") == PixelImage(None) def test_spaces_at_the_ends_are_permitted() -> None: + """Spaces and newlines around the image do not stop the recognition.""" assert recognize(" im3:g/5WjAL`NA \n") == PixelImage(3, 4, 2, 4) @@ -56,8 +65,249 @@ def test_spaces_at_the_ends_are_permitted() -> None: ], ) def test_text_that_is_not_an_image(body: str) -> None: + """Words that a person typed are not an image.""" assert recognize(body) is None def test_an_unknown_version_is_an_image_with_no_header() -> None: + """A version that MeshTerm does not know is an image with no header.""" assert recognize("im4:CC&tj68MFSB") == PixelImage(4) + + +# The pixel decoder of version 3. + +_DATA = Path(__file__).parent / "data" / "mcoimg" + +#: The palette profiles by name, in the order of their ids. +_PROFILE_NAMES = ( + "mono", + "master4", + "master8", + "master16", + "master32", + "master64", + "grayscale16", + "grayscale32", + "grayscale8", + "dynamicGlobal8", + "dynamicGlobal16", + "dynamicGlobal32", + "dynamicGlobal64", + "dynamicGlobal128", + "dynamicGlobal256", + "dynamicGlobal512", +) + + +def _vectors() -> list[dict]: + """All the vectors of the two files of ``tests/data/mcoimg/``.""" + found = [] + for name in ("v3-js-decoder-fixtures.json", "v3-js-encoder-fixtures.json"): + found += json.loads((_DATA / name).read_text(encoding="utf-8"))["fixtures"] + return found + + +_VECTORS = _vectors() + + +def test_the_vector_files_have_all_their_cases() -> None: + """The two vector files have 39 and 6 cases.""" + assert len(_VECTORS) == 45 + + +@pytest.mark.parametrize("vector", _VECTORS, ids=[vector["name"] for vector in _VECTORS]) +def test_a_vector_decodes_to_its_palette_references(vector: dict) -> None: + """Each vector decodes to its size, its profile, and the reference of each pixel.""" + indexed = _decode_refs(vector["text"]) + assert indexed is not None + assert (indexed.width, indexed.height) == (vector["width"], vector["height"]) + assert _PROFILE_NAMES[indexed.profile] == vector["paletteProfile"] + assert indexed.refs == vector["pixels"] + assert indexed.transparent == vector.get("transparentColor") + + +def _rgb(profile: str, ref: int) -> tuple[int, int, int]: + """The colour of a palette reference of a profile, from the colour tables.""" + if profile.startswith("dynamic"): + return mcoimg_palettes.GLOBAL_512[ref] + names = { + "mono": "MONO", + "grayscale8": "GREY_8", + "grayscale16": "GREY_16", + "grayscale32": "GREY_32", + } + name = names.get(profile) or "MASTER_" + profile.removeprefix("master") + return getattr(mcoimg_palettes, name)[ref] + + +@pytest.mark.parametrize("vector", _VECTORS, ids=[vector["name"] for vector in _VECTORS]) +def test_a_vector_decodes_to_the_colours_of_its_profile(vector: dict) -> None: + """Each vector decodes to the RGB colours of its profile, with transparent pixels.""" + picture = decode(vector["text"]) + assert picture is not None + assert (picture.width, picture.height) == (vector["width"], vector["height"]) + clear = vector.get("transparentColor") + expected = tuple( + None if ref == clear else _rgb(vector["paletteProfile"], ref) for ref in vector["pixels"] + ) + assert picture.pixels == expected + + +def test_mono_is_white_and_black() -> None: + """In the ``mono`` profile, colour 0 is white and colour 1 is black.""" + picture = decode("im3:TAYL>iBNGbA") # mono-checker-normal, 9 x 7 + assert picture is not None + assert picture.pixels[:2] == ((255, 255, 255), (0, 0, 0)) + assert set(picture.pixels) == {(255, 255, 255), (0, 0, 0)} + + +def test_the_transparent_colour_gives_no_colour() -> None: + """A pixel of the transparent colour has no colour.""" + vector = next(v for v in _VECTORS if v["name"] == "master8-transparent-normal") + picture = decode(vector["text"]) + assert picture is not None + clear = [pixel is None for pixel in picture.pixels] + assert clear == [ref == 0 for ref in vector["pixels"]] + assert any(clear) + assert not all(clear) + + +def test_the_colour_tables_have_their_sizes() -> None: + """Each colour table has the size of its profile, and a dynamic table has no duplicates.""" + sizes = { + "MONO": 2, + "MASTER_4": 4, + "MASTER_8": 8, + "MASTER_16": 16, + "MASTER_32": 32, + "MASTER_64": 64, + "GREY_8": 8, + "GREY_16": 16, + "GREY_32": 32, + "GLOBAL_512": 512, + } + for name, size in sizes.items(): + assert len(getattr(mcoimg_palettes, name)) == size, name + for size in (8, 16, 32, 64, 128, 256, 512): + table = getattr(mcoimg_palettes, f"DYNAMIC_{size}") + assert len(table) == size + assert len(set(table)) == size + assert all(0 <= index < 512 for index in table) + assert mcoimg_palettes.DYNAMIC_512 == tuple(range(512)) + + +def test_decode_reads_only_version_3() -> None: + """The decoder gives ``None`` for an image of version 1 or 2 and for words.""" + assert decode("im:CC&tj68MFSB") is None + assert decode("hello") is None + assert decode("im3:hello") is None + + +@pytest.mark.parametrize("vector", _VECTORS, ids=[vector["name"] for vector in _VECTORS]) +def test_a_truncated_image_gives_none(vector: dict) -> None: + """An image with the end of its text cut off gives ``None``.""" + text = vector["text"] + for end in range(len("im3:"), len(text) - 1): + assert decode(text[:end]) is None + + +def test_a_changed_image_does_not_raise() -> None: + """Change each character of each vector. The result can be an image or ``None``.""" + alphabet = mcoimg._ALPHABET + for vector in _VECTORS: + text = vector["text"] + for index in range(len("im3:"), len(text)): + for char in alphabet[::7]: + decode(text[:index] + char + text[index + 1 :]) + + +def test_random_base91_does_not_raise() -> None: + """Random Base91 text after the prefix gives a picture or ``None``, and never an error.""" + chooser = random.Random(1234) + for _ in range(3000): + length = chooser.randint(1, 200) + text = "".join(chooser.choice(mcoimg._ALPHABET) for _ in range(length)) + decode("im3:g/" + text) + decode("im3:" + text) + + +def test_a_very_long_text_gives_none() -> None: + """The decoder does not read a text that is longer than the limit.""" + assert decode("im3:g/" + "A" * 10_000) is None + + +def _encode_raw_global(width: int, height: int, profile: int, refs: list[int]) -> str: + """Encode an image as ``compactBlock`` and ``rawGlobal``: the minimal encoder of the spec. + + Only square sizes up to 64 are done here (dimension mode 0). + """ + assert width == height <= 64 + bits = max(1, (len(_PROFILE_COLOURS_BY_ID[profile]) - 1).bit_length()) + fields = [(0, 2), (width - 1, 6), (0x20, 8)] + [(ref, bits) for ref in refs] + value = position = 0 + for field, count in fields: + value |= field << position + position += count + data = bytes([0x13, 0x5A, profile]) + value.to_bytes((position + 7) // 8, "little") + return "im3:" + _base91_encode(data) + + +def _base91_encode(data: bytes) -> str: + """The basE91 encoder of the spec.""" + alphabet = mcoimg._ALPHABET + out = [] + queue = count = 0 + for byte in data: + queue |= byte << count + count += 8 + if count > 13: + value = queue & 8191 + if value > 88: + queue >>= 13 + count -= 13 + else: + value = queue & 16383 + queue >>= 14 + count -= 14 + out += [alphabet[value % 91], alphabet[value // 91]] + if count: + out.append(alphabet[queue % 91]) + if count > 7 or queue > 90: + out.append(alphabet[queue // 91]) + return "".join(out) + + +_PROFILE_COLOURS_BY_ID = {5: mcoimg_palettes.MASTER_64} + + +def test_a_64_by_64_image_decodes_quickly() -> None: + """A 64 x 64 image of 64 colours decodes in less than 50 ms.""" + chooser = random.Random(5) + refs = [chooser.randrange(64) for _ in range(64 * 64)] + text = _encode_raw_global(64, 64, 5, refs) + start = time.perf_counter() + picture = decode(text) + elapsed = time.perf_counter() - start + assert picture is not None + assert picture.pixels == tuple(mcoimg_palettes.MASTER_64[ref] for ref in refs) + assert elapsed < 0.05 + + +def test_a_picture_draws_two_pixels_in_each_cell() -> None: + """Half blocks: the top pixel is the colour, the bottom pixel is the background.""" + from meshterm.ui.pixelart import picture_text + + red, blue = (255, 0, 0), (0, 0, 255) + picture = mcoimg.Picture(2, 3, (red, None, blue, red, red, None)) + lines = picture_text(picture, 10, indent=2).plain.split("\n") + # Row 0 over row 1: red over blue, nothing over red. Row 2 alone: red, nothing. + assert lines == [" ▀▄", " ▀ "] + + +def test_a_wide_picture_becomes_smaller_to_fit_the_lane() -> None: + """An image wider than the lane keeps its proportions and fits the lane.""" + from meshterm.ui.pixelart import fit + + assert fit(64, 64, 40, 40) == (40, 40) + assert fit(16, 16, 40, 40) == (16, 16) # never larger + assert fit(30, 30, 53, 5) == (10, 10) # five rows hold ten pixels