image formats: comments are specs only

This commit is contained in:
4DBug committed 2026-11-01 01:54:53 -05:00
1 parent 0bd7b87d2b
commit b5546e208e
40 files changed
+246 -626

No files matched your search

+7 -12
View File
@@ -1,11 +1,7 @@
--!strict
-- image/ani: Windows animated cursors (RIFF "ACON": the anih header, rate / seq chunks, LIST fram of icon chunks;
-- containers/Riff; new code). Decode: every step of the animation as img.frames (the seq order when there is one,
-- each step's rate or the default iDispRate in jiffies of 1/60 s as the delay), the icon chunks (ICO / CUR files)
-- through the api hook opts.decodeImage (F.load passes it; without it: UNSUPPORTED), the hotspots of CUR frames
-- (frame image meta.hotspot), INFO title / author (meta.text). The image is the first step; img.loops = 0 (cursors
-- loop forever). Encode: img.frames (or the image) through opts.encodeImage(frame, "ico") as icon chunks, with a
-- rate chunk when the delays differ. Not supported: raw (non-icon) frame bitmaps (AF_ICON clear: UNSUPPORTED).
-- image/ani: Windows animated cursor (RIFF "ACON": anih header, rate / seq chunks, LIST fram of ICO / CUR chunks).
-- Supports: the steps as img.frames (seq order; rate or iDispRate in 1/60 s jiffies), CUR hotspots, INFO title /
-- author; icons through opts.decodeImage / opts.encodeImage. Not supported: raw frame bitmaps (AF_ICON clear).
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
@@ -25,11 +21,11 @@ local Ani = {
-- ------------------------------------------------------------------------------------------------ types
export type DecodeOptions = {
decodeImage: ((buffer) -> (Types.Image?, Err.Err?))?, -- decodes the ICO / CUR frames (the api passes one)
maxFrames: number?, -- refuse more steps (default 10000)
decodeImage: ((buffer) -> (Types.Image?, Err.Err?))?,
maxFrames: number?, -- default 10000
}
export type EncodeOptions = {
encodeImage: ((Types.Image, string) -> (buffer?, Err.Err?))?, -- writes the ICO / CUR frames (the api passes one)
encodeImage: ((Types.Image, string) -> (buffer?, Err.Err?))?,
}
-- ------------------------------------------------------------------------------------------------ sniff
@@ -67,7 +63,6 @@ function Ani.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.E
if not decodeImage then
return nil, Err.new(Err.UNSUPPORTED, "icon frames need the decodeImage hook")
end
-- the icon chunks
local icons: { Types.Image } = {}
for _, c in f.chunks do
if c.id == "LIST" and Riff.listType(f, c) == "fram" then
@@ -98,7 +93,7 @@ function Ani.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.E
local im = icons[idx + 1]
if not im then
if s >= #icons and not seq then
break -- fewer icons than steps: keep what is there
break
end
return nil, Err.new(Err.CORRUPT, "step " .. s .. " names frame " .. idx)
end
+4 -14
View File
@@ -1,14 +1,7 @@
--!strict
-- image/blp: Blizzard BLP textures (Warcraft III: BLP1; World of Warcraft: BLP2), read, and BLP2 written
-- (uncompressed BGRA). Written from the wowdev.wiki BLP page; no code taken.
-- Decode, mip 0 (meta.source.mips counts the levels) to rgba8:
-- BLP1 JPEG: the shared JPEG header + the mip's data through codecs/image/Jpeg; 4-component files (the usual
-- Warcraft III layout) are BGRA without colour conversion, 3-component ones YCbCr -> BGR (R and B swapped back);
-- BLP1 palette: 8-bit indexes into a BGRA palette, then an 8-bit alpha plane when alphaBits is 8 (else opaque);
-- BLP2 palette: indexes + a 1 / 4 / 8-bit alpha plane (LSB first), DXT1 / DXT3 / DXT5 (codecs/image/Bcn: alpha
-- type 0 / 1 / 7), uncompressed BGRA.
-- Encode: BLP2 uncompressed BGRA with 8-bit alpha (opts.mips = true adds the box-filtered mip chain).
-- Not supported: BLP0 (external .b00 mip files), BLP2 JPEG (never used by the games).
-- image/blp: Blizzard BLP textures (BLP1 Warcraft III, BLP2 World of Warcraft), from the wowdev.wiki BLP page.
-- Supports: mip 0 of BLP1 JPEG (4 components: BGRA, no colour conversion) / palette and BLP2 palette (1 / 4 / 8-bit
-- alpha, LSB first) / DXT1 / DXT3 / DXT5 / BGRA; writes BLP2 BGRA + mips. Not supported: BLP0 (.b00 mips), BLP2 JPEG.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
@@ -29,7 +22,7 @@ local Blp = {
-- ------------------------------------------------------------------------------------------------ types
export type DecodeOptions = { maxPixels: number? } -- default 2^26
export type EncodeOptions = { mips: boolean? } -- write the mip chain (default false)
export type EncodeOptions = { mips: boolean? } -- default false
-- ------------------------------------------------------------------------------------------------ constants
local readu8, readu32, writeu32, writeu8 = buffer.readu8, buffer.readu32, buffer.writeu32, buffer.writeu8
@@ -41,13 +34,11 @@ function Blp.sniff(r: Bytes.Reader): number
end
-- ------------------------------------------------------------------------------------------------ decode
-- BGRA u32 (b at the lowest address) -> RGBA u32 with the given alpha
local function swap(v: number, a: number): number
local b, g, r = v % 256, (v // 256) % 256, (v // 65536) % 256
return r + g * 256 + b * 65536 + a * 16777216
end
-- alpha of pixel i from a packed plane at p of depth bits
local function alphaAt(b: buffer, p: number, depth: number, i: number): number
if depth == 8 then
return readu8(b, p + i)
@@ -190,7 +181,6 @@ function Blp.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.E
end
-- ------------------------------------------------------------------------------------------------ encode
-- halve(px, w, h) -> the next mip (2 x 2 box filter; odd edges repeat)
local function halve(px: buffer, w: number, h: number): (buffer, number, number)
local nw, nh = math.max(1, w // 2), math.max(1, h // 2)
local out = buffer.create(nw * nh * 4)
+8 -24
View File
@@ -1,16 +1,8 @@
--!strict
--!optimize 2
-- image/bmp: Windows / OS/2 BMP. Absorbed from bmp-luau b86aed6 (same author, no third-party code; the reader), plus a
-- new encoder. Decode: BITMAPCOREHEADER (OS/2 1.x, 12 bytes), OS/2 2.x (16..64), BITMAPINFOHEADER (40), the v2 / v3
-- variants (52 / 56), BITMAPV4HEADER / BITMAPV5HEADER (108 / 124); 1 / 2 / 4 / 8 bpp paletted, 16 bpp (555 or
-- BITFIELDS), 24 bpp, 32 bpp (BI_RGB, BITFIELDS, ALPHABITFIELDS), RLE8 / RLE4 (delta / end-of-line / end-of-bitmap),
-- bottom-up and top-down rows. Lenient: bfSize / biSizeImage are ignored, a bad bfOffBits falls back to the end of the
-- palette, a short or missing palette pads with opaque black, a truncated pixel array decodes as zero bytes, a 32-bit
-- image whose alpha is all zero is opaque. Masks scale as Pillow does (v * 255 // max).
-- Encode (rgba8): 8 bpp paletted when the image is opaque with at most 256 colours (palette in first-appearance
-- order), else 24 bpp when opaque, else 32 bpp with alpha (BITMAPV4HEADER + BITFIELDS, or BI_RGB with
-- opts.header = "info" as Pillow writes). Byte-identical to Pillow for 24 bpp, paletted and BI_RGB 32 bpp output.
-- Not supported: embedded JPEG / PNG, OS/2 Huffman / RLE24, writing RLE / 16 bpp / 1-4 bpp.
-- image/bmp: Windows / OS/2 BMP; absorbed from bmp-luau b86aed6 (same author), new encoder. Supports: headers 12 /
-- 16..64 / 40 / 52 / 56 / 108 / 124, 1..32 bpp, BITFIELDS / ALPHABITFIELDS, RLE8 / RLE4, both row orders, Pillow's
-- leniency and mask scaling; writes 8 / 24 / 32 bpp as Pillow. Not supported: embedded JPEG / PNG, OS/2 Huffman, RLE24.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
@@ -40,11 +32,11 @@ export type Info = {
}
export type DecodeOptions = {
maxPixels: number?, -- refuse images with more pixels than this (default 2^26 = 64 Mpx)
maxPixels: number?, -- default 2^26
}
export type EncodeOptions = {
bitDepth: (number | "auto")?, -- 8, 24, 32; default "auto": 8 when opaque with <= 256 colours, else 24 when opaque, else 32
header: ("v4" | "info")?, -- 32 bpp: "v4" (default, BITFIELDS with an alpha mask) or "info" (BI_RGB, as Pillow)
bitDepth: (number | "auto")?, -- default "auto": 8 if opaque with <= 256 colours, else 24 if opaque, else 32
header: ("v4" | "info")?, -- 32 bpp: "v4" (default, BITFIELDS) or "info" (BI_RGB, as Pillow)
}
-- ------------------------------------------------------------------------------------------------ constants
@@ -54,7 +46,6 @@ local COMPRESSION_NAMES = { [0] = "rgb", "rle8", "rle4", "bitfields", "jpeg", "p
local readu8, readu16, readu32, readi32 = buffer.readu8, buffer.readu16, buffer.readu32, buffer.readi32
local band, rshift, lshift, countrz = bit32.band, bit32.rshift, bit32.lshift, bit32.countrz
-- the reader's range as a buffer starting at offset 0 (copied when it is a part of a bigger buffer)
local function whole(r: Bytes.Reader): buffer
if r.base == 0 and r.limit == buffer.len(r.buf) then
return r.buf
@@ -70,7 +61,6 @@ function Bmp.sniff(r: Bytes.Reader): number
if r:peek(2) ~= "BM" then
return 0
end
-- a known header size: a strong match; "BM" alone is weak
local n = r:peekU8(14) + math.max(r:peekU8(15), 0) * 256
if r:peekU8(16) == 0 and r:peekU8(17) == 0 and (n == 12 or n == 16 or n == 40 or n == 52 or n == 56 or n == 64 or n == 108 or n == 124) then
return 0.9
@@ -79,7 +69,6 @@ function Bmp.sniff(r: Bytes.Reader): number
end
-- ------------------------------------------------------------------------------------------------ decode
-- Header parse: info, palette start offset, palette entry size, header-provided masks (or nil) | nil, err
local function parseHeader(buf: buffer): (Info?, any)
local n = buffer.len(buf)
if n < 18 then
@@ -127,13 +116,11 @@ local function parseHeader(buf: buffer): (Info?, any)
return info
end
-- info(r) -> Info | nil, Err: the header without decoding the pixels
function Bmp.info(r: Bytes.Reader): (Info?, Err.Err?)
return parseHeader(whole(r))
end
-- u8 table of size (m + 1) mapping a masked value 0..m to 0..255: v * 255 // m, as Pillow does (browsers replicate
-- the top bits instead, which can differ by 1). m = 0 -> { empty }.
-- v * 255 // m, as Pillow (browsers replicate the top bits, which can differ by 1)
local function scaleTable(m: number, empty: number): buffer
local t = buffer.create(m + 1)
if m == 0 then
@@ -146,7 +133,7 @@ local function scaleTable(m: number, empty: number): buffer
return t
end
-- shift, mask >> shift, table for one channel mask (wider than 16 bits: keep the top 16)
-- a mask wider than 16 bits keeps its top 16
local function channel(mask: number, empty: number): (number, number, buffer)
if mask == 0 then
return 0, 0, scaleTable(0, empty)
@@ -166,7 +153,6 @@ local function channel(mask: number, empty: number): (number, number, buffer)
return sh, m, scaleTable(m, empty)
end
-- decode(r, opts?) -> rgba8 Image | nil, Err
function Bmp.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?)
local buf = whole(r)
local info, herr = parseHeader(buf)
@@ -236,7 +222,6 @@ function Bmp.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.E
end
end
-- palette
local entrySize = if hs == 12 then 3 else 4
local declared = if hs >= 36 then readu32(buf, 46) else 0
local palCount = 0
@@ -334,7 +319,6 @@ function Bmp.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.E
end
-- ------------------------------------------------------------------------------------------------ encode
-- encode(img, opts?) -> buffer | nil, Err
function Bmp.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?)
if type(img) ~= "table" or img.format ~= "rgba8" or type(img.pixels) ~= "buffer" then
return nil, Err.new(Err.ARG, "encode: needs an rgba8 Image")
+14 -30
View File
@@ -1,17 +1,7 @@
--!strict
-- image/dds: DirectDraw Surface (Microsoft "DDS" programming guide: DDS_HEADER, DDS_PIXELFORMAT, DDS_HEADER_DXT10; new
-- code). Decode: every DXGI format with a pixel layout (BC1..BC7 through codecs/image/Bcn; the uncompressed UNORM /
-- SNORM / UINT / SINT / FLOAT / packed / shared-exponent ones and YUY2 / AYUV / RGBG through codecs/image/Texel), the
-- legacy FourCC codes (DXT1..DXT5, ATI1 / BC4U / BC4S, ATI2 / BC5U / BC5S, RXGB, YUY2 / UYVY / RGBG / GRGB, the
-- D3DFMT float / 16-bit numbers) and legacy bit-mask RGB / luminance / alpha formats; mip chains, cube maps (all six
-- faces or a subset), texture arrays (DX10 arraySize) and volume textures. The first surface is the image; when there
-- are more (faces, layers, depth slices) img.frames lists every one of them (meta.layout = "2d" / "cube" / "array" /
-- "volume", meta.faces), and with opts.mips the smaller levels of the first surface go to img.meta.mipmaps. rgba8 by
-- default (BC6H and float formats clamped to 0..1); opts.native keeps rgbaf32 / rgba16 where the source has more.
-- Encode: rgba8 as uncompressed (R8G8B8A8 / B8G8R8A8), BC1 / BC3 / BC4 / BC5 (legacy FourCC headers), rgba16 / rgbaf32
-- as DX10 R16G16B16A16_UNORM / R32G32B32A32_FLOAT / R16G16B16A16_FLOAT; optional mip chains (box filter) and the
-- frames as a texture array or a cube map. Not supported: planar video formats (NV12, P010, ...), palettes (P8),
-- 1-bit R1_UNORM, the depth-stencil formats with stencil channels, BC encoders other than 1 / 3 / 4 / 5.
-- image/dds: DirectDraw Surface (Microsoft DDS guide: DDS_HEADER, DDS_PIXELFORMAT, DDS_HEADER_DXT10). Supports: DXGI
-- formats with a pixel layout, legacy FourCC and bit-mask formats, mips, cube maps, arrays, volumes; writes rgba8 / BC1
-- / BC3 / BC4 / BC5 / rgba16 / rgbaf32. Not supported: planar video (NV12, P010), P8, R1_UNORM, stencil formats.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
@@ -34,18 +24,17 @@ local Dds = {
-- ------------------------------------------------------------------------------------------------ types
export type DecodeOptions = {
native: boolean?, -- keep rgbaf32 / rgba16 for float / 16-bit / BC6H sources (default false: rgba8)
mips: boolean?, -- decode the smaller mip levels of the first surface into img.meta.mipmaps (default false)
surfaces: boolean?, -- decode every face / layer / slice into img.frames (default true)
maxPixels: number?, -- refuse larger images (default 2^26, counted over every decoded surface)
native: boolean?, -- default false: rgba8
mips: boolean?, -- default false
surfaces: boolean?, -- default true
maxPixels: number?, -- default 2^26, over every decoded surface
}
export type EncodeOptions = {
pixelFormat: ("rgba8" | "bgra8" | "bc1" | "bc3" | "bc4" | "bc5" | "rgba16" | "rgba16f" | "rgba32f")?, -- default:
-- rgba8 for rgba8 images, rgba16 / rgba32f for rgba16 / rgbaf32 ones
mips: boolean?, -- write a full mip chain (default false)
dx10: boolean?, -- always write the DX10 header (default: only when the format needs it, or for arrays)
cube: boolean?, -- write img.frames (6) as a cube map (default: when img.meta.layout == "cube")
alphaThreshold: number?, -- BC1: alpha below this is transparent (default 128)
pixelFormat: ("rgba8" | "bgra8" | "bc1" | "bc3" | "bc4" | "bc5" | "rgba16" | "rgba16f" | "rgba32f")?,
mips: boolean?, -- default false
dx10: boolean?, -- default: when the format needs it, or for arrays
cube: boolean?, -- default: when img.meta.layout == "cube"
alphaThreshold: number?, -- default 128
}
-- ------------------------------------------------------------------------------------------------ constants
@@ -101,10 +90,10 @@ export type Info = {
height: number,
depth: number,
mips: number,
format: string, -- the texture format name (codecs/image/Texture)
format: string,
layout: string, -- "2d" | "cube" | "array" | "volume"
layers: number,
faces: { string }, -- cube faces present (in file order), else { }
faces: { string }, -- in file order
srgb: boolean,
dxgi: number?,
fourcc: string?,
@@ -118,7 +107,6 @@ local function u32(b: buffer, o: number): number
return buffer.readu32(b, o)
end
-- info(r) -> Info | nil, Err (the headers only)
function Dds.info(r: Bytes.Reader): (Info?, Err.Err?)
local b, o, n = r.buf, r.base, r.limit - r.base
if n < 128 or buffer.readstring(b, o, 4) ~= MAGIC then
@@ -228,7 +216,6 @@ function Dds.info(r: Bytes.Reader): (Info?, Err.Err?)
if not d then
return nil, Err.new(Err.UNSUPPORTED, "pixel format masks", o + 92)
end
-- the common masks map onto named texel formats (fast paths, sane names)
local key = string.format("%d:%x:%x:%x:%x:%s", bitCount, rm, gm, bm, a, tostring(lum))
local named = ({
["32:ff:ff00:ff0000:ff000000:false"] = "rgba8",
@@ -265,7 +252,6 @@ function Dds.info(r: Bytes.Reader): (Info?, Err.Err?)
return info, nil
end
-- the bytes of one surface of format f
local function surfaceSize(info: any, w: number, h: number): number
if info.format == "masked" then
return (info.masked :: Texel.Desc).bytes * w * h
@@ -359,7 +345,6 @@ end
local BYTES_PF: { [string]: number } = { rgba8 = 4, bgra8 = 4, rgba16 = 8, rgba16f = 8, rgba32f = 16 }
local DX10_OUT: { [string]: number } = { rgba8 = 28, bgra8 = 87, bc1 = 71, bc3 = 77, bc4 = 80, bc5 = 83, rgba16 = 11, rgba16f = 10, rgba32f = 2 }
-- the surface bytes of one image in format f
local function surface(img: Types.Image, f: string, opts: EncodeOptions?): (buffer?, Err.Err?)
local w, h, px = img.width, img.height, img.pixels
if f == "bc1" or f == "bc3" or f == "bc4" or f == "bc5" then
@@ -448,7 +433,6 @@ function Dds.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?)
if pf ~= needs then
return nil, Err.new(Err.ARG, string.format("pixelFormat %s needs an %s Image", f, needs))
end
-- surfaces: the frames (array / cube faces) or the image
local images: { Types.Image } = { img }
if img.frames and #img.frames > 1 then
images = {}
+1 -9
View File
@@ -1,9 +1,7 @@
--!strict
--!native
--!optimize 2
-- image/exr/Codec: the OpenEXR byte-level codecs (from the OpenEXR file layout document and ImfZip / ImfRle, BSD-3-
-- Clause): RLE and ZIP / ZIPS decode (run lengths or zlib, then the delta predictor and the two-half byte interleave),
-- ZIP encode, and the per-line channel sample conversion to floats. Never throws.
-- image/exr/Codec: OpenEXR RLE / ZIP / ZIPS blocks and sample conversion (after ImfZip / ImfRle, BSD-3-Clause).
local Deflate = require("@rosetta/codecs/compress/Deflate")
local Half = require("@rosetta/codecs/image/Half")
@@ -12,7 +10,6 @@ local Codec = {}
local readu8, writeu8, readi8, readu16, readu32, readf32, writef32 = buffer.readu8, buffer.writeu8, buffer.readi8, buffer.readu16, buffer.readu32, buffer.readf32, buffer.writef32
local HALF = Half.TABLE
-- undoes the predictor and the interleave of t (n bytes) -> a new buffer
local function reconstruct(t: buffer, n: number): buffer
local prev = if n > 0 then readu8(t, 0) else 0
for i = 1, n - 1 do
@@ -30,7 +27,6 @@ local function reconstruct(t: buffer, n: number): buffer
return out
end
-- rle(src, p, n, outSize) -> the raw block | nil, message
function Codec.rle(src: buffer, p: number, n: number, outSize: number): (buffer?, string?)
local t = buffer.create(outSize)
local o, stop = 0, p + n
@@ -60,7 +56,6 @@ function Codec.rle(src: buffer, p: number, n: number, outSize: number): (buffer?
return reconstruct(t, outSize), nil
end
-- zip(src, p, n, outSize) -> the raw block | nil, message (ZIP and ZIPS)
function Codec.unzip(src: buffer, p: number, n: number, outSize: number): (buffer?, string?)
local t, err = Deflate.zlib(src, p, n, outSize)
if not t then
@@ -72,7 +67,6 @@ function Codec.unzip(src: buffer, p: number, n: number, outSize: number): (buffe
return reconstruct(t, outSize), nil
end
-- zipEncode(raw, level) -> the compressed block (interleave, predictor, zlib)
function Codec.zip(raw: buffer, level: number): buffer
local n = buffer.len(raw)
local t = buffer.create(n)
@@ -94,8 +88,6 @@ function Codec.zip(raw: buffer, level: number): buffer
return Deflate.zlibCompress(t, { level = level }) :: buffer
end
-- samples(src, p, count, kind, dst, d, step) -> reads count samples of kind (0 uint, 1 half, 2 float) at p into
-- dst (f32) at byte offset d, step bytes apart; returns the source offset after them
function Codec.samples(src: buffer, p: number, count: number, kind: number, dst: buffer, d: number, step: number): number
if kind == 1 then
for i = 0, count - 1 do
+1 -13
View File
@@ -1,10 +1,7 @@
--!strict
--!native
--!optimize 2
-- image/exr/Piz: OpenEXR's PIZ decompressor (written from the OpenEXR 3.x sources' algorithm description: ImfPizCompressor
-- / ImfHuf / ImfWav, BSD-3-Clause, licenses/openexr-LICENSE.md): the range bitmap and its reverse LUT, the Huffman
-- stream (packed code lengths, canonical codes, the run-length symbol), the 2-D Haar wavelet (14- and 16-bit
-- variants) per channel plane, then the planes rearranged into scanlines. Never throws: nil, message on bad data.
-- image/exr/Piz: OpenEXR PIZ decompressor (after ImfPizCompressor / ImfHuf / ImfWav, BSD-3-Clause).
local Piz = {}
local readu8, readu16, writeu16, readu32 = buffer.readu8, buffer.readu16, buffer.writeu16, buffer.readu32
@@ -16,7 +13,6 @@ local DECBITS = 14
local SHORT_ZEROCODE_RUN, LONG_ZEROCODE_RUN, SHORTEST_LONG_RUN = 59, 63, 6
-- ------------------------------------------------------------------------------------------------ Huffman
-- the canonical code table: lengths[i] and codes[i] for symbols im..iM (1-based tables: symbol s at s + 1)
local function unpackTable(src: buffer, p: number, limit: number, im: number, iM: number, len: { number }): number?
local c, lc = 0, 0
local function bits(n: number): number?
@@ -69,7 +65,6 @@ local function unpackTable(src: buffer, p: number, limit: number, im: number, iM
return p
end
-- hufUncompress: nRaw u16 values from [p, p + n) into out (a buffer of u16) | nil, message
local function huffman(src: buffer, p: number, n: number, out: buffer, nRaw: number): string?
if n == 0 then
return if nRaw == 0 then nil else "empty Huffman data"
@@ -136,7 +131,6 @@ local function huffman(src: buffer, p: number, n: number, out: buffer, nRaw: num
end
end
end
-- decode MSB-first from a zero-padded copy
local nbytes = (nBits + 7) // 8
local data = buffer.create(nbytes + 8)
buffer.copy(data, 0, src, q, nbytes)
@@ -211,7 +205,6 @@ local function huffman(src: buffer, p: number, n: number, out: buffer, nRaw: num
end
-- ------------------------------------------------------------------------------------------------ wavelet
-- the inverse 2-D Haar wavelet over n x ny u16 values at element offset base, strides ox / oy (in elements)
local function wav2Decode(t: buffer, base: number, nx: number, ox: number, ny: number, oy: number, mx: number)
local w14 = mx < 16384
local n = math.min(nx, ny)
@@ -280,9 +273,6 @@ end
-- ------------------------------------------------------------------------------------------------ decode
export type Chan = { nx: number, ny: number, size: number, ys: number }
-- decode(src, p, n, chans, minY, maxY, outSize) -> the uncompressed block (scanline order) | nil, message.
-- chans: per channel (sorted order) its sample counts nx / ny in the block, size (1 = half, 2 = float / uint) and
-- ySampling.
function Piz.decode(src: buffer, p: number, n: number, chans: { Chan }, minY: number, maxY: number, outSize: number): (buffer?, string?)
local total = 0
for _, c in chans do
@@ -313,7 +303,6 @@ function Piz.decode(src: buffer, p: number, n: number, chans: { Chan }, minY: nu
buffer.copy(bitmap, minNZ, src, p, cnt)
p += cnt
end
-- reverse LUT
local lut = buffer.create(USHORT_RANGE * 2)
local k = 0
for i = 0, USHORT_RANGE - 1 do
@@ -348,7 +337,6 @@ function Piz.decode(src: buffer, p: number, n: number, chans: { Chan }, minY: nu
for i = 0, total - 1 do
writeu16(tmp, i * 2, readu16(lut, readu16(tmp, i * 2) * 2))
end
-- planes -> scanlines
local o = 0
local cursor = table.clone(starts)
for y = minY, maxY do
+12 -36
View File
@@ -1,17 +1,7 @@
--!strict
-- image/exr: OpenEXR (the OpenEXR file layout and technical introduction documents, openexr.com; new code, the PIZ
-- decoder written after OpenEXR's algorithm, BSD-3-Clause: licenses/openexr-LICENSE.md). Decode: single-part and
-- multipart files (opts.part: 1-based index or part name; meta.source.parts lists them), scanline and tiled parts
-- (one level, mip-map and rip-map levels: level 0, plus the mip-map levels into img.meta.mipmaps with opts.mips),
-- compression NONE / RLE / ZIPS / ZIP / PIZ, HALF / FLOAT / UINT channels, x / y subsampled channels (nearest), any
-- line order, broken offset tables (rebuilt from the chunks of single-part files). R / G / B / A map to the image
-- (opts.layer = "diffuse" reads diffuse.R ...); a Y-only image is grey; every channel name is in meta.source.channels.
-- The image is the data window (meta.dataWindow / meta.displayWindow keep both boxes). opts.native gives the linear
-- rgbaf32 values; the default rgba8 is a display conversion like image/hdr's: round(clamp(v, 0, 1) ^ (1 / 2.2) * 255)
-- for colour, round(clamp(a, 0, 1) * 255) for alpha.
-- Encode: rgbaf32 (or rgba8 through the inverse curve) as a scanline file, HALF (default) or FLOAT channels, A only
-- when some alpha is not 1, compression NONE, ZIPS or ZIP (default). Not supported: deep data, PXR24 / B44 / B44A /
-- DWAA / DWAB / HTJ2K / ZSTD compression (UNSUPPORTED naming the method), RY / BY chroma (the Y channel is used).
-- image/exr: OpenEXR (openexr.com file layout docs; PIZ after OpenEXR, BSD-3-Clause: licenses/openexr-LICENSE.md).
-- Supports: single / multipart, scanline / tiled (mip / rip level 0, mips), NONE / RLE / ZIPS / ZIP / PIZ, HALF / FLOAT
-- / UINT, subsampling, layers; writes scanlines. Not supported: deep, PXR24 / B44(A) / DWA / HTJ2K / ZSTD.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
@@ -34,17 +24,17 @@ local Exr = {
-- ------------------------------------------------------------------------------------------------ types
export type DecodeOptions = {
native: boolean?, -- linear rgbaf32 (default false: rgba8 through a 1 / 2.2 display gamma)
part: (number | string)?, -- multipart files: the part to read (1-based index or name; default 1)
layer: string?, -- read <layer>.R / .G / .B / .A instead of R / G / B / A
mips: boolean?, -- tiled mip-map parts: decode the smaller levels into img.meta.mipmaps (default false)
maxPixels: number?, -- refuse larger images (default 2^26)
native: boolean?, -- default false: rgba8, round(clamp(v, 0, 1) ^ (1 / 2.2) * 255)
part: (number | string)?, -- 1-based index or name; default 1
layer: string?,
mips: boolean?, -- default false
maxPixels: number?, -- default 2^26
}
export type EncodeOptions = {
compression: ("none" | "zips" | "zip")?, -- default "zip"
pixelType: ("half" | "float")?, -- default "half"
alpha: boolean?, -- write A (default: when some alpha is not 1)
level: number?, -- zlib level 1..9 (default 6)
alpha: boolean?, -- default: when some alpha is not 1
level: number?, -- 1..9, default 6
}
-- ------------------------------------------------------------------------------------------------ constants
@@ -91,7 +81,6 @@ local function f32(b: buffer, o: number): number
return readf32(b, o)
end
-- one attribute value of a known type
local function value(b: buffer, p: number, size: number, typ: string): any
if typ == "chlist" then
local list: { Channel } = {}
@@ -146,7 +135,6 @@ local function value(b: buffer, p: number, size: number, typ: string): any
return raw
end
-- the attributes of one header from p -> attrs, the offset after its terminating NUL | nil, Err
local function header(b: buffer, p: number, limit: number): ({ [string]: any }?, number, Err.Err?)
local attrs: { [string]: any } = {}
local types: { [string]: string } = {}
@@ -179,7 +167,6 @@ local function header(b: buffer, p: number, limit: number): ({ [string]: any }?,
end
end
-- level sizes of a tiled part
local function levelSize(n: number, l: number, roundUp: boolean): number
local d = 2 ^ l
return math.max(1, if roundUp then math.ceil(n / d) else n // d)
@@ -201,7 +188,6 @@ local function levelCount(w: number, h: number, mode: number, roundUp: boolean):
return count(w), count(h)
end
-- chunk count of a part (single-part files: computed)
local function chunkCount(pt: Part): number
local w, h = pt.box[3] - pt.box[1] + 1, pt.box[4] - pt.box[2] + 1
if not pt.tiled then
@@ -287,7 +273,6 @@ local function parse(r: Bytes.Reader): (Info?, Err.Err?)
if multi then
p += 1
end
-- offset tables
for _, pt in info.parts do
local n = if type(pt.attrs.chunkCount) == "number" then pt.attrs.chunkCount else (if LINES[pt.compression] then chunkCount(pt) else 0)
if n < 0 or n > 2 ^ 24 then
@@ -306,20 +291,17 @@ local function parse(r: Bytes.Reader): (Info?, Err.Err?)
return info, nil
end
-- info(r) -> { multipart, tiled, deep, parts = { { name, type, attrs, channels, compression, box, ... } } } | nil, Err
function Exr.info(r: Bytes.Reader): (Info?, Err.Err?)
return parse(r)
end
-- bytes of a sample kind
local SIZE = { [0] = 4, 2, 4 }
-- number of multiples of s in [a, b]
local function samples(a: number, b: number, s: number): number
return b // s - (a - 1) // s
end
type Target = { [number]: number } -- channel index -> output component (0..3, 4 = grey)
type Target = { [number]: number }
local function newPlane(pw: number, ph: number): buffer
local px = buffer.create(pw * ph * 16)
@@ -328,7 +310,6 @@ local function newPlane(pw: number, ph: number): buffer
end
return px
end
-- one decompressed block: the lines y0..y1 (absolute), columns x0..x0 + bw - 1 of plane (pw wide, origin ox, oy)
local function block(part: Part, target: Target, data: buffer, dp: number, y0: number, y1: number, x0: number, bw: number, plane: buffer, pw: number, ph: number, ox: number, oy: number): Err.Err?
local p = dp
for y = y0, y1 do
@@ -373,7 +354,6 @@ local function block(part: Part, target: Target, data: buffer, dp: number, y0: n
return nil
end
-- the raw bytes of a block (uncompressed size raw)
local function unpack(b: buffer, comp: number, part: Part, p: number, size: number, raw: number, y0: number, y1: number, x0: number, bw: number): (buffer?, number, Err.Err?)
if size == raw or comp == 0 then
if size < raw then
@@ -443,7 +423,6 @@ function Exr.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.E
if w * h > maxPixels then
return nil, Err.new(Err.LIMIT, string.format("%d x %d is over the %d pixel limit", w, h, maxPixels))
end
-- channel -> output component
local prefix = if opts and opts.layer then opts.layer .. "." else ""
local target: Target = {}
local hasRgb = false
@@ -466,7 +445,6 @@ function Exr.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.E
end
end
local multi = info.multipart
-- offsets: single-part tables with holes are rebuilt from the chunk sequence
local offsets = part.offsets
local bad = false
for _, o in offsets do
@@ -512,7 +490,7 @@ function Exr.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.E
end
end
local planes: { [number]: buffer } = { [0] = newPlane(w, h) } -- level -> rgbaf32 pixels
local planes: { [number]: buffer } = { [0] = newPlane(w, h) }
local tiles = part.tiles
local roundUp = tiles ~= nil and tiles[4] == 1
local wantMips = opts and opts.mips and tiles ~= nil and tiles[3] == 1
@@ -684,7 +662,6 @@ function Exr.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?)
return nil, Err.new(Err.ARG, "pixelType must be half or float")
end
local level = opts and opts.level or 6
-- the float values
local n = w * h
local fl = buffer.create(n * 16)
if img.format == "rgbaf32" then
@@ -710,7 +687,6 @@ function Exr.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?)
local sz = if kind == 1 then 2 else 4
local lpb = LINES[comp]
local nblocks = (h + lpb - 1) // lpb
-- header
local hw = Bytes.writer(512)
hw:string(MAGIC)
hw:u32le(2)
+2 -9
View File
@@ -1,15 +1,12 @@
--!strict
--!native
--!optimize 2
-- image/gif/Decode: the per-frame pixel work (native; never throws): palette indexes (plain or interlaced rows) to
-- rgba8, and drawing a frame onto the canvas (transparent pixels leave the canvas as it is). The caller sizes every
-- buffer: indexes fw * fh bytes, the palette 256 u32 entries, the frame fw * fh * 4, the canvas cw * ch * 4.
-- image/gif/Decode: GIF frame pixels: palette indexes (plain or interlaced) to rgba8, drawn onto the canvas.
local readu8, readu32, writeu32 = buffer.readu8, buffer.readu32, buffer.writeu32
local Decode = {}
-- the source row of output row y in an interlaced frame (passes: every 8th from 0, every 8th from 4, every 4th from
-- 2, every 2nd from 1)
-- interlace passes: every 8th row from 0, every 8th from 4, every 4th from 2, every 2nd from 1
local function interlacedRow(fh: number): { number }
local map = table.create(fh, 0)
local r = 0
@@ -24,8 +21,6 @@ local function interlacedRow(fh: number): { number }
return map
end
-- toRgba(indexes, fw, fh, interlaced, palette, out): out = the frame in rgba8 (palette: 256 u32 entries, the
-- transparent one already alpha 0)
function Decode.toRgba(indexes: buffer, fw: number, fh: number, interlaced: boolean, palette: buffer, out: buffer)
local rows = if interlaced then interlacedRow(fh) else nil
for y = 0, fh - 1 do
@@ -37,7 +32,6 @@ function Decode.toRgba(indexes: buffer, fw: number, fh: number, interlaced: bool
end
end
-- draw(canvas, cw, ch, frame, fx, fy, fw, fh): frame pixels with alpha > 0 replace the canvas (clipped)
function Decode.draw(canvas: buffer, cw: number, ch: number, frame: buffer, fx: number, fy: number, fw: number, fh: number)
local x0, y0 = math.max(0, fx), math.max(0, fy)
local x1, y1 = math.min(cw, fx + fw), math.min(ch, fy + fh)
@@ -53,7 +47,6 @@ function Decode.draw(canvas: buffer, cw: number, ch: number, frame: buffer, fx:
end
end
-- clear(canvas, cw, ch, fx, fy, fw, fh): the frame's rectangle to transparent black (dispose to background)
function Decode.clear(canvas: buffer, cw: number, ch: number, fx: number, fy: number, fw: number, fh: number)
local x0, y0 = math.max(0, fx), math.max(0, fy)
local x1, y1 = math.min(cw, fx + fw), math.min(ch, fy + fh)
+10 -30
View File
@@ -1,18 +1,7 @@
--!strict
-- image/gif: GIF87a / GIF89a. New code from the GIF89a spec (W3C / CompuServe 1990). Supports: decode of every image
-- (global / local colour tables, interlaced rows, LZW minimum code sizes 2..8 and the odd 1, transparency, frames
-- smaller than or outside the canvas), animation (Graphic Control Extension delays, disposal none / background /
-- previous, NETSCAPE2.0 / ANIMEXTS1.0 loop counts), comments (meta.text.comment); truncated files keep the frames
-- read so far (meta.truncated). Encode of rgba8 images and animations (Types.Frame lists) through codecs/image/Quantize
-- (median cut or octree, optional Floyd-Steinberg dithering; exact palettes, so lossless, at <= 256 colours) with
-- alpha < 128 as the transparent index.
-- Not supported: the plain text extension (skipped), the aspect ratio (kept in meta.source.aspect), the "user input"
-- flag, and blend = "source" frames that clear pixels to transparent (GIF can only draw over).
--
-- Decoded value: img.pixels = the first frame composited on a transparent canvas; for animations img.frames = every
-- frame's own rectangle (rgba8; blend "over" when it has a transparent index, else "source") and img.loops, the
-- number of plays (0 = forever; 1 when the file has no loop extension). The NETSCAPE2.0 value counts repeats, as
-- browsers and ImageMagick read it: a stored n plays n + 1 times (n = 0: forever).
-- image/gif: GIF87a / GIF89a, from the GIF89a spec (CompuServe 1990). Supports: every image, interlace, LZW code sizes
-- 1..8, transparency, GCE delays / disposal, NETSCAPE2.0 / ANIMEXTS1.0 loops, comments; writes quantized frames. Not
-- supported: the plain text extension, the aspect ratio, the user input flag, blend "source" frames.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
@@ -34,17 +23,16 @@ local Gif = {
-- ------------------------------------------------------------------------------------------------ types
export type DecodeOptions = {
maxPixels: number?, -- refuse a canvas or frame larger than this (default 2^26)
maxTotalPixels: number?, -- refuse animations whose frames add up to more (default 2^28)
maxFrames: number?, -- stop after this many frames (default: all)
maxPixels: number?, -- default 2^26
maxTotalPixels: number?, -- default 2^28
maxFrames: number?, -- default: all
}
export type EncodeOptions = {
maxColors: number?, -- 2..256 per palette (default 256; one is taken by transparency when needed)
maxColors: number?, -- 2..256, default 256
method: ("mediancut" | "octree")?, -- default "mediancut"
dither: boolean?, -- Floyd-Steinberg (default false)
loops: number?, -- animation plays override (0 = forever, 1..65536; default img.loops)
globalPalette: boolean?, -- one palette for every frame (default false: a single image uses the global table,
-- each animation frame gets its own local table)
dither: boolean?, -- Floyd-Steinberg, default false
loops: number?, -- 0 = forever, 1..65536; default img.loops
globalPalette: boolean?, -- default false
}
-- ------------------------------------------------------------------------------------------------ constants
@@ -59,7 +47,6 @@ function Gif.sniff(r: Bytes.Reader): number
end
-- ------------------------------------------------------------------------------------------------ decode
-- a colour table at p (n entries) -> 256 u32 rgba entries (missing ones opaque black) and the { r, g, b, a } list
local function colorTable(b: buffer, p: number, n: number): (buffer, { { number } })
local t = buffer.create(1024)
local list: { { number } } = table.create(n) :: { { number } }
@@ -110,14 +97,12 @@ function Gif.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.E
local comments: { string } = {}
local loops: number? = nil
local total = 0
-- the pending Graphic Control Extension
local delay, dispose, trans = 0, 0, -1
local truncated = false
local interlacedAny = false
local localTables = 0
local minCode = 8
local limit = r.limit
-- the sub-blocks at r.pos: joined into one buffer (nil when they run past the end)
local function subBlocks(): (buffer?, number)
local p = r.pos
local n = 0
@@ -287,7 +272,6 @@ function Gif.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.E
break
end
else
-- junk between blocks: stop here, keeping what was read
if #frames == 0 then
return nil, Err.new(Err.CORRUPT, string.format("bad block introducer 0x%02x", intro), r.pos - 1)
end
@@ -340,7 +324,6 @@ local function hasTransparency(px: buffer, n: number): boolean
return false
end
-- palette list -> padded table bytes (power of two entries, >= 2) and its size code
local function writeTable(w: Bytes.Writer, pal: { { number } }): number
local bits = 1
while bit32.lshift(1, bits) < #pal do
@@ -381,7 +364,6 @@ function Gif.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?)
return nil, Err.new(Err.ARG, "method must be mediancut or octree")
end
local dither = opts and opts.dither or false
-- the frames to write: { image, x, y, delay, dispose }
local list: { Types.Frame } = {}
if type(img.frames) == "table" and #(img.frames :: any) > 0 then
for i, f in img.frames :: { Types.Frame } do
@@ -402,13 +384,11 @@ function Gif.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?)
if type(loops) ~= "number" or loops < 0 or loops > 65536 or loops % 1 ~= 0 then
return nil, Err.new(Err.ARG, "loops must be 0..65536")
end
-- palettes
local shared = (opts and opts.globalPalette) or not animated
local qopts: Quantize.PaletteOptions = { method = method, dither = dither }
local globalPal: { { number } }? = nil
local globalTrans = false
if shared then
-- every frame's pixels together
local npx = 0
for _, f in list do
npx += f.image.width * f.image.height
+2 -12
View File
@@ -1,17 +1,13 @@
--!strict
--!native
--!optimize 2
-- image/hdr/Codec: Radiance RGBE scanlines (native; never throws). Written from the Radiance file format notes
-- (Greg Ward, "Real Pixels", Graphics Gems II) and Bruce Walter's rgbe.c conventions: flat pixels, old-style RLE
-- (1, 1, 1, n repeats the previous pixel, shifted by 8 for consecutive markers) and new-style RLE (2, 2, width, then
-- four run-length coded channel planes). RGBE -> float is mantissa * 2^(e - 136), as rgbe.c, stb_image and
-- ImageMagick (no +0.5 offset); float -> RGBE as rgbe.c float2rgbe (frexp). Every read is bounds-checked.
-- image/hdr/Codec: Radiance RGBE scanlines (Graphics Gems II; rgbe.c): mantissa * 2^(e - 136), no +0.5, as stb_image.
local readu8, writeu8, writef32, readf32 = buffer.readu8, buffer.writeu8, buffer.writef32, buffer.readf32
local frexp = math.frexp
local Codec = {}
-- readLine(b, p, limit, w, row) -> new position | nil, message: one scanline into row (w * 4 RGBE bytes)
-- old-style RLE: 1, 1, 1, n repeats the previous pixel (n << 8 for consecutive markers); new-style: 2, 2, width, planes
function Codec.readLine(b: buffer, p: number, limit: number, w: number, row: buffer): (number?, string?)
if w >= 8 and w <= 32767 and p + 4 <= limit and readu8(b, p) == 2 and readu8(b, p + 1) == 2 and readu8(b, p + 2) < 128 then
if readu8(b, p + 2) * 256 + readu8(b, p + 3) ~= w then
@@ -95,7 +91,6 @@ function Codec.readLine(b: buffer, p: number, limit: number, w: number, row: buf
return p, nil
end
-- toFloat(row, n, out, offsets): n RGBE pixels -> rgbaf32 at out byte offsets dest(i) = base + i * step
function Codec.toFloat(row: buffer, n: number, out: buffer, base: number, step: number)
for i = 0, n - 1 do
local q = i * 4
@@ -115,7 +110,6 @@ function Codec.toFloat(row: buffer, n: number, out: buffer, base: number, step:
end
end
-- fromFloat(px, y, w, row): row y of an rgbaf32 image -> w RGBE pixels (rgbe.c float2rgbe)
function Codec.fromFloat(px: buffer, y: number, w: number, row: buffer)
for x = 0, w - 1 do
local q = (y * w + x) * 16
@@ -162,7 +156,6 @@ function Codec.fromFloat(px: buffer, y: number, w: number, row: buffer)
end
end
-- writeLine(row, w, out, o) -> new offset: new-style RLE (rgbe.c RGBE_WriteBytes_RLE); out needs w * 4 + w + 8
function Codec.writeLine(row: buffer, w: number, out: buffer, o: number): number
writeu8(out, o, 2)
writeu8(out, o + 1, 2)
@@ -172,7 +165,6 @@ function Codec.writeLine(row: buffer, w: number, out: buffer, o: number): number
for c = 0, 3 do
local cur = 0
while cur < w do
-- find the next run of at least 4
local begRun = cur
local runCount = 0
local oldRun = 0
@@ -187,14 +179,12 @@ function Codec.writeLine(row: buffer, w: number, out: buffer, o: number): number
end
end
end
-- a short run just before the long one
if oldRun > 1 and oldRun == begRun - cur then
writeu8(out, o, 128 + oldRun)
writeu8(out, o + 1, readu8(row, cur * 4 + c))
o += 2
cur = begRun
end
-- raw bytes up to the run
while cur < begRun do
local n = math.min(begRun - cur, 128)
writeu8(out, o, n)
+7 -14
View File
@@ -1,12 +1,7 @@
--!strict
-- image/hdr: Radiance HDR / RGBE (.hdr, .pic), written from the Radiance file format notes and rgbe.c conventions.
-- Decode: "#?RADIANCE" / "#?RGBE" (any "#?" program name) headers, FORMAT=32-bit_rle_rgbe, EXPOSURE (the product of
-- every EXPOSURE line, kept in meta.exposure, not applied), other header lines in meta.text, the eight resolution
-- orientations (-Y +X standard, +Y, -X and the X-major ones), flat, old-style RLE and new-style RLE scanlines.
-- opts.native gives the linear rgbaf32 values (alpha 1); the default rgba8 is a display conversion:
-- round(clamp(v, 0, 1) ^ (1 / 2.2) * 255) per channel. Encode: rgbaf32 (or rgba8 through the inverse curve) to a
-- -Y +X file with new-style RLE (flat scanlines for widths outside 8..32767).
-- Not supported: FORMAT=32-bit_rle_xyze (CIE XYZ files: UNSUPPORTED), PRIMARIES / COLORCORR (ignored).
-- image/hdr: Radiance HDR / RGBE (.hdr, .pic), from the Radiance file format notes and rgbe.c. Supports: "#?" headers,
-- 32-bit_rle_rgbe, EXPOSURE (kept, not applied), the eight orientations, flat / old / new RLE; writes -Y +X new RLE.
-- Not supported: 32-bit_rle_xyze, PRIMARIES / COLORCORR (ignored).
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
@@ -26,12 +21,12 @@ local Hdr = {
-- ------------------------------------------------------------------------------------------------ types
export type DecodeOptions = {
native: boolean?, -- linear rgbaf32 (default false: rgba8 through a 1 / 2.2 display gamma)
maxPixels: number?, -- refuse larger images (default 2^26)
native: boolean?, -- default false: rgba8, round(clamp(v, 0, 1) ^ (1 / 2.2) * 255)
maxPixels: number?, -- default 2^26
}
export type EncodeOptions = {
rle: boolean?, -- new-style RLE scanlines (default true)
exposure: number?, -- write an EXPOSURE line (default meta.exposure when not 1)
rle: boolean?, -- default true
exposure: number?, -- default: meta.exposure when not 1
}
-- ------------------------------------------------------------------------------------------------ constants
@@ -57,7 +52,6 @@ function Hdr.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.E
local maxPixels = opts and opts.maxPixels or 2 ^ 26
local b, limit = r.buf, r.limit
local p = r.base
-- header lines up to the first empty one
local function line(): string?
local s = p
while p < limit and buffer.readu8(b, p) ~= 10 do
@@ -187,7 +181,6 @@ function Hdr.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?)
local o: any = opts or {}
local px = img.pixels
if bpp == 4 then
-- rgba8 through the inverse of the decoder's display curve
local lut = table.create(256, 0)
for v = 0, 255 do
lut[v + 1] = (v / 255) ^ 2.2
+7 -15
View File
@@ -1,13 +1,7 @@
--!strict
-- image/icns: Apple Icon Image files (the icns resource type; new code; chunks through containers/Chunks). Decode:
-- the legacy RGB entries is32 / il32 / ih32 / it32 (the icns RLE, or raw) with their s8mk / l8mk / h8mk / t8mk alpha
-- masks, ic04 / ic05 ARGB entries, the 1-bit ics# / ICN# / ich# / icm# icons with their masks, and PNG entries in any
-- type (icp4 .. ic14) through the api hook opts.decodeImage. JPEG 2000 entries are skipped (meta.skipped lists them),
-- like 4 / 8-bit palette entries and nested dark-mode / TOC chunks. The image is the largest entry; img.frames lists
-- every decoded entry (each with meta.source = { type = "ic07", ... }); a file of JPEG 2000 entries only returns
-- UNSUPPORTED. Encode: the image and every img.frames image (square, 16 .. 1024): PNG entries through opts.encodeImage
-- (icp4 / icp5 / icp6 / ic07 / ic08 / ic09 / ic10), or without the hook (or opts.legacy) the RLE entries for 16 / 32 /
-- 48 / 128 with masks.
-- image/icns: Apple icon images (icns resource type). Supports: is32 / il32 / ih32 / it32 (icns RLE) with s8mk / l8mk /
-- h8mk / t8mk masks, ic04 / ic05 ARGB, 1-bit ics# / ICN# / ich# / icm#, PNG entries through opts.decodeImage; writes
-- PNG or RLE entries. Not supported: JPEG 2000 entries, 4 / 8-bit palette entries, nested dark-mode / TOC chunks.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
@@ -28,12 +22,12 @@ local Icns = {
-- ------------------------------------------------------------------------------------------------ types
export type DecodeOptions = {
decodeImage: ((buffer) -> (Types.Image?, Err.Err?))?, -- decodes PNG entries (the api passes one)
maxPixels: number?, -- refuse entries larger than this (default 2^22)
decodeImage: ((buffer) -> (Types.Image?, Err.Err?))?,
maxPixels: number?, -- default 2^22
}
export type EncodeOptions = {
encodeImage: ((Types.Image, string) -> (buffer?, Err.Err?))?, -- writes PNG entries (the api passes one)
legacy: boolean?, -- RLE entries (16 / 32 / 48 / 128) even when encodeImage is there (default false)
encodeImage: ((Types.Image, string) -> (buffer?, Err.Err?))?,
legacy: boolean?, -- default false
}
-- ------------------------------------------------------------------------------------------------ constants
@@ -58,7 +52,6 @@ function Icns.sniff(r: Bytes.Reader): number
end
-- ------------------------------------------------------------------------------------------------ decode
-- the icns RLE of n channels of count bytes each from [p, stop) into out at channel offsets (interleaved, step 4)
local function unrle(b: buffer, p: number, stop: number, out: buffer, channels: { number }, count: number): boolean
for _, ch in channels do
local i = 0
@@ -228,7 +221,6 @@ function Icns.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.
end
-- ------------------------------------------------------------------------------------------------ encode
-- the icns RLE of one channel (count bytes, step 4 from ch) into w
local function rle(w: Bytes.Writer, px: buffer, ch: number, count: number)
local i = 0
while i < count do
+2 -8
View File
@@ -1,18 +1,14 @@
--!strict
--!native
--!optimize 2
-- image/ico/Dib: the BMP device-independent bitmaps inside ICO / CUR entries (native; never throws). Written from
-- the Microsoft ICO / BITMAPINFOHEADER documentation: a colour (XOR) bitmap of 1 / 4 / 8 / 16 (5-5-5) / 24 / 32-bit
-- pixels, bottom-up rows padded to 4 bytes, then a 1-bit AND mask (1 = transparent). 32-bit entries use their alpha
-- channel unless it is all zero (old icons), in which case the AND mask decides. The row loops are
-- codecs/image/Pixels (shared with BMP); the AND mask and the alpha rule are ICO's.
-- image/ico/Dib: ICO / CUR DIBs: XOR bitmap (1..32-bit, bottom-up, 4-byte rows) + 1-bit AND mask (1 = transparent).
local Pixels = require("@rosetta/codecs/image/Pixels")
local readu8, readu32, writeu32 = buffer.readu8, buffer.readu32, buffer.writeu32
local Dib = {}
-- decode(b, p, e, w, h, bpp, pal, palN, out) -> ok, message: the XOR + AND bitmaps at b[p, e) into rgba8 out
-- 32-bit entries use their alpha unless it is all zero (old icons); then the AND mask decides
function Dib.decode(b: buffer, p: number, e: number, w: number, h: number, bpp: number, pal: buffer, palN: number, out: buffer): (boolean, string?)
local stride = ((w * bpp + 31) // 32) * 4
local maskStride = ((w + 31) // 32) * 4
@@ -61,8 +57,6 @@ function Dib.decode(b: buffer, p: number, e: number, w: number, h: number, bpp:
return true, nil
end
-- encode(px, w, h, out, o) -> new offset: rgba8 as a 32-bit BGRA bitmap (bottom-up) + an AND mask (alpha 0 = 1).
-- out needs room for w * h * 4 + maskStride * h bytes.
function Dib.encode(px: buffer, w: number, h: number, out: buffer, o: number): number
for y = h - 1, 0, -1 do
for x = 0, w - 1 do
+8 -15
View File
@@ -1,14 +1,7 @@
--!strict
-- image/ico: Windows icons and cursors (ICO / CUR), written from Microsoft's ICO format documentation. Decode: every
-- directory entry, as a BMP DIB (1 / 4 / 8 / 16 / 24 / 32-bit with a colour table and the AND mask; 32-bit alpha) or
-- an embedded PNG, decoded through the api hook opts.decodeImage (F.load supplies it; without it PNG entries are
-- skipped, and a file of PNG entries only returns UNSUPPORTED). The image is the largest entry (then the deepest);
-- img.frames lists every decoded entry in file order (Types.Frame, each frame image with meta.source.bitDepth / png
-- and, for cursors, meta.hotspot = { x, y }). Encode: the image, or every img.frames image (each up to 256 x 256), as
-- 32-bit DIB entries with an AND mask; 256-pixel entries (or all with opts.png) as PNG through opts.encodeImage when it
-- is there; a cursor (CUR) with opts.cursor or when the image has meta.hotspot.
-- Not supported: resizing to a set of icon sizes (do that with ops/ImageOps first), DIB compression (BI_BITFIELDS
-- 16 / 32-bit is read as 5-5-5 / BGRA), the obsolete 2-colour planes.
-- image/ico: Windows icons and cursors (ICO / CUR), from Microsoft's ICO documentation. Supports: every entry as a BMP
-- DIB (1..32-bit, AND mask) or PNG (opts.decodeImage), CUR hotspots; writes 32-bit DIB or PNG entries. Not supported:
-- resizing to icon sizes, DIB compression (BI_BITFIELDS read as 5-5-5 / BGRA), 2-colour planes.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
@@ -28,13 +21,13 @@ local Ico = {
-- ------------------------------------------------------------------------------------------------ types
export type DecodeOptions = {
decodeImage: ((buffer) -> (Types.Image?, Err.Err?))?, -- decodes PNG entries (the api passes one)
maxPixels: number?, -- refuse larger entries (default 2^26)
decodeImage: ((buffer) -> (Types.Image?, Err.Err?))?,
maxPixels: number?, -- default 2^26
}
export type EncodeOptions = {
encodeImage: ((Types.Image, string) -> (buffer?, Err.Err?))?, -- writes PNG entries (the api passes one)
png: boolean?, -- every entry as PNG (needs encodeImage; default: only 256-pixel entries, when it exists)
cursor: boolean?, -- write a CUR (default: when the image has meta.hotspot)
encodeImage: ((Types.Image, string) -> (buffer?, Err.Err?))?,
png: boolean?, -- default: only 256-pixel entries
cursor: boolean?, -- default: when the image has meta.hotspot
}
-- ------------------------------------------------------------------------------------------------ constants
+6 -13
View File
@@ -1,12 +1,7 @@
--!strict
-- image/ilbm: IFF ILBM and PBM pictures (EA IFF 85 "ILBM" standard, the Amiga ROM Kernel Manual; new code; chunks
-- through containers/Chunks, ByteRun1 through codecs/compress/PackBits). Decode: planar ILBM with 1..8 planes and a
-- CMAP (grey without one), EHB (extra half-brite, CAMG 0x80), HAM6 / HAM8 (CAMG 0x800), deep 24 / 32-plane RGB(A),
-- chunky PBM (8-bit, Deluxe Paint), masking 1 (a mask plane) and 2 (a transparent colour index), uncompressed or
-- ByteRun1 bodies; opts.adjustColors scales 4-bit OCS palettes (all low nibbles zero) to 8 bits; NAME / ANNO / AUTH
-- text (meta.text). HAM channel values replicate their bits (4-bit v -> v * 17; ilbmtoppm shifts: v * 16). Encode: rgba8 as a planar ILBM: up to 256 opaque colours with a CMAP and the fewest planes, else
-- 24 planes (32 with alpha), ByteRun1 (default) or uncompressed. Not supported: animations (ANIM), the rarer
-- encodings (RGBN / RGB8 / ACBM / DEEP chunks: UNSUPPORTED), SHAM / PCHG palette changes (ignored).
-- image/ilbm: IFF ILBM / PBM (EA IFF 85 "ILBM", Amiga ROM Kernel Manual). Supports: 1..8 planes + CMAP, EHB (CAMG
-- 0x80), HAM6 / HAM8 (CAMG 0x800; 4-bit v -> v * 17, ilbmtoppm shifts), 24 / 32 planes, PBM, masking 1 / 2, ByteRun1,
-- NAME / ANNO / AUTH. Not supported: ANIM, RGBN / RGB8 / ACBM / DEEP, SHAM / PCHG (ignored).
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
@@ -28,11 +23,11 @@ local Ilbm = {
-- ------------------------------------------------------------------------------------------------ types
export type DecodeOptions = {
adjustColors: boolean?, -- scale 4-bit OCS palettes (every low nibble 0) to 8 bits (default false)
maxPixels: number?, -- refuse larger images (default 2^26)
adjustColors: boolean?, -- default false
maxPixels: number?, -- default 2^26
}
export type EncodeOptions = {
compress: boolean?, -- ByteRun1 (default true)
compress: boolean?, -- default true
}
local readu8, readu16 = buffer.readu8, buffer.readu16
@@ -92,7 +87,6 @@ function Ilbm.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.
end
local ham = bit32.band(camg, 0x800) ~= 0 and (planes == 6 or planes == 8)
local ehb = bit32.band(camg, 0x80) ~= 0 and planes == 6 and not ham
-- palette
local pal = buffer.create(1024)
local ncol = 0
if cmap then
@@ -125,7 +119,6 @@ function Ilbm.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.
buffer.writeu32(pal, (32 + i) * 4, bit32.rshift(rr, 1) + bit32.rshift(gg, 1) * 256 + bit32.rshift(bb, 1) * 65536 + 0xFF000000)
end
end
-- the body, decompressed
local rowBytes = if chunky then w + w % 2 else ((w + 15) // 16) * 2
local total = if chunky then rowBytes * h else rowBytes * (planes + (if masking == 1 then 1 else 0)) * h
local raw = buffer.create(total)
+15 -30
View File
@@ -1,20 +1,7 @@
--!strict
-- image/jpeg: JPEG / JFIF / EXIF (ITU T.81), a thin format over codecs/image/Jpeg (the engine, shared with the Motion-JPEG
-- video tracks; absorbed from jpeg-luau 1.0, same author, bit-exact with libjpeg-turbo's djpeg and byte-identical
-- with cjpeg; IJG-derived parts: licenses/libjpeg-turbo-LICENSE.md). This module is the contract, the sniff, the
-- options and the meta segments: meta.exif (APP1), meta.icc (APP2 chunks), meta.text.comment (COM) and meta.dpi
-- (JFIF density) are written from the Image on encode and read back on decode. Encode also takes yuv420p Images
-- (coded 4:2:0 from the planes as they are).
-- Decode: baseline, extended and progressive frames, Huffman or arithmetic coded (SOF0/1/2/9/10), 8 and 12-bit
-- samples, 1, 3 or 4 components with any sampling factors 1..4, restart intervals (resynchronising after corrupt
-- data), grey / YCbCr / RGB / CMYK / YCCK (Adobe APP14), scaled decodes (opts.scale = 2, 4, 8 through libjpeg's
-- reduced IDCTs), EXIF orientation reported in meta.orientation and applied with opts.orient. Truncated or corrupt
-- scans decode as far as they go (meta.truncated = true).
-- Encode: baseline (standard or optimised Huffman tables) and progressive (libjpeg's simple progression), grey or
-- YCbCr 4:4:4 / 4:2:2 / 4:2:0, libjpeg quality tables, restart intervals, EXIF / ICC / comment segments from meta;
-- byte-identical to cjpeg for the same settings.
-- Not supported: lossless (SOF3) and hierarchical frames, DNL, 2-component images, ICC colour management, 12-bit
-- or CMYK encoding.
-- image/jpeg: JPEG / JFIF / EXIF (ITU T.81) over codecs/image/Jpeg (from jpeg-luau 1.0, same author; bit-exact with
-- djpeg, byte-identical with cjpeg; IJG parts: licenses/libjpeg-turbo-LICENSE.md). Supports: SOF0/1/2/9/10, 8 / 12-bit,
-- scaled decodes, EXIF / ICC / COM / JFIF density. Not supported: lossless (SOF3), hierarchical, DNL, 2 components.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
@@ -34,20 +21,20 @@ local Jpeg = {
-- ------------------------------------------------------------------------------------------------ types
export type DecodeOptions = {
scale: number?, -- 1 (default), 2, 4 or 8: decode at ceil(size / scale) (8 reads the DC coefficients only)
orient: boolean?, -- apply the EXIF orientation (default false: reported in meta.orientation only)
native: boolean?, -- grey files decode to gray8 (default false: rgba8)
maxPixels: number?, -- refuse larger images (default 2^26)
scale: number?, -- 1 (default), 2, 4 or 8
orient: boolean?, -- default false
native: boolean?, -- default false
maxPixels: number?, -- default 2^26
}
export type EncodeOptions = {
quality: number?, -- 1..100 (default 90), libjpeg's scaling of the T.81 annex K tables
subsampling: ("420" | "422" | "444")?, -- chroma subsampling (default "420")
quality: number?, -- 1..100, default 90 (libjpeg scaling of the T.81 annex K tables)
subsampling: ("420" | "422" | "444")?, -- default "420"
progressive: boolean?, -- default false
optimize: boolean?, -- optimised Huffman tables for baseline files (default false; progressive always optimises)
gray: boolean?, -- a one-component file (default: true for gray8 images)
restart: number?, -- restart interval in MCUs (default 0 = none)
jfif: boolean?, -- write the JFIF APP0 header (default true)
meta: boolean?, -- write meta.exif (APP1), meta.icc (APP2) and meta.text.comment (COM) (default true)
optimize: boolean?, -- default false; progressive always optimises
gray: boolean?, -- default: true for gray8 images
restart: number?, -- in MCUs, default 0 = none
jfif: boolean?, -- default true
meta: boolean?, -- default true
}
export type Info = Codec.Info
@@ -59,7 +46,6 @@ function Jpeg.sniff(r: Bytes.Reader): number
end
-- ------------------------------------------------------------------------------------------------ decode
-- info(r) -> Info | nil, Err (reads the headers up to the frame header)
function Jpeg.info(r: Bytes.Reader): (Info?, Err.Err?)
return Codec.info(r.buf, r.base, r.limit - r.base)
end
@@ -69,7 +55,7 @@ function Jpeg.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.
return nil, Err.new(Err.ARG, "options must be a table")
end
local o = opts or {} :: DecodeOptions
-- one image: no yuv output, no field weaving (two JPEGs back to back are an image and a preview, as in MPF)
-- two JPEGs back to back are an image and a preview, as in MPF
return Codec.decode(r.buf, r.base, r.limit - r.base, {
scale = o.scale,
orient = o.orient,
@@ -80,7 +66,6 @@ function Jpeg.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.
end
-- ------------------------------------------------------------------------------------------------ encode
-- the APP1 / APP2 / COM segments and the JFIF density from img.meta
local function metaSegments(meta: any): ({ { marker: number, data: buffer } }, { unit: number, x: number, y: number }?)
local segments = {}
if type(meta.exif) == "buffer" and buffer.len(meta.exif) <= 65527 then
+13 -27
View File
@@ -1,15 +1,7 @@
--!strict
-- image/ktx: Khronos texture containers (KTX 1.1 and KTX 2.0 specifications; new code). Decode: KTX1 (OpenGL
-- glInternalFormat / glFormat + glType: the S3TC / RGTC / BPTC / ETC1 / ETC2 / EAC compressed formats and the
-- uncompressed ones with 4-byte row alignment; big-endian files) and KTX2 (VkFormat: BCn, ETC2 / EAC and every
-- uncompressed format codecs/image/Texel knows; Zstandard (codecs/compress/Zstd) and ZLIB supercompression); mip
-- levels, cube maps, arrays and 3D textures, the key / value data (meta.keyValue) and KTXorientation (T=u rows are
-- flipped). Like image/dds: the first surface is the image, img.frames lists every face / layer / slice when there is
-- more than one (meta.layout), opts.mips decodes the smaller levels into img.meta.mipmaps; rgba8 unless opts.native.
-- Encode: KTX2, uncompressed: rgba8 (R8G8B8A8_UNORM, or _SRGB when meta.colorSpace is "srgb"), rgba16
-- (R16G16B16A16_UNORM), rgbaf32 (R32G32B32A32_SFLOAT or R16G16B16A16_SFLOAT), with a full DFD, optional mip chain,
-- frames as layers or cube faces, optional ZLIB supercompression. Not supported: Basis Universal (BasisLZ / ETC1S and
-- UASTC: UNSUPPORTED), ASTC and PVRTC, writing KTX1 or Zstandard.
-- image/ktx: Khronos KTX 1.1 / KTX 2.0. Supports: KTX1 (GL compressed and uncompressed, big-endian), KTX2 (VkFormat BCn
-- / ETC2 / EAC / uncompressed; Zstd and ZLIB supercompression), mips, cubes, arrays, 3D, KTXorientation; writes
-- uncompressed KTX2. Not supported: Basis Universal (BasisLZ / UASTC), ASTC, PVRTC.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
@@ -33,18 +25,18 @@ local Ktx = {
-- ------------------------------------------------------------------------------------------------ types
export type DecodeOptions = {
native: boolean?, -- keep rgbaf32 / rgba16 for float / 16-bit / BC6H / EAC sources (default false: rgba8)
mips: boolean?, -- decode the smaller mip levels of the first surface into img.meta.mipmaps (default false)
surfaces: boolean?, -- decode every face / layer / slice into img.frames (default true)
maxPixels: number?, -- refuse larger images (default 2^26, over every decoded surface)
native: boolean?, -- default false: rgba8
mips: boolean?, -- default false
surfaces: boolean?, -- default true
maxPixels: number?, -- default 2^26, over every decoded surface
}
export type EncodeOptions = {
pixelFormat: ("rgba8" | "rgba16" | "rgba16f" | "rgba32f")?, -- default: the image's own (rgbaf32 -> rgba32f)
srgb: boolean?, -- rgba8 as R8G8B8A8_SRGB (default: meta.colorSpace == "srgb")
mips: boolean?, -- a full mip chain (box filter; default false)
cube: boolean?, -- img.frames as cube faces (default: meta.layout == "cube")
zlib: number?, -- ZLIB-supercompress every level at this level 1..9 (default none)
keyValue: { [string]: string }?, -- extra key / value pairs (KTXwriter is always written)
srgb: boolean?, -- default: meta.colorSpace == "srgb"
mips: boolean?, -- default false
cube: boolean?, -- default: meta.layout == "cube"
zlib: number?, -- 1..9, default none
keyValue: { [string]: string }?, -- KTXwriter is always written
}
-- ------------------------------------------------------------------------------------------------ constants
@@ -118,7 +110,7 @@ export type Info = {
layers: number,
faces: number,
levels: number,
format: string?, -- the texture format name (nil when unsupported: see unsupported)
format: string?,
unsupported: string?,
srgb: boolean,
opaque: boolean, -- BC1 RGB
@@ -289,7 +281,6 @@ local function info2(r: Bytes.Reader): (Info?, Err.Err?)
return info, nil
end
-- info(r) -> Info | nil, Err (the headers only)
function Ktx.info(r: Bytes.Reader): (Info?, Err.Err?)
local id = r:peek(12)
if id == ID2 then
@@ -300,7 +291,6 @@ function Ktx.info(r: Bytes.Reader): (Info?, Err.Err?)
return nil, Err.new(Err.CORRUPT, "not a KTX file", r.base)
end
-- reverses the bytes of every typeSize-wide element of a big-endian KTX1 image
local function swapped(b: buffer, p: number, n: number, size: number): buffer
local out = buffer.create(n)
buffer.copy(out, 0, b, p, n)
@@ -352,7 +342,6 @@ function Ktx.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.E
local w, h, d = info.width, info.height, info.depth
for level = 0, info.levels - 1 do
local want = level == 0 or wantMips
-- the level's data: buf, offset, the image stride and row pitch
local lb, lp = b, 0
local rowPitch: number? = nil
local imgSize = Texture.size(fmt, w, h) :: number
@@ -492,7 +481,6 @@ function Ktx.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.E
end
-- ------------------------------------------------------------------------------------------------ encode
-- format -> VkFormat, bytes per texel, component bytes, kind
local OUT: { [string]: { number } } = {
rgba8 = { 37, 4, 1 },
rgba16 = { 91, 8, 2 },
@@ -582,7 +570,6 @@ function Ktx.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?)
if zl ~= nil and (type(zl) ~= "number" or zl < 1 or zl > 9) then
return nil, Err.new(Err.ARG, "zlib level must be 1..9")
end
-- level data: the images of every layer / face per level
local levelData: { buffer } = {}
local raw: { number } = {}
local cur = table.clone(images)
@@ -602,7 +589,6 @@ function Ktx.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?)
end
levelData[lv] = lb
end
-- key / value data
local kvw = Bytes.writer()
local pairs_: { { string } } = { { "KTXwriter", "rosetta" } }
if opts and opts.keyValue then
+5 -9
View File
@@ -1,9 +1,7 @@
--!strict
-- image/pcx: ZSoft PC Paintbrush (the ZSoft "Technical Reference Manual" PCX header and RLE; new code). Decode: 1-bit
-- monochrome, 1-bit x 2..4 planes (EGA, the header palette), 2 / 4-bit packed (the header palette), 8-bit with the
-- 256-colour palette at the end (grey when it is missing), 8-bit x 3 / 4 planes (RGB / RGBA); RLE (runs may cross
-- scan lines) and the rare uncompressed encoding; the window (xMin / yMin) and DPI (meta.dpi). Encode: rgba8 as
-- 8-bit palette (up to 256 opaque colours), 24-bit (3 planes) or 32-bit (4 planes, when there is alpha), RLE.
-- image/pcx: ZSoft PC Paintbrush (ZSoft "Technical Reference Manual" header and RLE). Supports: 1-bit, 1-bit x 2..4
-- planes (EGA), 2 / 4-bit packed, 8-bit with the 256-colour end palette, 8-bit x 3 / 4 planes, RLE across scan lines,
-- uncompressed, DPI; writes 8-bit palette or 24 / 32-bit planes.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
@@ -23,10 +21,10 @@ local Pcx = {
-- ------------------------------------------------------------------------------------------------ types
export type DecodeOptions = {
maxPixels: number?, -- refuse larger images (default 2^26)
maxPixels: number?, -- default 2^26
}
export type EncodeOptions = {
palette: boolean?, -- 8-bit palette when possible (default true); false: always 24 / 32-bit planes
palette: boolean?, -- default true; false: always 24 / 32-bit planes
}
local readu8, readu16 = buffer.readu8, buffer.readu16
@@ -111,7 +109,6 @@ function Pcx.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.E
p += n
truncated = n < total
end
-- palettes
local pal = buffer.create(1024)
local function setPal(i: number, rr: number, gg: number, bb: number)
buffer.writeu32(pal, i * 4, rr + gg * 256 + bb * 65536 + 0xFF000000)
@@ -183,7 +180,6 @@ function Pcx.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.E
end
-- ------------------------------------------------------------------------------------------------ encode
-- RLE of one plane row into w
local function rleRow(out: Bytes.Writer, src: buffer, p: number, n: number)
local i = 0
while i < n do
+1 -5
View File
@@ -1,9 +1,7 @@
--!strict
--!native
--!optimize 2
-- image/png/Apng: APNG frame compositing (APNG spec 1.0: dispose_op none / background / previous, blend_op source /
-- over) onto full rgba8 canvases. The "over" blend uses the same integer arithmetic as ffmpeg's pngdec.c, so the
-- canvases match ffmpeg byte for byte. Nothing here throws: the caller (init) validated every frame rectangle.
-- image/png/Apng: APNG 1.0 dispose / blend compositing; "over" uses ffmpeg pngdec.c's integer arithmetic (byte-exact).
local readu8, writeu8, readu32, writeu32 = buffer.readu8, buffer.writeu8, buffer.readu32, buffer.writeu32
local bcreate, bcopy, bfill = buffer.create, buffer.copy, buffer.fill
@@ -13,7 +11,6 @@ local function div255(x: number): number
return (x + 128) * 257 // 65536
end
-- blend(canvas, cw, src, fw, fh, fx, fy, over): draw an rgba8 rectangle onto the canvas
local function blend(canvas: buffer, cw: number, src: buffer, fw: number, fh: number, fx: number, fy: number, over: boolean)
for y = 0, fh - 1 do
local so = y * fw * 4
@@ -46,7 +43,6 @@ local function blend(canvas: buffer, cw: number, src: buffer, fw: number, fh: nu
end
end
-- composite(w, h, frames) -> { buffer }: the full canvas after each frame (frames: { image, x, y, dispose, blend })
function Apng.composite(w: number, h: number, frames: { any }): { buffer }
local canvas = bcreate(w * h * 4)
local saved = bcreate(w * h * 4)
+1 -16
View File
@@ -1,12 +1,7 @@
--!strict
--!native
--!optimize 2
-- image/png/Decode: the PNG pixel stage. Undo the per-row filters (none / sub / up / average / Paeth) in place in the
-- inflated image data, then expand every colour type and bit depth to RGBA8, for one image or the 7 Adam7 passes.
-- Absorbed from png-luau src/Png/Decode.luau (same author).
--
-- The caller (init) has validated the header and checked that the data holds at least the expected number of
-- bytes, so every index here is in range. A bad filter type returns false, message: nothing in this module throws.
-- image/png/Decode: PNG unfiltering and expansion to RGBA8 (absorbed from png-luau src/Png/Decode.luau, same author).
local band, rshift, lshift = bit32.band, bit32.rshift, bit32.lshift
local readu8, writeu8, readu32, writeu32 = buffer.readu8, buffer.writeu8, buffer.readu32, buffer.writeu32
local bcopy = buffer.copy
@@ -28,20 +23,16 @@ Decode.PASSES = PASSES
local CHANNELS = { [0] = 1, [2] = 3, [3] = 1, [4] = 2, [6] = 4 }
Decode.CHANNELS = CHANNELS
-- bytes per row (without the filter byte) for a pass width
function Decode.rowBytes(pw: number, channels: number, depth: number): number
return (pw * channels * depth + 7) // 8
end
-- Unfilter ph rows of rb bytes starting at raw[p] (each row: a filter byte, then rb bytes). bpp: bytes per
-- complete pixel (at least 1). Returns true, or false + the bad filter type.
local function unfilter(raw: buffer, p: number, ph: number, rb: number, bpp: number): (boolean, number)
local stride = rb + 1
for r = 0, ph - 1 do
local f = readu8(raw, p)
local cur = p + 1
if f == 0 then
-- none
elseif f == 1 then
for i = cur + bpp, cur + rb - 1 do
writeu8(raw, i, readu8(raw, i) + readu8(raw, i - bpp))
@@ -51,7 +42,6 @@ local function unfilter(raw: buffer, p: number, ph: number, rb: number, bpp: num
local i = cur
local e4 = cur + rb - 4
while i <= e4 do
-- four bytes at once: add without carries between the byte lanes
local x, y = readu32(raw, i), readu32(raw, i - stride)
local lo = band(x, 0x7F7F7F7F) + band(y, 0x7F7F7F7F)
writeu32(raw, i, bit32.bxor(lo, band(bit32.bxor(x, y), 0x80808080)))
@@ -112,9 +102,6 @@ local function unfilter(raw: buffer, p: number, ph: number, rb: number, bpp: num
return true, 0
end
-- Expand one unfiltered row (pw pixels at raw[ro]) to RGBA8 at out[oo], oo stepping by ostep bytes.
-- pal: 256 RGBA8 entries (index -> u32 little-endian RGBA). tr: the tRNS key for grey / RGB (-1 if none),
-- as a sample value (grey) or r * 2^32 + g * 2^16 + b (RGB), at the image's bit depth.
local function convert(raw: buffer, ro: number, pw: number, out: buffer, oo: number, ostep: number, ct: number, depth: number, pal: buffer, tr: number)
if ct == 6 then
if depth == 8 then
@@ -213,8 +200,6 @@ local function convert(raw: buffer, ro: number, pw: number, out: buffer, oo: num
end
end
-- Decode the inflated data raw (at least the expected size) of a w x h image to out (w * h * 4 bytes, RGBA8).
-- Returns true, or false + message.
function Decode.run(raw: buffer, w: number, h: number, depth: number, ct: number, interlace: number, pal: buffer, tr: number, out: buffer): (boolean, string?)
local channels = CHANNELS[ct]
local bpp = math.max(1, (channels * depth) // 8)
+1 -10
View File
@@ -1,9 +1,7 @@
--!strict
--!native
--!optimize 2
-- image/png/Encode: the PNG encoder's pixel stage. Picks the smallest lossless colour type for rgba8 pixels and
-- writes the filtered scanlines (a filter byte + the row), choosing each row's filter by the minimum sum of absolute
-- signed residuals (the libpng heuristic). Nothing here throws: the caller (init) validated the image.
-- image/png/Encode: PNG colour type choice and filtering (per-row minimum sum of |signed residuals|, as libpng).
local readu8, writeu8 = buffer.readu8, buffer.writeu8
local bcreate, bcopy = buffer.create, buffer.copy
@@ -11,7 +9,6 @@ local Encode = {}
local CHANNELS = { [0] = 1, [2] = 3, [4] = 2, [6] = 4 }
-- pickColorType(px, w, h) -> "rgba" | "rgb" | "graya" | "gray"
function Encode.pickColorType(px: buffer, w: number, h: number): string
local opaque, gray = true, true
for i = 0, w * h - 1 do
@@ -33,7 +30,6 @@ function Encode.pickColorType(px: buffer, w: number, h: number): string
return "rgb"
end
-- convert rgba8 to the colour type's packed rows (no filter bytes)
local function pack(px: buffer, w: number, h: number, ct: number): buffer
local ch = CHANNELS[ct]
if ch == 4 then
@@ -70,8 +66,6 @@ local function paeth(a: number, b: number, c: number): number
return c
end
-- the five filter costs (sums of |signed residual|) of the row at s (rb bytes; previous row at s - rb unless first);
-- the arithmetic is inlined: this runs for every byte
local function costs(src: buffer, s: number, rb: number, bpp: number, first: boolean): (number, number, number, number, number)
local c0, c1, c2, c3, c4 = 0, 0, 0, 0, 0
local p = s - rb
@@ -101,7 +95,6 @@ local function costs(src: buffer, s: number, rb: number, bpp: number, first: boo
return c0, c1, c2, c3, c4
end
-- write the row at s filtered with f to out[o + 1 ..] (out[o] = f)
local function apply(src: buffer, s: number, rb: number, bpp: number, first: boolean, f: number, out: buffer, o: number)
writeu8(out, o, f)
o += 1
@@ -130,8 +123,6 @@ local function apply(src: buffer, s: number, rb: number, bpp: number, first: boo
end
end
-- filter(px, w, h, ct) -> the filtered scanlines (h * (1 + rowBytes)); each row's filter: the minimum sum of
-- |signed residuals| (the libpng heuristic)
function Encode.filter(px: buffer, w: number, h: number, ct: number): buffer
local ch = CHANNELS[ct]
local src = pack(px, w, h, ct)
+7 -25
View File
@@ -1,14 +1,7 @@
--!strict
-- image/png: PNG (ISO/IEC 15948, W3C PNG 3rd ed.). Absorbed from png-luau 1.0.0 (same author) + a new encoder.
-- Supports: decode of every colour type (grey, RGB, palette, grey + alpha, RGBA) at every bit depth (1, 2, 4, 8, 16),
-- PLTE / tRNS transparency, the five filters, Adam7, tEXt; encode of rgba8 to RGBA / RGB / grey / grey + alpha
-- (chosen automatically) with adaptive filters. Decodes to rgba8 (16-bit samples keep their high byte).
-- APNG (APNG 1.0): acTL / fcTL / fdAT decode to img.frames (each frame its own rectangle, delay in seconds, dispose /
-- blend ops), img.loops = num_plays; img.pixels stays the default image (meta.apngDefaultHidden when the IDAT is not
-- part of the animation). Png.composite(img) draws the frames onto full canvases (byte-exact with ffmpeg). Encode
-- writes an APNG when img.frames is a non-empty list (or opts.apng). Sequence numbers and frame rectangles are checked.
-- Not supported: colour management (gAMA / cHRM / sRGB / iCCP are
-- ignored; iCCP is kept raw-compressed in meta.iccCompressed), palette / 16-bit / interlaced output.
-- image/png: PNG (ISO/IEC 15948, W3C PNG 3rd ed.) and APNG 1.0; from png-luau 1.0.0 (same author). Supports: every
-- colour type and bit depth, tRNS, Adam7, tEXt, acTL / fcTL / fdAT; writes RGBA / RGB / grey(+alpha) and APNG. Not
-- supported: colour management (iCCP kept raw), palette / 16-bit / interlaced output.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
@@ -32,14 +25,13 @@ local Png = {
}
export type DecodeOptions = {
checkCrc: boolean?, -- verify every chunk's CRC-32 (default false)
maxPixels: number?, -- refuse larger images (default 2^26 = 64 Mpixel, a 256 MB RGBA buffer)
checkCrc: boolean?, -- default false
maxPixels: number?, -- default 2^26
}
export type EncodeOptions = {
level: number?, -- deflate level 0..9 (default 6)
level: number?, -- 0..9, default 6
colorType: ("auto" | "rgba" | "rgb" | "gray" | "graya")?, -- default "auto": the smallest lossless one
apng: boolean?, -- true: an APNG even without img.frames (one frame); false: a still PNG; default: APNG when
-- img.frames is a non-empty list
apng: boolean?, -- default: APNG when img.frames is a non-empty list
}
-- ------------------------------------------------------------------------------------------------ constants
@@ -66,7 +58,6 @@ end
-- ------------------------------------------------------------------------------------------------ decode
type Header = { width: number, height: number, bitDepth: number, colorType: number, interlace: number }
-- the IHDR at r's start: Header | nil, Err
local function header(r: Bytes.Reader): (Header?, Err.Err?)
local b, o, n = r.buf, r.base, r.limit - r.base
if n < 8 or readu8(b, o) ~= 137 or buffer.readstring(b, o, 8) ~= SIGNATURE then
@@ -98,7 +89,6 @@ local function header(r: Bytes.Reader): (Header?, Err.Err?)
return h, nil
end
-- info(r) -> { width, height, bitDepth, colorType, interlace } | nil, Err (reads only the header)
function Png.info(r: Bytes.Reader): (Header?, Err.Err?)
return header(r)
end
@@ -117,8 +107,6 @@ type FrameControl = {
}
local DISPOSE: { [number]: "none" | "background" | "previous" } = { [0] = "none", [1] = "background", [2] = "previous" }
-- pixels(b, chunks, total, w, h, depth, ct, interlace, pal, tr, out) -> nil | Err: inflate the zlib stream split
-- over chunks ({ offset, length } in b), unfilter and expand it to rgba8 in out (w x h)
local function pixels(b: buffer, chunks: { { number } }, total: number, w: number, ht: number, depth: number, ct: number, interlace: number, pal: buffer, tr: number, out: buffer): Err.Err?
-- the inflated size: every (pass) row has a filter byte
local channels = Decode.CHANNELS[ct]
@@ -175,7 +163,6 @@ function Png.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.E
return nil, Err.new(Err.LIMIT, string.format("%d x %d is over the %d pixel limit", w, ht, maxPixels))
end
local b, n = r.buf, r.limit
-- chunks
local pal = buffer.create(1024)
for i = 0, 255 do
buffer.writeu32(pal, i * 4, 0xFF000000) -- out-of-range indexes: opaque black
@@ -375,7 +362,6 @@ local CT_CODES = { gray = 0, rgb = 2, graya = 4, rgba = 6 }
local DISPOSE_CODES: { [string]: number } = { none = 0, background = 1, previous = 2 }
local BLEND_CODES: { [string]: number } = { source = 0, over = 1 }
-- a frame delay in seconds -> num, den (u16 each): the smallest exact denominator, else milliseconds
local function delayFraction(delay: number): (number, number)
for den = 1, 1000 do
local num = math.floor(delay * den + 0.5)
@@ -407,7 +393,6 @@ local function validImage(im: any): boolean
and buffer.len(im.pixels) >= im.width * im.height * 4
end
-- the frames to write as an APNG (nil for a plain PNG), or nil, Err for a bad frame list
local function animationFrames(img: Types.Image, opts: EncodeOptions?): ({ Types.Frame }?, Err.Err?)
local frames = img.frames
local mode = if opts then opts.apng else nil
@@ -465,7 +450,6 @@ function Png.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?)
local want = opts and opts.colorType or "auto"
local ctName: string = want
if want == "auto" then
-- the smallest colour type that holds the image and every frame
local alpha, color = false, false
local function scan(im: Types.Image)
local c = Encode.pickColorType(im.pixels, im.width, im.height)
@@ -569,8 +553,6 @@ function Png.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?)
end
-- ------------------------------------------------------------------------------------------------ extras
-- composite(img) -> { Image } | nil, Err: every APNG frame drawn onto a full canvas (dispose / blend applied, as a
-- player shows them; byte-exact with ffmpeg). A still image gives { a copy of img }.
function Png.composite(img: Types.Image): ({ Types.Image }?, Err.Err?)
if not validImage(img) then
return nil, Err.new(Err.ARG, "composite: needs an rgba8 Image")
+3 -17
View File
@@ -1,17 +1,13 @@
--!strict
--!native
--!optimize 2
-- image/pnm/Codec: the Netpbm sample loops (native; never throws). Written from the Netpbm format pages (pbm, pgm,
-- ppm, pam, pfm). Reading: binary 8 / 16-bit samples, ASCII samples (P1 digits may run together), P4 bit rows, PFM
-- floats (either byte order, bottom-to-top rows); packing samples into a Types pixel format with maxval scaling.
-- Writing: samples of any pixel format extracted at 1..4 channels and 8 or 16 bits. Every read is bounds-checked.
-- image/pnm/Codec: Netpbm sample loops: P1 digits may run together; PFM either byte order.
local readu8, writeu8, readu16, writeu16 = buffer.readu8, buffer.writeu8, buffer.readu16, buffer.writeu16
local readf32, writef32, readu32, writeu32 = buffer.readf32, buffer.writef32, buffer.readu32, buffer.writeu32
local byteswap = bit32.byteswap
local Codec = {}
-- readSamples(b, p, limit, count, mode, out) -> true | false, message: count raw values into out (u16 each).
-- mode 1 = binary 8-bit, 2 = binary 16-bit big-endian, 3 = ASCII decimal, 4 = ASCII P1 (single digits)
function Codec.readSamples(b: buffer, p: number, limit: number, count: number, mode: number, out: buffer): (boolean, string?)
if mode == 1 then
@@ -33,7 +29,6 @@ function Codec.readSamples(b: buffer, p: number, limit: number, count: number, m
end
local i = 0
while i < count do
-- skip whitespace and comments
while p < limit do
local c = readu8(b, p)
if c == 35 then -- '#'
@@ -73,7 +68,6 @@ function Codec.readSamples(b: buffer, p: number, limit: number, count: number, m
return true, nil
end
-- readBits(b, p, limit, w, h, out) -> ok, message: P4 rows (MSB first, rows padded to bytes) as u16 0 / 1 values
function Codec.readBits(b: buffer, p: number, limit: number, w: number, h: number, out: buffer): (boolean, string?)
local rowBytes = (w + 7) // 8
if p + rowBytes * h > limit then
@@ -89,11 +83,9 @@ function Codec.readBits(b: buffer, p: number, limit: number, w: number, h: numbe
return true, nil
end
-- format codes for pack / extract
Codec.RGBA8, Codec.RGB8, Codec.GRAY8, Codec.GRAYA8, Codec.RGBA16, Codec.GRAY16, Codec.RGBAF32 = 0, 1, 2, 3, 4, 5, 6
-- pack(samples, n, ch, maxval, invert, fmt, dst): n pixels of ch raw samples (u16, 0..maxval; invert: 1 - v for
-- PBM bits) into dst in pixel format fmt, scaled to the format's range (8-bit: round(v * 255 / maxval))
-- 8-bit: round(v * 255 / maxval)
function Codec.pack(s: buffer, n: number, ch: number, maxval: number, invert: boolean, fmt: number, dst: buffer)
local wide = fmt == 4 or fmt == 5
local top = if wide then 65535 else 255
@@ -144,7 +136,6 @@ function Codec.pack(s: buffer, n: number, ch: number, maxval: number, invert: bo
end
end
-- readFloats(b, p, limit, w, h, ch, le, dst) -> ok, message: PFM rows (bottom-to-top) into rgbaf32 dst
function Codec.readFloats(b: buffer, p: number, limit: number, w: number, h: number, ch: number, le: boolean, dst: buffer): (boolean, string?)
if p + w * h * ch * 4 > limit then
return false, "truncated"
@@ -182,8 +173,7 @@ local function f(v: number): number
return math.floor(math.clamp(v, 0, 1) * 65535 + 0.5)
end
-- extract(px, fmt, n, ch, wide) -> u16 samples: n pixels of format fmt as ch channels (1 grey (Rec. 601 luma for
-- colour sources, Pillow's L = (299 R + 587 G + 114 B) / 1000), 2 grey + alpha, 3 RGB, 4 RGBA), 16-bit if wide
-- grey from colour: Pillow's L = (299 R + 587 G + 114 B) / 1000
function Codec.extract(px: buffer, fmt: number, n: number, ch: number, wide: boolean): buffer
local out = buffer.create(n * ch * 2)
local srcWide = fmt == 4 or fmt == 5
@@ -232,7 +222,6 @@ function Codec.extract(px: buffer, fmt: number, n: number, ch: number, wide: boo
return out
end
-- writeSamples(s, count, wide, out, o) -> new offset: binary samples (8-bit or 16-bit big-endian)
function Codec.writeSamples(s: buffer, count: number, wide: boolean, out: buffer, o: number): number
if wide then
for i = 0, count - 1 do
@@ -250,7 +239,6 @@ function Codec.writeSamples(s: buffer, count: number, wide: boolean, out: buffer
return o
end
-- writeBits(s, w, h, threshold, out, o) -> new offset: P4 rows from grey samples (below threshold = black = 1)
function Codec.writeBits(s: buffer, w: number, h: number, threshold: number, out: buffer, o: number): number
for y = 0, h - 1 do
local acc, nb = 0, 0
@@ -271,8 +259,6 @@ function Codec.writeBits(s: buffer, w: number, h: number, threshold: number, out
return o
end
-- writeFloats(px, w, h, ch, out, o) -> new offset: rgbaf32 (ch 3) or its first channel (ch 1) as little-endian PFM
-- rows, bottom-to-top
function Codec.writeFloats(px: buffer, w: number, h: number, ch: number, out: buffer, o: number): number
for y = h - 1, 0, -1 do
for x = 0, w - 1 do
+10 -18
View File
@@ -1,12 +1,7 @@
--!strict
-- image/pnm: the Netpbm family, written from the Netpbm format pages: PBM (P1 ASCII / P4 binary), PGM (P2 / P5),
-- PPM (P3 / P6), PAM (P7: BLACKANDWHITE, GRAYSCALE, GRAYSCALE_ALPHA, RGB, RGB_ALPHA and their _ALPHA forms, any
-- tuple type of depth 1..4) and PFM (PF colour / Pf grey 32-bit float, either byte order, bottom-to-top rows).
-- maxval 1..65535 (scaled to 8 bits by round(v * 255 / maxval)). Decode: rgba8, or with opts.native the source layout
-- (gray8, gray16, graya8, rgb8, rgba8, rgba16 for 16-bit colour or grey + alpha, rgbaf32 for PFM). PFM to rgba8 is
-- clamp(v, 0, 1) * 255 rounded (linear, no gamma). Encode: any of the seven types, binary or ASCII, from every pixel
-- format; the subtype comes from opts.format / the file extension (pbm, pgm, ppm, pam, pfm) or the image.
-- Not supported: multi-image streams (the first image is read), PAM depths above 4.
-- image/pnm: Netpbm, from the Netpbm format pages: PBM (P1 / P4), PGM (P2 / P5), PPM (P3 / P6), PAM (P7, depth 1..4)
-- and PFM (PF / Pf, either byte order, bottom-up rows). Supports: maxval 1..65535, PFM to rgba8 as clamp(v, 0, 1) *
-- 255; writes all seven types. Not supported: multi-image streams, PAM depths above 4.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
@@ -26,15 +21,14 @@ local Pnm = {
-- ------------------------------------------------------------------------------------------------ types
export type DecodeOptions = {
native: boolean?, -- keep the source layout (default false: rgba8)
maxPixels: number?, -- refuse larger images (default 2^26)
native: boolean?, -- default false: rgba8
maxPixels: number?, -- default 2^26
}
export type EncodeOptions = {
format: string?, -- "pbm" | "pgm" | "ppm" | "pam" | "pfm" (default: from the image: grey -> pgm, opaque colour
-- -> ppm, alpha -> pam, rgbaf32 -> pfm); "pnm" means the default
ascii: boolean?, -- P1 / P2 / P3 instead of P4 / P5 / P6 (default false)
maxval: number?, -- 1..65535 (default 255, or 65535 for 16-bit / float sources); pbm ignores it
threshold: number?, -- pbm: grey below this (0..255) is black (default 128)
format: string?, -- default: grey -> pgm, opaque colour -> ppm, alpha -> pam, rgbaf32 -> pfm; "pnm" means the default
ascii: boolean?, -- default false
maxval: number?, -- 1..65535, default 255 (65535 for 16-bit / float sources)
threshold: number?, -- 0..255, default 128
}
-- ------------------------------------------------------------------------------------------------ constants
@@ -66,7 +60,6 @@ local function isSpace(c: number): boolean
return c == 32 or (c >= 9 and c <= 13)
end
-- the next header token from p: token, position after it (nil at the end)
local function token(b: buffer, p: number, limit: number): (string?, number)
while p < limit do
local c = readu8(b, p)
@@ -161,7 +154,6 @@ function Pnm.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.E
maxval = int(v)
elseif key == "TUPLTYPE" then
tupl = v
-- the rest of the line belongs to the value
while p < limit and readu8(b, p) ~= 10 do
p += 1
end
@@ -184,7 +176,7 @@ function Pnm.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.E
else
return nil, Err.new(Err.CORRUPT, "not a Netpbm file", r.base)
end
local w, h, maxval = w :: number, h :: number, maxval :: number -- each branch above returns when one is nil
local w, h, maxval = w :: number, h :: number, maxval :: number
if w < 1 or h < 1 or maxval < 1 or maxval > 65535 then
return nil, Err.new(Err.CORRUPT, string.format("bad size %d x %d or maxval %d", w, h, maxval))
end
+1 -5
View File
@@ -1,16 +1,13 @@
--!strict
--!native
--!optimize 2
-- image/qoi/Codec: the QOI op loops (native; never throws). Written from the QOI specification 1.0 (qoiformat.org).
-- decode reads ops from b[p, limit) into an rgba8 buffer; encode writes ops for rgba8 / rgb8 pixels. Every input read
-- is checked against limit; the output buffer has exactly w * h * 4 bytes and the loop stops when it is full.
-- image/qoi/Codec: QOI op loops, from the QOI specification 1.0 (qoiformat.org).
local readu8, writeu8, writeu32 = buffer.readu8, buffer.writeu8, buffer.writeu32
local Codec = {}
local index = buffer.create(256)
-- decode(b, p, limit, out, n) -> true | false, "truncated" (n pixels into out)
function Codec.decode(b: buffer, p: number, limit: number, out: buffer, n: number): (boolean, string?)
buffer.fill(index, 0, 0, 256)
local r, g, bl, a = 0, 0, 0, 255
@@ -82,7 +79,6 @@ function Codec.decode(b: buffer, p: number, limit: number, out: buffer, n: numbe
return true, nil
end
-- encode(px, n, bpp, out, o) -> new offset: n pixels of bpp (3 or 4) bytes; out has room for n * (bpp + 1) bytes
function Codec.encode(px: buffer, n: number, bpp: number, out: buffer, o: number): number
buffer.fill(index, 0, 0, 256)
local pr, pg, pb, pa = 0, 0, 0, 255
+6 -8
View File
@@ -1,8 +1,6 @@
--!strict
-- image/qoi: QOI, the Quite OK Image format (specification 1.0, qoiformat.org). New code written from the spec.
-- Supports: decode of RGB and RGBA files (either colour space tag) to rgba8 (opts.native: rgb8 for 3-channel files);
-- encode of rgba8 (4 channels) and rgb8 (3 channels), lossless; meta.source.colorSpace keeps the sRGB / linear tag.
-- Not supported: nothing in the spec is left out.
-- image/qoi: QOI, the Quite OK Image format (specification 1.0, qoiformat.org). Supports: the whole spec (RGB / RGBA,
-- both colour space tags in meta.source.colorSpace).
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
@@ -22,12 +20,12 @@ local Qoi = {
-- ------------------------------------------------------------------------------------------------ types
export type DecodeOptions = {
native: boolean?, -- rgb8 for 3-channel files (default false: always rgba8)
maxPixels: number?, -- refuse larger images (default 2^26)
native: boolean?, -- default false: rgba8
maxPixels: number?, -- default 2^26
}
export type EncodeOptions = {
channels: number?, -- 3 or 4 (default: 3 for rgb8 images or opaque rgba8, else 4)
linear: boolean?, -- tag the file as linear instead of sRGB (default: meta.source.colorSpace == "linear")
channels: number?, -- default: 3 for rgb8 or opaque rgba8, else 4
linear: boolean?, -- default: meta.source.colorSpace == "linear"
}
-- ------------------------------------------------------------------------------------------------ sniff
+8 -11
View File
@@ -1,10 +1,7 @@
--!strict
-- image/sgi: Silicon Graphics image files (.rgb / .sgi / .bw / .rgba; Paul Haeberli's "The SGI Image File Format"
-- 1.00; new code). Decode: verbatim and RLE storage, 1 and 2 bytes per channel, 1 (grey), 2 (grey + alpha), 3 (RGB)
-- and 4 (RGBA) channels, dimension 1 / 2 / 3, rows bottom-up; rgba8 (2-byte channels keep their high byte), or rgba16
-- with opts.native for 2-byte files; the image name (meta.text.name). Encode: rgba8 as RGB (or RGBA when there is
-- alpha), RLE (default) or verbatim; rgba16 as 2-byte channels. Not supported: the obsolete dithered / screen /
-- colour-map files (colormap field 1..3: UNSUPPORTED).
-- image/sgi: Silicon Graphics images (Paul Haeberli's "The SGI Image File Format" 1.00). Supports: verbatim and RLE, 1
-- / 2 bytes per channel, 1..4 channels, dimension 1..3, bottom-up rows, the image name; writes RGB(A) 8 / 16-bit. Not
-- supported: dithered / screen / colour-map files (colormap 1..3).
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
@@ -24,12 +21,12 @@ local Sgi = {
-- ------------------------------------------------------------------------------------------------ types
export type DecodeOptions = {
native: boolean?, -- rgba16 for 2-byte files (default false: rgba8)
maxPixels: number?, -- refuse larger images (default 2^26)
native: boolean?, -- default false: rgba8
maxPixels: number?, -- default 2^26
}
export type EncodeOptions = {
rle: boolean?, -- RLE storage (default true)
name: string?, -- the image name (up to 79 bytes; default meta.text.name)
rle: boolean?, -- default true
name: string?, -- up to 79 bytes; default meta.text.name
}
local readu8, readu16, readu32 = buffer.readu8, buffer.readu16, buffer.readu32
@@ -79,7 +76,7 @@ function Sgi.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.E
if w * h > maxPixels then
return nil, Err.new(Err.LIMIT, string.format("%d x %d is over the %d pixel limit", w, h, maxPixels))
end
-- channel planes as 16-bit samples (8-bit values scaled * 257)
-- 8-bit values scaled * 257
local plane = buffer.create(w * h * z * 2)
local truncated = false
local function put(c: number, row: number, x: number, v: number)
+5 -8
View File
@@ -1,10 +1,7 @@
--!strict
-- image/sunras: Sun Raster (rasterfile(5), SunOS <rasterfile.h>; new code). Decode: 1-bit (0 = white without a colour
-- map), 8-bit (grey or the RGB colour map), 24-bit and 32-bit pixels in BGR / XBGR order (RT_STANDARD, RT_OLD,
-- RT_BYTE_ENCODED) or RGB / XRGB order (RT_FORMAT_RGB), the byte-encoded RLE (0x80 escapes), 16-bit row padding; in
-- 32-bit files the X byte is alpha when it is not all zero. Encode: rgba8 as 24-bit (opaque) or 32-bit (alpha in the
-- X byte) BGR, RT_BYTE_ENCODED (default) or RT_STANDARD. Not supported: RT_FORMAT_TIFF / RT_FORMAT_IFF (UNSUPPORTED),
-- raw colour maps (RMT_RAW is ignored).
-- image/sunras: Sun Raster (rasterfile(5), SunOS <rasterfile.h>). Supports: 1-bit (0 = white without a colour map),
-- 8-bit, 24 / 32-bit BGR / XBGR (RT_STANDARD, RT_OLD, RT_BYTE_ENCODED) or RGB / XRGB (RT_FORMAT_RGB), 0x80 RLE, 16-bit
-- row padding; 32-bit X is alpha unless all zero. Not supported: RT_FORMAT_TIFF / RT_FORMAT_IFF, RMT_RAW.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
@@ -25,10 +22,10 @@ local Sunras = {
-- ------------------------------------------------------------------------------------------------ types
export type DecodeOptions = {
maxPixels: number?, -- refuse larger images (default 2^26)
maxPixels: number?, -- default 2^26
}
export type EncodeOptions = {
rle: boolean?, -- RT_BYTE_ENCODED (default true); false: RT_STANDARD
rle: boolean?, -- default true; false: RT_STANDARD
}
local MAGIC = "\89\166\106\149"
+2 -9
View File
@@ -1,15 +1,12 @@
--!strict
--!native
--!optimize 2
-- image/tga/Codec: the Truevision TGA pixel loops (native; never throws). Written from the Truevision TGA 2.0
-- specification. decode reads raw or RLE pixel data (packets may cross scanlines) into rgba8 at the oriented
-- position; encode writes raw or RLE rows. Every read is bounds-checked; the output has exactly w * h * 4 bytes.
-- image/tga/Codec: Truevision TGA 2.0 pixel loops: raw / RLE (packets may cross scanlines on read, never on write).
local readu8, readu16, readu32, writeu8, writeu32 = buffer.readu8, buffer.readu16, buffer.readu32, buffer.writeu8, buffer.writeu32
local Codec = {}
-- one source pixel at b[p] -> rgba as a u32; kind: 0 grey 8, 1 grey + alpha 16, 2 = 15/16-bit ARGB1555,
-- 3 = BGR 24, 4 = BGRA 32, 5 = index 8, 6 = index 16 (pal: u32 entries, palN of them)
-- kind: 0 grey 8, 1 grey + alpha 16, 2 = 15/16-bit ARGB1555, 3 = BGR 24, 4 = BGRA 32, 5 = index 8, 6 = index 16
local function pixel(b: buffer, p: number, kind: number, alpha1: boolean, pal: buffer, palN: number): number
if kind == 0 then
return readu8(b, p) * 0x10101 + 0xFF000000
@@ -33,7 +30,6 @@ local function pixel(b: buffer, p: number, kind: number, alpha1: boolean, pal: b
end
Codec.pixel = pixel
-- decode(b, p, limit, w, h, bpp, kind, alpha1, rle, bottomUp, rtl, pal, palN, out) -> pixels written, truncated?
function Codec.decode(b: buffer, p: number, limit: number, w: number, h: number, bpp: number, kind: number, alpha1: boolean, rle: boolean, bottomUp: boolean, rtl: boolean, pal: buffer, palN: number, out: buffer): (number, boolean)
local n = w * h
local i = 0
@@ -85,9 +81,6 @@ function Codec.decode(b: buffer, p: number, limit: number, w: number, h: number,
return i, false
end
-- encode(px, w, h, srcBpp, outBpp, rle, topDown, out, o) -> new offset. px: rgba8 / rgb8 / gray8 (srcBpp 4 / 3 / 1);
-- written as BGRA / BGR / grey (outBpp 4 / 3 / 1), rows top-down or bottom-up; RLE packets stay inside a row.
-- out needs room for w * h * (outBpp + 1) bytes.
function Codec.encode(px: buffer, w: number, h: number, srcBpp: number, outBpp: number, rle: boolean, topDown: boolean, out: buffer, o: number): number
local function get(q: number): number
if srcBpp == 1 then
+9 -17
View File
@@ -1,13 +1,7 @@
--!strict
-- image/tga: Truevision TGA (TGA 2.0 specification; new code). Decode: colour-mapped (1), true-colour (2) and grey (3)
-- images, raw or RLE (9, 10, 11; packets may cross scanlines), 8 / 15 / 16 / 24 / 32-bit pixels, 15 / 16 / 24 /
-- 32-bit colour maps with a first index, 8 / 16-bit indexes, grey + alpha (16-bit type 3), every origin (bottom-left,
-- top-left, right-to-left), the alpha bits of the descriptor (16-bit: alpha only when it declares 1 alpha bit; 32-bit:
-- alpha always), the image ID (meta.text.id) and the TGA 2.0 footer (tolerated, not needed). Truncated pixel data
-- leaves the rest transparent black (meta.truncated). opts.native: gray8 for grey files, rgb8 for 24-bit.
-- Encode: rgba8 (32-bit BGRA when there is alpha, else 24-bit), rgb8 (24-bit), gray8 (type 3), raw or RLE, bottom-left
-- (default) or top-left origin, with the TGA 2.0 footer. Not supported: the extension area's fields (gamma, postage
-- stamp, ...), which are ignored.
-- image/tga: Truevision TGA (TGA 2.0 specification). Supports: types 1 / 2 / 3 and RLE 9 / 10 / 11, 8..32-bit pixels
-- and colour maps, every origin, descriptor alpha bits (16-bit: only when 1 alpha bit is declared), the image ID, the
-- 2.0 footer. Not supported: the extension area's fields (ignored).
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
@@ -27,14 +21,14 @@ local Tga = {
-- ------------------------------------------------------------------------------------------------ types
export type DecodeOptions = {
native: boolean?, -- gray8 for grey files, rgb8 for 24-bit ones (default false: rgba8)
maxPixels: number?, -- refuse larger images (default 2^26)
native: boolean?, -- default false: rgba8
maxPixels: number?, -- default 2^26
}
export type EncodeOptions = {
rle: boolean?, -- run-length encode (default false)
origin: ("bottom-left" | "top-left")?, -- default "bottom-left" (the classic layout every reader understands)
alpha: boolean?, -- force 32-bit (true) or 24-bit (false) for rgba8 (default: 32-bit when any alpha < 255)
id: string?, -- the image ID field (up to 255 bytes; default meta.text.id)
rle: boolean?, -- default false
origin: ("bottom-left" | "top-left")?, -- default "bottom-left"
alpha: boolean?, -- default: 32-bit when any alpha < 255
id: string?, -- up to 255 bytes; default meta.text.id
}
-- ------------------------------------------------------------------------------------------------ constants
@@ -79,7 +73,6 @@ local function header(r: Bytes.Reader): Header?
return h
end
-- plausible(h) -> nil | why not
local function implausible(h: Header): string?
local t = h.imageType
if not TYPES[t] then
@@ -141,7 +134,6 @@ function Tga.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.E
local p = r.base + 18
local id = if h.idLen > 0 and p + h.idLen <= r.limit then buffer.readstring(b, p, h.idLen) else nil
p += h.idLen
-- colour map
local pal = buffer.create(4)
local palN = 0
if h.cmapType == 1 and h.cmapLen > 0 then
+6 -17
View File
@@ -1,10 +1,7 @@
--!strict
--!native
--!optimize 2
-- image/tiff/Pixels: the hot loops of the TIFF codec (native; never throws): the horizontal (2) and
-- floating-point (3) predictors both ways (TIFF 6.0 section 14, Adobe TIFF technote 3; predictor 3 as libtiff's
-- fpAcc / fpDiff), fill-order bit reversal, and the sample converter from decoded planes to a Types.Image layout.
-- Callers (image/tiff/init) size every buffer before calling: planes hold h rows of rb bytes plus 8 bytes of slack.
-- image/tiff/Pixels: TIFF predictors 2 / 3 (TIFF 6.0 section 14, technote 3; 3 as libtiff fpAcc / fpDiff).
local Bytes = require("@rosetta/core/Bytes")
local readu8, writeu8, readu16, writeu16, readu32, writeu32 = buffer.readu8, buffer.writeu8, buffer.readu16, buffer.writeu16, buffer.readu32, buffer.writeu32
local readf32, writef32, readf64 = buffer.readf32, buffer.writef32, buffer.readf64
@@ -15,8 +12,7 @@ local Pixels = {}
local scratch = buffer.create(8)
-- floats read through their bits: NaN / infinity never load from memory (LuaJIT's FFI would hand back a NaN with an
-- arbitrary payload, which its NaN-tagged values misread as a table / userdata)
-- floats read through their bits: LuaJIT's FFI can hand back a NaN with a payload its NaN-tagging misreads
local function f32(bits: number): number
if band(bits, 0x7F800000) == 0x7F800000 then
if band(bits, 0x7FFFFF) ~= 0 then
@@ -59,7 +55,6 @@ function Pixels.reverseBits(b: buffer, off: number, len: number)
end
-- ------------------------------------------------------------------------------------------------ predictors
-- unpredict2(b, off, rows, rb, stride, bps, le): undo horizontal differencing (bps 8, 16 or 32; others untouched)
function Pixels.unpredict2(b: buffer, off: number, rows: number, rb: number, stride: number, bps: number, le: boolean)
for r = 0, rows - 1 do
local base = off + r * rb
@@ -95,7 +90,6 @@ function Pixels.unpredict2(b: buffer, off: number, rows: number, rb: number, str
end
end
-- predict2(b, off, rows, rb, stride, bps): apply horizontal differencing to little-endian samples (8 / 16 bit)
function Pixels.predict2(b: buffer, off: number, rows: number, rb: number, stride: number, bps: number)
for r = 0, rows - 1 do
local base = off + r * rb
@@ -112,8 +106,7 @@ function Pixels.predict2(b: buffer, off: number, rows: number, rb: number, strid
end
end
-- unpredict3(b, off, rows, rb, bytes, stride, tmp): undo the floating-point predictor; the samples come out little
-- endian whatever the file's byte order (libtiff fpAcc). tmp holds at least rb bytes.
-- the samples come out little endian whatever the file's byte order (libtiff fpAcc)
function Pixels.unpredict3(b: buffer, off: number, rows: number, rb: number, bytes: number, stride: number, tmp: buffer)
local wc = rb // bytes
for r = 0, rows - 1 do
@@ -130,7 +123,6 @@ function Pixels.unpredict3(b: buffer, off: number, rows: number, rb: number, byt
end
end
-- predict3(b, off, rows, rb, bytes, stride, tmp): the floating-point predictor on little-endian samples (fpDiff)
function Pixels.predict3(b: buffer, off: number, rows: number, rb: number, bytes: number, stride: number, tmp: buffer)
local wc = rb // bytes
for r = 0, rows - 1 do
@@ -152,7 +144,7 @@ local half = Bytes.half
export type Params = {
planes: { buffer },
rb: number, -- bytes per row in each plane
rb: number,
chunky: boolean,
w: number,
h: number,
@@ -161,14 +153,13 @@ export type Params = {
sfmt: number, -- 1 uint, 2 int, 3 float
le: boolean,
photo: number, -- 0 min-is-white, 1 min-is-black, 2 RGB, 3 palette, 5 CMYK
alpha: number, -- sample index of the alpha channel, -1 = none
alpha: number,
assoc: boolean, -- premultiplied alpha (undone)
cmap: buffer?, -- palette: 3 * 2^bps u16 (red block, green block, blue block)
kind: string, -- the output pixel format
kind: string,
out: buffer,
}
-- the common 8-bit chunky cases without per-sample dispatch; false when P is not one of them
local function fast(P: Params): boolean
if not P.chunky or P.bps ~= 8 or P.sfmt ~= 1 or P.assoc then
return false
@@ -218,7 +209,6 @@ local function fast(P: Params): boolean
return false
end
-- convert(P): every pixel into P.out in P.kind's layout
function Pixels.convert(P: Params)
if fast(P) then
return
@@ -229,7 +219,6 @@ function Pixels.convert(P: Params)
local float = sfmt == 3
local signed = sfmt == 2
local cmapN = 2 ^ math.min(bps, 16)
-- raw sample s of pixel x in the row starting at byte ro of its plane
local function raw(s: number, x: number, row: number): number
local b, i
if chunky then
+13 -30
View File
@@ -1,15 +1,7 @@
--!strict
-- image/tiff: TIFF 6.0 (+ Adobe technote 3 floating point, BigTIFF). New code from the TIFF 6.0 specification.
-- Decode: both byte orders, classic and BigTIFF, strips and tiles, planar configuration 1 and 2, compression none /
-- LZW (codecs/compress/Lzw, also old-style) / Deflate (8 and 32946, codecs/compress/Deflate) / PackBits, JPEG (7) through the api's
-- opts.decodeImage hook (JPEGTables stitched to each strip / tile), predictors 2 (8 / 16 / 32-bit) and 3 (float),
-- 1..32-bit unsigned / signed integer and 16 / 32 / 64-bit float samples, min-is-white / min-is-black, RGB, palette,
-- CMYK (naive conversion), extra samples (associated alpha is un-premultiplied), fill order 2, every page as
-- img.frames, resolution (meta.dpi), ICC (meta.icc). Decodes to rgba8, or with opts.native to the nearest standard
-- layout (gray8, gray16, graya8, rgb8, rgba8, rgba16, rgbaf32).
-- Encode: rgba8 / rgb8 / gray8 / graya8 / gray16 / rgba16 / rgbaf32 as the matching TIFF layout, compression none /
-- deflate / lzw / packbits with predictor 2 (integers) or 3 (floats), strips, multi-page from img.frames.
-- Not supported: old-style JPEG (6), CCITT fax (2, 3, 4), uncompressed YCbCr with subsampling, CIELab, JBIG.
-- image/tiff: TIFF 6.0 (+ Adobe technote 3, BigTIFF). Supports: strips, tiles, planar 1 / 2, none / LZW (old-style too)
-- / Deflate (8, 32946) / PackBits / JPEG (7), predictors 2 / 3, int / float samples, CMYK (naive), fill order 2. Not
-- supported: old-style JPEG (6), CCITT (2, 3, 4), YCbCr, CIELab, JBIG.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
@@ -32,16 +24,16 @@ local Tiff = {
-- ------------------------------------------------------------------------------------------------ types
export type DecodeOptions = {
native: boolean?, -- keep the source layout (gray8 / gray16 / graya8 / rgb8 / rgba8 / rgba16 / rgbaf32); default rgba8
maxPixels: number?, -- per page (default 2^26)
maxPages: number?, -- pages decoded into img.frames (default 1024)
page: number?, -- decode only this page (1-based)
decodeImage: ((buffer) -> (any, any))?, -- the api's hook, for JPEG-compressed pages
native: boolean?, -- default false: rgba8
maxPixels: number?, -- per page, default 2^26
maxPages: number?, -- default 1024
page: number?, -- 1-based
decodeImage: ((buffer) -> (any, any))?,
}
export type EncodeOptions = {
compression: ("none" | "deflate" | "lzw" | "packbits")?, -- default "deflate"
predictor: boolean?, -- horizontal / float predictor with deflate and lzw (default true)
level: number?, -- deflate level 0..9 (default 6)
predictor: boolean?, -- default true
level: number?, -- 0..9, default 6
rowsPerStrip: number?, -- default: about 64 KB per strip
}
@@ -90,7 +82,6 @@ local function off(c: Ctx, at: number): number
return if c.big then u64(c, at) else u32(c, at)
end
-- values(c, e, max) -> the entry's numbers (rationals divided) | nil when out of range / too many
local function values(c: Ctx, e: Entry?, max: number?): { number }?
if not e then
return nil
@@ -155,7 +146,6 @@ local function one(c: Ctx, e: Entry?, default: number): number
return if v and v[1] then v[1] else default
end
-- the IFD at absolute offset p: { [tag] = Entry }, next IFD offset (absolute, 0 = none) | nil, Err
local function readIfd(c: Ctx, p: number): ({ [number]: Entry }?, number, Err.Err?)
local esize = if c.big then 20 else 12
local hsize = if c.big then 8 else 2
@@ -203,7 +193,6 @@ local function bytesOf(c: Ctx, e: Entry?, max: number): buffer?
return x
end
-- decompress one chunk at [p, p + len) into out[o, o + size): bytes produced | nil, Err
local function inflateChunk(c: Ctx, comp: number, p: number, len: number, out: buffer, o: number, size: number, rev: boolean): (number?, Err.Err?)
if p < c.base or len < 0 or p + len > c.limit then
-- a chunk past the end: keep what exists (truncated files)
@@ -308,10 +297,10 @@ local function decodePage(c: Ctx, t: { [number]: Entry }, opts: DecodeOptions?):
if ch > h and not tiled then
ch = h
end
local pspp = if chunky then spp else 1 -- samples per pixel in one plane
local pspp = if chunky then spp else 1
local nplanes = if chunky then 1 else spp
local rb = math.ceil(w * pspp * bps / 8) -- bytes per image row in a plane
local crb = math.ceil(cw * pspp * bps / 8) -- bytes per chunk row
local rb = math.ceil(w * pspp * bps / 8)
local crb = math.ceil(cw * pspp * bps / 8)
if rb * h * nplanes > 2 ^ 30 or crb * ch > 2 ^ 30 then
return nil, Err.new(Err.LIMIT, "decoded data over 1 GB")
end
@@ -382,7 +371,6 @@ local function decodePage(c: Ctx, t: { [number]: Entry }, opts: DecodeOptions?):
elseif predictor == 3 and bytesPer >= 2 and crb % bytesPer == 0 then
Pixels.unpredict3(tmp, 0, rows, crb, bytesPer, pspp, ftmp)
end
-- into the plane
local plane = planes[pl + 1]
local x0b = math.floor(tx * cw * pspp * bps / 8)
local cols = math.min(cw, w - tx * cw)
@@ -402,7 +390,6 @@ local function decodePage(c: Ctx, t: { [number]: Entry }, opts: DecodeOptions?):
le = true -- fpAcc leaves the samples little endian
end
local colorType = PHOTOMETRIC[photo]
-- the output layout
local kind = "rgba8"
if opts and opts.native and comp ~= 7 then
if photo == 3 or photo == 5 then
@@ -506,7 +493,6 @@ local function decodePage(c: Ctx, t: { [number]: Entry }, opts: DecodeOptions?):
return img, nil
end
-- pages(r) -> the IFD tables of every page (and the context) | nil, Err
local function pages(r: Bytes.Reader, maxPages: number): ({ { [number]: Entry } }?, Ctx?, Err.Err?)
local b, base, limit = r.buf, r.base, r.limit
if limit - base < 8 then
@@ -551,7 +537,6 @@ local function pages(r: Bytes.Reader, maxPages: number): ({ { [number]: Entry }
return list, c, nil
end
-- info(r) -> { pages, width, height, bitDepth, samples, compression } of page 1 | nil, Err
function Tiff.info(r: Bytes.Reader): ({ [string]: any }?, Err.Err?)
local list, c, err = pages(r, 1024)
if not list or not c then
@@ -617,7 +602,6 @@ function Tiff.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.
end
-- ------------------------------------------------------------------------------------------------ encode
-- layout per pixel format: samples, bits, sample format, photometric, extra samples
local LAYOUT = {
gray8 = { 1, 8, 1, 1 },
graya8 = { 2, 8, 1, 1 },
@@ -764,7 +748,6 @@ function Tiff.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?
if not tags or not strips then
return nil, err
end
-- strip data first
local soffs = {}
for i, s in strips do
if w:tell() % 2 == 1 then
+6 -13
View File
@@ -1,13 +1,7 @@
--!strict
-- image/tim: PlayStation TIM images (magic 0x10), read and write. Written from the PSX "File Formats" documentation
-- (Sony, TIM: pmode, CLUT and image blocks with their VRAM positions); no code taken.
-- Decode: 4-bit and 8-bit CLUT images (opts.clut picks the palette row, default 0), 15-bit direct and 24-bit
-- direct, to rgba8: PSX colours are 1-5-5-5 STP-B-G-R, channels expanded as (v << 3) | (v >> 2); the colour 0x0000
-- is transparent (alpha 0) as on the hardware, others opaque (the STP bit is kept in meta.source.stp = true when
-- any pixel or CLUT entry has it). meta.source = { format, bpp, clut = { x, y, colours, count }?, x, y (VRAM) }.
-- Encode: rgba8 to 16-bit direct (default), 24-bit (opts.bpp = 24, alpha dropped) or 4 / 8-bit CLUT when the image
-- has at most 16 / 256 PSX colours (opts.bpp = 4 / 8; Err.ARG otherwise); alpha below 128 becomes 0x0000; opaque
-- black is written as 0x8000 (STP set) so it stays opaque. Not supported: mixed mode (pmode 4) images.
-- image/tim: PlayStation TIM (magic 0x10), from Sony's PSX "File Formats" documentation. Supports: 4 / 8-bit CLUT, 15 /
-- 24-bit direct; colours are 1-5-5-5 STP-B-G-R, expanded (v << 3) | (v >> 2), 0x0000 transparent as on the hardware,
-- opaque black written as 0x8000. Not supported: mixed mode (pmode 4).
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
@@ -26,14 +20,14 @@ local Tim = {
-- ------------------------------------------------------------------------------------------------ types
export type DecodeOptions = {
clut: number?, -- the CLUT row to use for indexed images (0-based, default 0)
clut: number?, -- 0-based, default 0
maxPixels: number?, -- default 2^26
}
export type EncodeOptions = {
bpp: number?, -- 4, 8, 16 (default) or 24
x: number?, -- VRAM position of the image (default 0, 0)
x: number?, -- default 0, 0
y: number?,
clutX: number?, -- VRAM position of the CLUT (default 0, 480)
clutX: number?, -- default 0, 480
clutY: number?,
}
@@ -160,7 +154,6 @@ function Tim.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.E
end
-- ------------------------------------------------------------------------------------------------ encode
-- rgba8 pixel -> PSX colour
local function psx(v: number): number
local r, g, b, a = v % 256, (v // 256) % 256, (v // 65536) % 256, v // 16777216
if a < 128 then
+8 -20
View File
@@ -1,16 +1,7 @@
--!strict
-- image/vtf: Valve Texture Format (VTF 7.0 - 7.5: Source engine textures), read. Written from the Valve Developer
-- Community "VTF (Valve Texture Format)" page; no code taken.
-- Decode: the high-resolution image (located by the 7.3+ resource directory or after the low-resolution thumbnail
-- for 7.0 - 7.2), mip 0 of slice 0 and face 0 (opts.mip / opts.face / opts.slice pick others), frame 1 as the Image
-- and every frame of an animated texture in img.frames (opts.frames ~= false; delay opts.delay, default 0.1 s), to
-- rgba8. Texel formats: RGBA8888, ABGR8888, RGB888, BGR888, RGB565, I8, IA88, A8, RGB888 / BGR888 bluescreen (pure
-- blue transparent), ARGB8888, BGRA8888, BGRX8888, BGR565, BGRX5551, BGRA5551, BGRA4444, UV88, UVWQ8888, UVLX8888,
-- RGBA16161616 (integers) / RGBA16161616F (halves, clamped), R32F, RGB323232F, RGBA32323232F (all through
-- codecs/image/Texel), DXT1 (+ one-bit alpha),
-- DXT3, DXT5, ATI1N, ATI2N (ids 35 / 34 since Alien Swarm, 38 / 37 in Source 2013) through codecs/image/Bcn. meta.source = { format, version, flags, frames, faces, depth, mips,
-- texel, reflectivity, bumpScale }.
-- Not supported: P8 (never implemented by Valve), the newer Strata / Source 2 formats, writing.
-- image/vtf: Valve Texture Format 7.0 - 7.5 (Source engine), from the Valve Developer Community VTF page. Supports: the
-- high-resolution image, mips / faces / slices / frames, uncompressed texels, DXT1 / DXT3 / DXT5, ATI1N / ATI2N (35 /
-- 34 Alien Swarm, 38 / 37 Source 2013). Not supported: P8, Strata / Source 2 formats, writing.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
@@ -31,17 +22,16 @@ local Vtf = {
-- ------------------------------------------------------------------------------------------------ types
export type DecodeOptions = {
mip: number?, -- mip level (0 = full size, default)
face: number?, -- cube map face (0-based, default 0)
slice: number?, -- volume slice (0-based, default 0)
frames: boolean?, -- decode every frame into img.frames (default true)
delay: number?, -- frame delay in seconds (default 0.1)
mip: number?, -- 0 = full size, default
face: number?, -- 0-based, default 0
slice: number?, -- 0-based, default 0
frames: boolean?, -- default true
delay: number?, -- seconds, default 0.1
maxPixels: number?, -- default 2^26
}
-- ------------------------------------------------------------------------------------------------ constants
local M = Texel.masked
-- format id -> a codecs/image/Texel format (name or bit-mask descriptor) | { texel, bluescreen = true } | a BCn kind
local FORMATS: { [number]: any } = {
[0] = "rgba8", -- RGBA8888
[1] = M(4, 0xFF000000, 0x00FF0000, 0x0000FF00, 0x000000FF), -- ABGR8888
@@ -90,7 +80,6 @@ function Vtf.sniff(r: Bytes.Reader): number
end
-- ------------------------------------------------------------------------------------------------ decode
-- bytes of one w x h image in format f
local function imageSize(f: any, w: number, h: number): number
if type(f) == "string" and BCN[f] then
return Bcn.size(if f == "bc1a" then "bc1" else f, w, h) or 0
@@ -162,7 +151,6 @@ function Vtf.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.E
local lowSize = if lowFmt >= 0 and lowW > 0 and lowH > 0 and lf then imageSize(lf, lowW, lowH) else 0
dataAt = headerSize + lowSize
end
-- the chain: mips smallest first; per mip: frames, faces, slices
local mip = math.clamp(math.floor(opts and opts.mip or 0), 0, mips - 1)
local face = math.clamp(math.floor(opts and opts.face or 0), 0, faces - 1)
local slice = math.clamp(math.floor(opts and opts.slice or 0), 0, depth - 1)
+2 -4
View File
@@ -1,8 +1,7 @@
--!strict
--!native
-- image/webp/Alpha: the ALPH chunk (RFC 9649 section 2.7.1.2): header byte (compression, filter, pre-processing),
-- raw or VP8L-compressed alpha (the green channel of a headerless VP8L stream), and the horizontal / vertical /
-- gradient unfilters of libwebp src/dsp/filters.c (BSD-3-Clause, licenses/libwebp-LICENSE.txt). Never throws.
-- image/webp/Alpha: the ALPH chunk (RFC 9649 section 2.7.1.2); unfilters of libwebp src/dsp/filters.c (BSD-3-Clause,
-- licenses/libwebp-LICENSE.txt).
local Vp8L = require("@rosetta/codecs/image/Vp8L")
local readu8, writeu8 = buffer.readu8, buffer.writeu8
@@ -42,7 +41,6 @@ local function unfilter(a: buffer, w: number, h: number, filter: number)
end
end
-- decode(buf, off, len, w, h) -> w * h alpha bytes, header info | nil, message
function Alpha.decode(buf: buffer, off: number, len: number, w: number, h: number): (buffer?, any)
if len <= 1 then
return nil, "truncated: ALPH chunk"
+7 -16
View File
@@ -1,10 +1,7 @@
--!strict
--!native
-- image/webp/Anim: animation compositing. coalesce() reproduces libwebp's WebPAnimDecoder (src/demux/anim_decode.c,
-- BSD-3-Clause, licenses/libwebp-LICENSE.txt) exactly: key frame detection, transparent canvas (the background colour
-- is ignored, as the spec recommends and libwebp does), non-premultiplied "over" blending of the pixels with alpha
-- < 255, dispose to background. composite() is the generic Types.Frame model (also dispose "previous") used by the
-- encoder to flatten frames WebP cannot store as they are. Pixels are rgba8; never throws.
-- image/webp/Anim: WebP animation compositing; coalesce() matches libwebp's WebPAnimDecoder (src/demux/anim_decode.c,
-- BSD-3-Clause, licenses/libwebp-LICENSE.txt): the background colour is ignored, as the spec recommends.
local band, rshift = bit32.band, bit32.rshift
local readu32, writeu32 = buffer.readu32, buffer.writeu32
local bcreate, bcopy, bfill = buffer.create, buffer.copy, buffer.fill
@@ -12,18 +9,18 @@ local bcreate, bcopy, bfill = buffer.create, buffer.copy, buffer.fill
local Anim = {}
export type Frame = {
rgba: buffer, -- w * h rgba8
rgba: buffer,
x: number,
y: number,
w: number,
h: number,
blend: boolean, -- alpha-blend over the canvas (false: overwrite)
disposeBg: boolean, -- after display, clear the rectangle to transparent
disposePrev: boolean?, -- after display, restore the canvas as it was before the frame (composite() only)
blend: boolean,
disposeBg: boolean,
disposePrev: boolean?, -- composite() only
hasAlpha: boolean,
}
-- blend(src, dst) -> src over dst, both non-premultiplied 0xAABBGGRR (libwebp BlendPixelNonPremult)
-- non-premultiplied 0xAABBGGRR, as libwebp BlendPixelNonPremult
local function blendPixel(src: number, dst: number): number
local sa = rshift(src, 24)
if sa == 0 then
@@ -40,7 +37,6 @@ local function blendPixel(src: number, dst: number): number
end
Anim.blendPixel = blendPixel
-- blendRow(cur, prev, offset, n): pixels of cur with alpha < 255 blended over prev (pixel offsets)
local function blendRow(cur: buffer, prev: buffer, o: number, n: number)
for i = o, o + n - 1 do
local s = readu32(cur, i * 4)
@@ -50,7 +46,6 @@ local function blendRow(cur: buffer, prev: buffer, o: number, n: number)
end
end
-- draw(canvas, cw, f): copy the frame rectangle into the canvas
local function draw(canvas: buffer, cw: number, f: Frame)
for j = 0, f.h - 1 do
bcopy(canvas, ((f.y + j) * cw + f.x) * 4, f.rgba, j * f.w * 4, f.w * 4)
@@ -63,7 +58,6 @@ local function clearRect(canvas: buffer, cw: number, x: number, y: number, w: nu
end
end
-- coalesce(cw, ch, frames) -> one full canvas (rgba8) per frame, as WebPAnimDecoder returns them
function Anim.coalesce(cw: number, ch: number, frames: { Frame }): { buffer }
local size = cw * ch * 4
local out: { buffer } = {}
@@ -122,9 +116,6 @@ function Anim.coalesce(cw: number, ch: number, frames: { Frame }): { buffer }
return out
end
-- composite(cw, ch, frames) -> one full canvas per frame in the generic model: start transparent, draw (blend or
-- overwrite; "over" a fully transparent pixel copies it), show, then dispose (background: clear the rectangle;
-- previous: restore)
function Anim.composite(cw: number, ch: number, frames: { Frame }): { buffer }
local size = cw * ch * 4
local canvas = bcreate(size)
+14 -33
View File
@@ -1,18 +1,7 @@
--!strict
-- image/webp: WebP (RFC 9649; Google's "WebP Container Specification"). New code: the bitstreams are ports of libwebp 1.6
-- (codecs/image/Vp8, codecs/image/Vp8L; BSD-3-Clause, licenses/libwebp-LICENSE.txt), the chunks go through containers/Riff, the
-- container rules and the compositing follow libwebp's demux / WebPAnimDecoder.
-- Supports: decode of lossy (VP8 key frames: bit-exact with dwebp, fancy or point chroma upsampling, or the raw
-- yuv420p planes with opts.native), lossless (VP8L, bit-exact), alpha (ALPH raw or lossless, every filter), the
-- extended format (VP8X), animation (ANIM / ANMF: frames as their own rectangles plus the composited first frame, or
-- every frame composited exactly as WebPAnimDecoder with opts.coalesce), ICC / EXIF / XMP into meta.icc / meta.exif
-- / meta.xmp; encode of rgba8 images and animations as lossless VP8L (VP8X / ANIM / ANMF for animations and
-- metadata).
-- Not supported: lossy encoding (UNSUPPORTED), the VP8 horizontal / vertical scale fields (ignored, as dwebp does),
-- alpha dithering / premultiplied output.
-- Speed (one Zen 5 core, 512 x 512, tools/bench.luau): lossy decode ~50 MB/s of rgba8 out (luau --codegen) / ~38 MB/s
-- (LuaJIT), lossless decode ~43 / ~73 MB/s, lossless encode ~6 / ~8 MB/s at effort 5 (~15 / ~18 MB/s at effort 1).
-- Encoded size: within ~4 % of cwebp -lossless on photos at effort 9, smaller on some synthetic images.
-- image/webp: WebP (RFC 9649); bitstreams ported from libwebp 1.6 (BSD-3-Clause, licenses/libwebp-LICENSE.txt).
-- Supports: VP8 key frames (bit-exact with dwebp), VP8L, ALPH, VP8X, ANIM / ANMF, ICC / EXIF / XMP; writes VP8L. Not
-- supported: lossy encoding, VP8 scale fields (ignored, as dwebp), alpha dithering.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
@@ -36,21 +25,19 @@ local Webp = {
-- ------------------------------------------------------------------------------------------------ types
export type DecodeOptions = {
maxPixels: number?, -- refuse a canvas or frame larger than this (default 2^26)
native: boolean?, -- a still lossy image without alpha decodes to its yuv420p planes (default false: rgba8)
upsampling: ("fancy" | "nearest")?, -- lossy chroma upsampling, default "fancy" (libwebp's default; "nearest" =
-- dwebp -nofancy)
coalesce: boolean?, -- animations: every frame is the full composited canvas (x = y = 0, dispose "none",
-- blend "source"), exactly what WebPAnimDecoder returns (default false: each frame's own rectangle)
frames: boolean?, -- animations: decode every frame (default true; false: only the first canvas)
maxPixels: number?, -- default 2^26
native: boolean?, -- default false: rgba8
upsampling: ("fancy" | "nearest")?, -- default "fancy" (libwebp's; "nearest" = dwebp -nofancy)
coalesce: boolean?, -- default false: each frame's own rectangle
frames: boolean?, -- default true
}
export type EncodeOptions = {
lossless: boolean?, -- must be true or nil (lossy encoding is not supported)
effort: number?, -- 0..9, default 5: VP8L encoder effort (more = smaller, slower)
exact: boolean?, -- keep the RGB of fully transparent pixels (default false: they may be changed)
loops: number?, -- animations: play count (default img.loops; 0 = forever)
background: { number }?, -- animations: ANIM background colour { r, g, b, a } (default meta.background or 0)
lossless: boolean?, -- true or nil
effort: number?, -- 0..9, default 5
exact: boolean?, -- default false
loops: number?, -- default img.loops; 0 = forever
background: { number }?, -- default meta.background or 0
}
-- ------------------------------------------------------------------------------------------------ constants
@@ -67,7 +54,6 @@ local function corrupt(msg: string, offset: number?): (nil, Err.Err)
return nil, Err.new(Err.CORRUPT, msg, offset)
end
-- an Err from a submodule message ("truncated: ...", "limit: ...", "unsupported: ...", else CORRUPT)
local function fromMessage(msg: any, offset: number?): Err.Err
if Err.is(msg) then
return msg
@@ -103,8 +89,7 @@ local function convert(list: { Riff.Chunk }): ({ Chunk }?, Err.Err?)
return out, nil
end
-- readChunks(r) -> the chunks of a RIFF "WEBP" file, the containers/Riff File | nil, Err. As libwebp: the RIFF size
-- must fit the data (TRUNCATED) and bytes after it are ignored.
-- as libwebp: the RIFF size must fit the data and bytes after it are ignored
local function readChunks(r: Bytes.Reader): ({ Chunk }?, any)
local buf, base, limit = r.buf, r.base, r.limit
if limit - base < 12 then
@@ -131,7 +116,6 @@ local function readChunks(r: Bytes.Reader): ({ Chunk }?, any)
return list, f
end
-- subChunks(f, c) -> the chunks inside an ANMF payload (after its 16-byte header)
local function subChunks(f: Riff.File, c: Chunk): ({ Chunk }?, Err.Err?)
local n = c.size - 12
return convert(Riff.list(f, { id = c.id, start = c.off + 4, offset = c.off + 12, size = n, declared = n, avail = n, truncated = false, streamed = false }))
@@ -374,7 +358,6 @@ function Webp.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.
return img, nil
end
-- info(r) -> { width, height, animated, alpha, lossless, frames? } from the headers only | nil, Err
function Webp.info(r: Bytes.Reader): (any, Err.Err?)
local chunks, cerr = readChunks(r)
if not chunks then
@@ -599,8 +582,6 @@ function Webp.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?
end
-- ------------------------------------------------------------------------------------------------ extras
-- coalesce(img) -> the full composited canvases of a decoded animation's frames ({ buffer }, rgba8), the way
-- WebPAnimDecoder composites them (nil for a still image or frames that do not fit the canvas)
function Webp.coalesce(img: Types.Image): { buffer }?
if type(img) ~= "table" or type(img.frames) ~= "table" or type(img.width) ~= "number" or type(img.height) ~= "number" then
return nil
+6 -9
View File
@@ -1,8 +1,6 @@
--!strict
-- image/xbm: X BitMap (X11 bitmap(1) C source; X10 16-bit variant; new code). Decode: the #define _width / _height
-- (and _x_hot / _y_hot: meta.hotspot), the char / short bits array in hex, decimal or octal, LSB first, set bits black,
-- clear bits white (opts.transparent: clear bits transparent instead). Encode: rgba8 thresholded (luminance below
-- opts.threshold, default 128, and alpha >= 128 is black), X11 format, opts.name (default "image").
-- image/xbm: X BitMap (X11 bitmap(1) C source; X10 16-bit variant). Supports: _width / _height / _x_hot / _y_hot
-- defines, char / short arrays in hex, decimal or octal, LSB first, set bits black; writes X11 format.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
@@ -22,12 +20,12 @@ local Xbm = {
-- ------------------------------------------------------------------------------------------------ types
export type DecodeOptions = {
transparent: boolean?, -- clear bits transparent (default false: white)
maxPixels: number?, -- refuse larger images (default 2^26)
transparent: boolean?, -- default false: white
maxPixels: number?, -- default 2^26
}
export type EncodeOptions = {
name: string?, -- the C identifier prefix (default "image"; an extension is dropped, other characters become _)
threshold: number?, -- luminance below this is black (default 128)
name: string?, -- default "image"
threshold: number?, -- default 128
}
-- ------------------------------------------------------------------------------------------------ sniff
@@ -120,7 +118,6 @@ function Xbm.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?)
if w < 1 or h < 1 then
return nil, Err.new(Err.ARG, "bad size")
end
-- a C identifier from opts.name (F.save passes the file name: "out.xbm" -> out)
local name = string.gsub(string.gsub(opts and opts.name or "image", "%.[^.]*$", ""), "[^%w_]", "_")
if name == "" or string.match(name, "^%d") then
name = "_" .. name
+1 -4
View File
@@ -1,7 +1,5 @@
--!strict
-- image/xpm/Names: colour names for XPM colour tables: the CSS Color 4 named colours (which come from X11), with X11's
-- own values where the two differ (gray / grey, green, maroon, purple), and X11's grey0 .. grey100 / gray0 .. gray100.
-- lookup(name) takes a lower-case name without spaces and returns R + G * 256 + B * 65536, or nil.
-- image/xpm/Names: CSS Color 4 named colours with X11's values where they differ, and grey0 .. grey100.
local Names = {}
local HEX: { [string]: number } = {
@@ -37,7 +35,6 @@ local HEX: { [string]: number } = {
violet = 0xEE82EE, wheat = 0xF5DEB3, white = 0xFFFFFF, whitesmoke = 0xF5F5F5, yellow = 0xFFFF00, yellowgreen = 0x9ACD32,
}
-- lookup(name) -> R + G * 256 + B * 65536 | nil (name: lower case, no spaces)
function Names.lookup(name: string): number?
local v = HEX[name]
if v then
+5 -11
View File
@@ -1,10 +1,7 @@
--!strict
-- image/xpm: X PixMap (XPM 3 C source and the XPM 2 plain form; the "XPM Manual" by Arnaud Le Hors; new code). Decode:
-- the values line (width, height, colours, chars per pixel, hotspot: meta.hotspot), colour lines with the c / g / g4 /
-- m / s keys (c preferred, then g, g4, m), #RGB / #RRGGBB / #RRRGGGBBB / #RRRRGGGGBBBB, None (transparent) and colour
-- names (image/xpm/Names: the CSS / X11 names and grey0..100; an unknown name is black and listed in
-- meta.unknownColours), the extensions section skipped. Encode: rgba8 as XPM 3 with hex colours, alpha < 128 as None,
-- the fewest chars per pixel; opts.name (default "image").
-- image/xpm: X PixMap (XPM 3 C source and XPM 2 plain; Arnaud Le Hors's "XPM Manual"). Supports: the values line and
-- hotspot, c / g / g4 / m / s keys (c preferred, then g, g4, m), #RGB .. #RRRRGGGGBBBB, None, colour names (unknown:
-- black); writes XPM 3 with hex colours. Not supported: the extensions section (skipped).
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
@@ -25,10 +22,10 @@ local Xpm = {
-- ------------------------------------------------------------------------------------------------ types
export type DecodeOptions = {
maxPixels: number?, -- refuse larger images (default 2^26)
maxPixels: number?, -- default 2^26
}
export type EncodeOptions = {
name: string?, -- the C identifier (default "image"; an extension is dropped, other characters become _)
name: string?, -- default "image"
}
-- the characters of pixel codes (printable ASCII without '"' and '\')
@@ -44,7 +41,6 @@ function Xpm.sniff(r: Bytes.Reader): number
end
-- ------------------------------------------------------------------------------------------------ decode
-- colour value -> rgba8 u32, or nil for an unknown name
local function colour(v: string): number?
local l = string.lower(v)
if l == "none" or l == "transparent" then
@@ -69,7 +65,6 @@ local function colour(v: string): number?
return if rgb then rgb + 0xFF000000 else nil
end
-- the strings of the file: C string literals (XPM 3) or plain lines (XPM 2)
local function strings(s: string): { string }
local out = {}
if string.sub(Sniff.dropBom(s), 1, 6) == "! XPM2" then
@@ -214,7 +209,6 @@ function Xpm.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?)
if w < 1 or h < 1 then
return nil, Err.new(Err.ARG, "bad size")
end
-- a C identifier from opts.name (F.save passes the file name: "out.xbm" -> out)
local name = string.gsub(string.gsub(opts and opts.name or "image", "%.[^.]*$", ""), "[^%w_]", "_")
if name == "" or string.match(name, "^%d") then
name = "_" .. name