Skip to content

A lightweight Clip Studio Paint alternative with real-time multiplayer collaborative drawing. Built with Tauri and React.

11.1 KB
Raw Blame
/**
 * Pure binary wire-packet codec for InkStudio `CODE_TILE_DELTA` frames
 * (`EMPTY`, `RAW`, `LZ4`, `SOLID`, `SUBRECT_LZ4`).
 *
 * Zero `HTMLCanvasElement`, zero `SparseTileGrid`.
 * In desktop runtime, `ink-engine` (`crates/ink-engine/src/collab/mod.rs`) performs
 * native tile encoding/decoding directly against its Rust tile grid; this module
 * supplies wire header inspection and WebRTC Host Hub sub-rect op_log compaction.
 */

import { lz4CompressBlock, lz4DecompressBlock } from './lz4';
import {
  BYTES_1BIT,
  BYTES_32BIT,
  TILE_PIXELS,
  TILE_SIZE,
  TileFormat,
  getTileByteSize,
} from './tauriEnv';

export const TILE_CODEC_EMPTY = 0;
export const TILE_CODEC_RAW = 1;
export const TILE_CODEC_LZ4 = 2;
export const TILE_CODEC_SOLID = 3;
export const TILE_CODEC_SUBRECT_LZ4 = 4;

export const TILE_PACKET_HEADER_BYTES = 14;
export const TILE_SUBRECT_HEADER_BYTES = 6; // [rx: u8, ry: u8, rw: u16, rh: u16]

export interface TileSubRectData {
  rx: number;
  ry: number;
  rw: number;
  rh: number;
  data: Uint8Array;
}

export interface WireTilePayload {
  layerId: string;
  tileX: number;
  tileY: number;
  format: TileFormat;
  version: number;
  data: Uint8Array | null;
}

export type DecodedWireTilePacket =
  | { kind: 'full'; tile: WireTilePayload }
  | {
      kind: 'subrect';
      layerId: string;
      tileX: number;
      tileY: number;
      format: TileFormat;
      version: number;
      subRect: TileSubRectData;
    };

export function formatToWireCode(format: TileFormat): number {
  return format === 'monochrome-1bit' ? 1 : format === 'grayscale-8bit' ? 2 : 4;
}

export function wireCodeToFormat(formatCode: number): TileFormat | null {
  if (formatCode === 1) return 'monochrome-1bit';
  if (formatCode === 2) return 'grayscale-8bit';
  if (formatCode === 4) return 'color-32bit';
  return null;
}

function getExpectedSubRectByteLength(
  format: TileFormat,
  rx: number,
  ry: number,
  rw: number,
  rh: number
): number | null {
  if (
    !Number.isInteger(rx) ||
    !Number.isInteger(ry) ||
    !Number.isInteger(rw) ||
    !Number.isInteger(rh) ||
    rx < 0 ||
    ry < 0 ||
    rw < 1 ||
    rh < 1 ||
    rx + rw > TILE_SIZE ||
    ry + rh > TILE_SIZE
  ) {
    return null;
  }
  if (format === 'monochrome-1bit') {
    if ((rx & 7) !== 0 || (rw & 7) !== 0) return null;
    return (rw >>> 3) * rh;
  }
  if (format === 'grayscale-8bit') {
    return rw * rh;
  }
  return rw * rh * 4;
}

function detectSolidTilePayload(format: TileFormat, rawBytes: Uint8Array): Uint8Array | null {
  const expectedLen = getTileByteSize(format);
  if (rawBytes.byteLength !== expectedLen) return null;

  if (format === 'monochrome-1bit') {
    const first = rawBytes[0];
    if (first !== 0x00 && first !== 0xff) return null;
    for (let i = 1; i < expectedLen; i++) {
      if (rawBytes[i] !== first) return null;
    }
    return new Uint8Array([first]);
  }

  if (format === 'grayscale-8bit') {
    const first = rawBytes[0];
    for (let i = 1; i < expectedLen; i++) {
      if (rawBytes[i] !== first) return null;
    }
    return new Uint8Array([first]);
  }

  const r = rawBytes[0];
  const g = rawBytes[1];
  const b = rawBytes[2];
  const a = rawBytes[3];
  for (let i = 4; i < expectedLen; i += 4) {
    if (
      rawBytes[i] !== r ||
      rawBytes[i + 1] !== g ||
      rawBytes[i + 2] !== b ||
      rawBytes[i + 3] !== a
    ) {
      return null;
    }
  }
  return new Uint8Array([r, g, b, a]);
}

function expandSolidTilePayload(format: TileFormat, payload: Uint8Array): Uint8Array | null {
  if (format === 'monochrome-1bit') {
    if (payload.byteLength !== 1) return null;
    const v = payload[0];
    if (v !== 0x00 && v !== 0xff) return null;
    const data = new Uint8Array(BYTES_1BIT);
    if (v !== 0) data.fill(v);
    return data;
  }
  if (format === 'grayscale-8bit') {
    if (payload.byteLength !== 1) return null;
    const data = new Uint8Array(TILE_PIXELS);
    if (payload[0] !== 0) data.fill(payload[0]);
    return data;
  }
  if (payload.byteLength !== 4) return null;
  const data = new Uint8Array(BYTES_32BIT);
  const r = payload[0];
  const g = payload[1];
  const b = payload[2];
  const a = payload[3];
  if ((r | g | b | a) !== 0) {
    for (let i = 0; i < BYTES_32BIT; i += 4) {
      data[i] = r;
      data[i + 1] = g;
      data[i + 2] = b;
      data[i + 3] = a;
    }
  }
  return data;
}

export function applyTileSubRectPatch(
  targetData: Uint8Array,
  format: TileFormat,
  subRect: TileSubRectData
): boolean {
  const expectedTileLen = getTileByteSize(format);
  if (targetData.byteLength !== expectedTileLen) return false;
  const expectedSubLen = getExpectedSubRectByteLength(
    format,
    subRect.rx,
    subRect.ry,
    subRect.rw,
    subRect.rh
  );
  if (expectedSubLen === null || subRect.data.byteLength !== expectedSubLen) {
    return false;
  }

  if (format === 'color-32bit') {
    const rowBytes = subRect.rw * 4;
    const tileRowStride = TILE_SIZE * 4;
    const dstColOff = subRect.rx * 4;
    for (let row = 0; row < subRect.rh; row++) {
      const srcStart = row * rowBytes;
      const dstStart = (subRect.ry + row) * tileRowStride + dstColOff;
      targetData.set(subRect.data.subarray(srcStart, srcStart + rowBytes), dstStart);
    }
    return true;
  }

  if (format === 'grayscale-8bit') {
    for (let row = 0; row < subRect.rh; row++) {
      const srcStart = row * subRect.rw;
      const dstStart = (subRect.ry + row) * TILE_SIZE + subRect.rx;
      targetData.set(subRect.data.subarray(srcStart, srcStart + subRect.rw), dstStart);
    }
    return true;
  }

  const rowBytes = subRect.rw >>> 3;
  const tileRowStride = TILE_SIZE >>> 3;
  const dstColOff = subRect.rx >>> 3;
  for (let row = 0; row < subRect.rh; row++) {
    const srcStart = row * rowBytes;
    const dstStart = (subRect.ry + row) * tileRowStride + dstColOff;
    targetData.set(subRect.data.subarray(srcStart, srcStart + rowBytes), dstStart);
  }
  return true;
}

export function serializeWireTilePacket(tile: WireTilePayload): Uint8Array {
  const formatCode = formatToWireCode(tile.format);
  if (tile.data === null) {
    const packet = new Uint8Array(TILE_PACKET_HEADER_BYTES);
    const view = new DataView(packet.buffer, packet.byteOffset, packet.byteLength);
    view.setInt32(0, tile.tileX, true);
    view.setInt32(4, tile.tileY, true);
    view.setUint8(8, formatCode);
    view.setUint32(9, tile.version, true);
    view.setUint8(13, TILE_CODEC_EMPTY);
    return packet;
  }

  const expectedLen = getTileByteSize(tile.format);
  const rawBytes =
    tile.data.byteLength === expectedLen ? tile.data : new Uint8Array(expectedLen);

  const solidPayload = detectSolidTilePayload(tile.format, rawBytes);
  if (solidPayload !== null) {
    const packet = new Uint8Array(TILE_PACKET_HEADER_BYTES + solidPayload.byteLength);
    const view = new DataView(packet.buffer, packet.byteOffset, packet.byteLength);
    view.setInt32(0, tile.tileX, true);
    view.setInt32(4, tile.tileY, true);
    view.setUint8(8, formatCode);
    view.setUint32(9, tile.version, true);
    view.setUint8(13, TILE_CODEC_SOLID);
    packet.set(solidPayload, TILE_PACKET_HEADER_BYTES);
    return packet;
  }

  const compressed = lz4CompressBlock(rawBytes);
  const useLz4 = compressed.byteLength <= rawBytes.byteLength;
  const payload = useLz4 ? compressed : rawBytes;
  const codec = useLz4 ? TILE_CODEC_LZ4 : TILE_CODEC_RAW;

  const packet = new Uint8Array(TILE_PACKET_HEADER_BYTES + payload.byteLength);
  const view = new DataView(packet.buffer, packet.byteOffset, packet.byteLength);
  view.setInt32(0, tile.tileX, true);
  view.setInt32(4, tile.tileY, true);
  view.setUint8(8, formatCode);
  view.setUint32(9, tile.version, true);
  view.setUint8(13, codec);
  packet.set(payload, TILE_PACKET_HEADER_BYTES);
  return packet;
}

export function deserializeWireTilePacketStrict(
  layerId: string,
  packet: Uint8Array
): DecodedWireTilePacket | null {
  if (!packet || packet.byteLength < TILE_PACKET_HEADER_BYTES) {
    return null;
  }
  const view = new DataView(packet.buffer, packet.byteOffset, packet.byteLength);
  const tileX = view.getInt32(0, true);
  const tileY = view.getInt32(4, true);
  const formatCode = view.getUint8(8);
  const version = view.getUint32(9, true);
  const codec = view.getUint8(13);

  const format = wireCodeToFormat(formatCode);
  if (!format) return null;

  const expectedLen = getTileByteSize(format);
  const payload = packet.subarray(TILE_PACKET_HEADER_BYTES);

  if (codec === TILE_CODEC_SUBRECT_LZ4) {
    if (payload.byteLength < TILE_SUBRECT_HEADER_BYTES + 1) return null;
    const pView = new DataView(payload.buffer, payload.byteOffset, payload.byteLength);
    const rx = pView.getUint8(0);
    const ry = pView.getUint8(1);
    const rw = pView.getUint16(2, true);
    const rh = pView.getUint16(4, true);
    const expectedSubLen = getExpectedSubRectByteLength(format, rx, ry, rw, rh);
    if (expectedSubLen === null || expectedSubLen > BYTES_32BIT) return null;

    const lz4Bytes = payload.subarray(TILE_SUBRECT_HEADER_BYTES);
    const subData = lz4DecompressBlock(lz4Bytes, expectedSubLen, BYTES_32BIT);
    if (!subData) return null;

    return {
      kind: 'subrect',
      layerId,
      tileX,
      tileY,
      format,
      version,
      subRect: { rx, ry, rw, rh, data: subData },
    };
  }

  let data: Uint8Array | null;
  if (codec === TILE_CODEC_EMPTY) {
    if (payload.byteLength !== 0) return null;
    data = null;
  } else if (codec === TILE_CODEC_SOLID) {
    data = expandSolidTilePayload(format, payload);
    if (!data) return null;
  } else if (codec === TILE_CODEC_LZ4) {
    data = lz4DecompressBlock(payload, expectedLen, BYTES_32BIT);
    if (!data) return null;
  } else if (codec === TILE_CODEC_RAW) {
    if (payload.byteLength !== expectedLen) return null;
    data = new Uint8Array(expectedLen);
    data.set(payload);
  } else {
    return null;
  }

  return {
    kind: 'full',
    tile: {
      layerId,
      tileX,
      tileY,
      format,
      version,
      data,
    },
  };
}

/**
 * Composes a `TILE_CODEC_SUBRECT_LZ4` packet onto an existing self-contained base tile packet
 * (`RAW`, `LZ4`, or `SOLID`) and re-serializes it into a self-contained full tile packet.
 * Used by WebRTC Host Hub so op_log and snapshots never serve orphaned sub-rect patches.
 */
export function composeSubRectOntoTilePacket(
  layerId: string,
  basePacket: Uint8Array,
  subRectPacket: Uint8Array
): Uint8Array | null {
  const baseDecoded = deserializeWireTilePacketStrict(layerId, basePacket);
  if (!baseDecoded || baseDecoded.kind !== 'full' || !baseDecoded.tile.data) {
    return null;
  }
  const subDecoded = deserializeWireTilePacketStrict(layerId, subRectPacket);
  if (
    !subDecoded ||
    subDecoded.kind !== 'subrect' ||
    subDecoded.tileX !== baseDecoded.tile.tileX ||
    subDecoded.tileY !== baseDecoded.tile.tileY ||
    subDecoded.format !== baseDecoded.tile.format
  ) {
    return null;
  }
  const merged = new Uint8Array(baseDecoded.tile.data.byteLength);
  merged.set(baseDecoded.tile.data);
  if (!applyTileSubRectPatch(merged, subDecoded.format, subDecoded.subRect)) {
    return null;
  }
  return serializeWireTilePacket({
    ...baseDecoded.tile,
    data: merged,
    version: subDecoded.version,
  });
}