Initial Commit

This commit is contained in:
SoraKatadzuma committed 2026-10-28 08:26:26 -05:00
commit f40701771e
69 files changed
+7703

No files matched your search

+271
View File
@@ -0,0 +1,271 @@
#! Contains how deflate writes its blocks: bits after one another, the first the
#! least significant, and each block of bytes and runs in whichever of
#! DEFLATE's three ways is shortest: stored as it is, by the fixed codes, or by
#! codes of its own, which it gives first.
module image::png;
# Writes bits after one another, the first the least significant, as DEFLATE
# packs them into bytes.
struct bit_writer {
var out: vector<u8>;
var buffer: u64;
var count: u64; #! How many bits the buffer holds, fewer than 8 between writes.
}
# Writes the lowest bits of a number.
def bit_writer::put(&mut this, bits: u32, size: u64): void {
this.buffer |= (bits as u64) << this.count;
this.count += size;
while this.count >= 8 {
this.out.append(this.buffer as u8);
this.buffer >>= 8;
this.count -= 8;
}
}
# Writes zeros up to the next whole byte.
def bit_writer::align(&mut this): void {
if this.count > 0 {
this.put(0, 8 - this.count);
}
}
# A block's bytes and runs, as deflate finds them: each a byte, by a length of
# 0, or a run of a length back a distance, and how often each symbol is used.
struct block {
var lengths: vector<u16>;
var values: vector<u16>; #! Each byte, or each run's distance.
var literals: u32[288]; #! How often each literal and length symbol is used.
var distances: u32[30];
var start: u64; #! Where the block's bytes begin in the data.
}
def block::new(): block {
return block { lengths = vector::<u16>::new(), values = vector::<u16>::new() };
}
# Empties the block, to hold what's found from a place on.
def block::reset(&mut this, start: u64): void {
this.lengths.clear();
this.values.clear();
for symbol in 0u..288u {
this.literals[symbol] = 0;
}
for symbol in 0u..30u {
this.distances[symbol] = 0;
}
this.start = start;
}
def block::byte(&mut this, value: u8): void {
this.lengths.append(0);
this.values.append(value as u16);
this.literals[value as u64]++;
}
def block::run(&mut this, length: u64, distance: u64): void {
this.lengths.append(length as u16);
this.values.append(distance as u16);
this.literals[257 + length_symbol[length] as u64]++;
this.distances[distance_symbol(distance)]++;
}
# The codes a block is written by, and their lengths.
struct codes {
var literal_lengths: u8[288];
var literal_codes: u16[288];
var distance_lengths: u8[30];
var distance_codes: u16[30];
}
# DEFLATE's fixed codes.
def codes::fixed(): codes {
var made := codes { literal_lengths = fixed_lengths() };
for symbol in 0u..30u {
made.distance_lengths[symbol] = 5;
}
codes_of(made.literal_lengths[:], made.literal_codes[:]);
codes_of(made.distance_lengths[:], made.distance_codes[:]);
return made;
}
# How many bits a block's symbols take in codes, without its header.
def codes::cost(&this, held: &block): u64 {
var bits: u64 = 0;
for symbol in 0u..286u {
bits += held.literals[symbol] as u64 * this.literal_lengths[symbol] as u64;
}
for symbol in 0u..30u {
bits += held.distances[symbol] as u64 * this.distance_lengths[symbol] as u64;
}
return bits;
}
# Writes a block of data, the last or not, in whichever way is shortest.
def bit_writer::block(&mut this, held: &mut block, data: span<u8>, end: u64, last: bool, fixed: &codes): void {
held.literals[256] = 1;
val bytes := data[held.start:end - held.start];
# The bits more of each run's length and distance, which any codes write.
var extra: u64 = 0;
for symbol in 0u..29u {
extra += held.literals[257 + symbol] as u64 * length_extra[symbol] as u64;
}
for symbol in 0u..30u {
extra += held.distances[symbol] as u64 * distance_extra[symbol] as u64;
}
# Codes of its own, and the lengths of them as the code of lengths gives them.
var own := codes {};
code_lengths(held.literals[0:286], 15, own.literal_lengths[0:286]);
code_lengths(held.distances[:], 15, own.distance_lengths[:]);
codes_of(own.literal_lengths[:], own.literal_codes[:]);
codes_of(own.distance_lengths[:], own.distance_codes[:]);
var literals: u64 = 286;
while literals > 257 && own.literal_lengths[literals - 1] == 0 {
literals--;
}
var distances: u64 = 30;
while distances > 1 && own.distance_lengths[distances - 1] == 0 {
distances--;
}
var all_lengths: u8[316];
for symbol in 0..literals {
all_lengths[symbol] = own.literal_lengths[symbol];
}
for symbol in 0..distances {
all_lengths[literals + symbol] = own.distance_lengths[symbol];
}
var runs := vector::<u8>::new();
var repeats := vector::<u8>::new();
var run_counts: u32[19];
run_lengths(all_lengths[0:literals + distances], &mut runs, &mut repeats, run_counts[:]);
var length_lengths: u8[19];
var length_codes: u16[19];
code_lengths(run_counts[:], 7, length_lengths[:]);
codes_of(length_lengths[:], length_codes[:]);
var told: u64 = 19;
while told > 4 && length_lengths[length_order[told - 1]] == 0 {
told--;
}
var own_bits: u64 = 3 + 14 + told * 3 + own.cost(held) + extra;
for symbol in 0u..19u {
own_bits += run_counts[symbol] as u64 * length_lengths[symbol] as u64;
}
own_bits += (run_counts[16] as u64) * 2 + (run_counts[17] as u64) * 3 + (run_counts[18] as u64) * 7;
val fixed_bits := 3 + fixed.cost(held) + extra;
val stored_bits := (bytes.length + 5 * ((bytes.length + 65534) / 65535 + 1)) * 8;
if stored_bits <= own_bits && stored_bits <= fixed_bits {
this.stored(bytes, last);
return;
}
this.put(last ? 1 : 0, 1);
if fixed_bits <= own_bits {
this.put(1, 2);
this.symbols(held, fixed);
return;
}
this.put(2, 2);
this.put((literals - 257) as u32, 5);
this.put((distances - 1) as u32, 5);
this.put((told - 4) as u32, 4);
for index in 0..told {
this.put(length_lengths[length_order[index]] as u32, 3);
}
for index in 0..runs.length {
val symbol := runs[index] as u64;
this.put(length_codes[symbol] as u32, length_lengths[symbol] as u64);
if symbol >= 16 {
this.put(repeats[index] as u32, symbol == 16 ? 2 : (symbol == 17 ? 3 : 7));
}
}
this.symbols(held, &own);
}
# Writes a block's bytes and runs by codes, then its end.
def bit_writer::symbols(&mut this, held: &block, by: &codes): void {
for index in 0..held.lengths.length {
val length := held.lengths[index] as u64;
val value := held.values[index] as u64;
if length == 0 {
this.put(by.literal_codes[value] as u32, by.literal_lengths[value] as u64);
continue;
}
val symbol := length_symbol[length] as u64;
this.put(by.literal_codes[257 + symbol] as u32, by.literal_lengths[257 + symbol] as u64);
this.put((length - length_base[symbol] as u64) as u32, length_extra[symbol] as u64);
val which := distance_symbol(value);
this.put(by.distance_codes[which] as u32, by.distance_lengths[which] as u64);
this.put((value - distance_base[which] as u64) as u32, distance_extra[which] as u64);
}
this.put(by.literal_codes[256] as u32, by.literal_lengths[256] as u64);
}
# Writes bytes as stored blocks, as many as hold them, the last of them the
# data's last block or not.
def bit_writer::stored(&mut this, bytes: span<u8>, last: bool): void {
var at: u64 = 0;
while true {
val size := bytes.length - at < 65535 ? bytes.length - at : 65535;
val final := last && at + size == bytes.length;
this.put(final ? 1 : 0, 1);
this.put(0, 2);
this.align();
this.put(size as u32, 16);
this.put((size ^ 0xFFFF) as u32, 16);
this.out.extend(bytes[at:size]);
at += size;
if at >= bytes.length {
break;
}
}
}
# The lengths of a dynamic block's codes as the code of lengths gives them: each
# length itself, or 16 repeating the last 3 to 6 times, or 17 and 18 giving 3 to
# 10 zeros, and 11 to 138, each with the count it adds bits for, counting how
# often each is used.
def run_lengths(lengths: span<u8>, runs: &mut vector<u8>, repeats: &mut vector<u8>, counts: slice<u32>): void {
var at: u64 = 0;
while at < lengths.length {
val length := lengths[at];
var run: u64 = 1;
while at + run < lengths.length && lengths[at + run] == length {
run++;
}
at += run;
if length == 0 {
while run >= 11 {
val taken := run < 138 ? run : 138;
add_run(runs, repeats, counts, 18, taken - 11);
run -= taken;
}
if run >= 3 {
add_run(runs, repeats, counts, 17, run - 3);
run = 0;
}
} else {
add_run(runs, repeats, counts, length, 0);
run--;
while run >= 3 {
val taken := run < 6 ? run : 6;
add_run(runs, repeats, counts, 16, taken - 3);
run -= taken;
}
}
while run > 0 {
add_run(runs, repeats, counts, length, 0);
run--;
}
}
}
def add_run(runs: &mut vector<u8>, repeats: &mut vector<u8>, counts: slice<u32>, symbol: u8, repeat: u64): void {
runs.append(symbol);
repeats.append(repeat as u8);
counts[symbol as u64]++;
}
+48
View File
@@ -0,0 +1,48 @@
#! Contains the checksums PNG's data is checked by: the CRC-32 that ends each
#! chunk, and the Adler-32 that ends zlib's data.
module image::png;
# The Adler-32 of bytes, as zlib checks them by.
def adler32(data: span<u8>): u32 {
var low: u32 = 1;
var high: u32 = 0;
var at: u64 = 0;
while at < data.length {
# 5552 bytes is the most that can be summed before either could pass 32 bits.
val end := at + 5552 < data.length ? at + 5552 : data.length;
while at < end {
low += data[at];
high += low;
at++;
}
low %= 65521;
high %= 65521;
}
return (high << 16) | low;
}
# The table CRC-32 is worked out by, a byte at a time.
def crc_table(): u32[256] {
var table: u32[256];
for index in 0u..256u {
var crc := index as u32;
for _ in 0..8 {
crc = (crc & 1) != 0 ? 0xEDB88320 ^ (crc >> 1) : crc >> 1;
}
table[index] = crc;
}
return table;
}
const crc_bytes: u32[256] = crc_table();
# The CRC-32 of bytes, as PNG checks each chunk by.
def crc32(data: span<u8>): u32 {
var crc: u32 = 0xFFFFFFFF;
for byte in data {
crc = crc_bytes[((crc ^ byte) & 0xFF) as u64] ^ (crc >> 8);
}
return crc ^ 0xFFFFFFFF;
}
+132
View File
@@ -0,0 +1,132 @@
#! Contains what colors an image holds, which choose the color type and depth
#! it's written in: whether every pixel is gray, whether every one is opaque,
#! the least depth its grays are exact at, and its colors, where there are no
#! more than a palette holds.
module image::png;
# How many places the table of colors has: four for each entry a palette may.
const color_slots: u64 = 1024;
# The colors of an image, up to a palette's 256, each an entry in the order
# they're added, found by its RGBA in a table.
struct colors {
var keys: u32[1024];
var slots: u16[1024]; #! Each place's entry, plus 1, or 0 where it's empty.
var entries: u32[256]; #! Each entry's RGBA, red the most significant.
var count: u32;
var full: bool; #! Whether more colors were seen than a palette holds.
}
# The RGBA of the pixel at a byte, red the most significant.
def key_of(pixels: span<u8>, at: u64): u32 {
return (pixels[at] as u32 << 24) | (pixels[at + 1] as u32 << 16) | (pixels[at + 2] as u32 << 8) | pixels[at + 3] as u32;
}
def slot_of(key: u32): u64 {
return ((key * 2654435761) >> 22) as u64;
}
# Adds a color, where it's new, and marks the colors full where there's no room.
def colors::add(&mut this, key: u32): void {
var slot := slot_of(key);
while this.slots[slot] != 0 {
if this.keys[slot] == key {
return;
}
slot = (slot + 1) % color_slots;
}
if this.count >= 256 {
this.full = true;
return;
}
this.keys[slot] = key;
this.slots[slot] = (this.count + 1) as u16;
this.entries[this.count as u64] = key;
this.count++;
}
# The entry of a color added.
def colors::entry_of(&this, key: u32): u32 {
var slot := slot_of(key);
while this.keys[slot] != key || this.slots[slot] == 0 {
slot = (slot + 1) % color_slots;
}
return this.slots[slot] as u32 - 1;
}
# The same colors, those with any alpha first, so `tRNS` needs name no others.
def colors::alpha_first(&this): colors {
var made := colors {};
for pass in 0u..2u {
for entry in 0..this.count as u64 {
val opaque := (this.entries[entry] & 0xFF) == 0xFF;
if opaque == (pass == 1) {
made.add(this.entries[entry]);
}
}
}
return made;
}
# The header an image is written with: where it's reduced, the least color type
# and depth that hold its pixels exactly, and its palette, where it has one,
# made of its colors; and otherwise RGBA of 8 bits.
def header_for(picture: &image, reduced: bool, found: &mut colors): header {
var head := header { width = picture.width, height = picture.height, depth = 8, color = rgba, channels = 4 };
if !reduced {
return head;
}
var is_gray := true;
var opaque := true;
var gray_depth: u32 = 1;
var seen := colors {};
val pixels := picture.pixels.view();
var at: u64 = 0;
while at < pixels.length {
val r := pixels[at];
if is_gray && (r != pixels[at + 1] || r != pixels[at + 2]) {
is_gray = false;
}
if is_gray && gray_depth < 8 {
val needs: u32 = r % 255 == 0 ? 1 : (r % 85 == 0 ? 2 : (r % 17 == 0 ? 4 : 8));
gray_depth = needs > gray_depth ? needs : gray_depth;
}
if pixels[at + 3] != 255 {
opaque = false;
}
if !seen.full {
seen.add(key_of(pixels, at));
}
at += 4;
}
# A palette's indices are as few bits as its entries need, which is fewer than
# any but gray's samples take.
val entries := seen.count;
val palette_depth: u32 = entries <= 2 ? 1 : (entries <= 4 ? 2 : (entries <= 16 ? 4 : 8));
if is_gray && opaque && (seen.full || palette_depth >= gray_depth) {
head.color = gray;
head.depth = gray_depth;
} else if !seen.full {
head.color = indexed;
head.depth = palette_depth;
found = seen.alpha_first();
head.entries = found.count;
for entry in 0..found.count as u64 {
val key := found.entries[entry];
head.palette[entry * 4] = (key >> 24) as u8;
head.palette[entry * 4 + 1] = (key >> 16) as u8;
head.palette[entry * 4 + 2] = (key >> 8) as u8;
head.palette[entry * 4 + 3] = key as u8;
}
} else if is_gray {
head.color = gray_alpha;
} else if opaque {
head.color = truecolor;
}
head.channels = channels_of(head.color);
return head;
}
+188
View File
@@ -0,0 +1,188 @@
#! Contains deflate, which compresses PNG's image data as DEFLATE, as RFC 1951
#! writes it, within zlib's wrapping, as RFC 1950 writes it: what repeats bytes
#! before it, as far back as 32 KiB, written as a run back to them, found by
#! chains of where each three bytes were seen, as zlib finds them, the longest
#! that a level looks far enough to find.
module image::png;
# How far back runs reach, and how short and long they may be.
const window: u64 = 32768;
const shortest: u64 = 3;
const longest: u64 = 258;
# How hard each level looks, from 1 to 9, as zlib's do: how many places back
# it looks for a run, and how long a run it takes without looking further. From
# 4, each also looks one byte on, where the run is shorter than the third, for
# a longer one, which it takes the byte alone before, as zlib's lazy matching
# does, looking a quarter as far where the run is as long as the fourth. Those
# below 4 note where each byte of a run was seen only where it's no longer than
# the third, as zlib's fast ones do.
const chain_lengths: u32[10] = [0, 4, 8, 32, 16, 32, 128, 256, 1024, 4096];
const nice_lengths: u32[10] = [0, 8, 16, 32, 16, 32, 128, 128, 258, 258];
const lazy_lengths: u32[10] = [0, 4, 5, 6, 4, 16, 16, 32, 128, 258];
const good_lengths: u32[10] = [0, 4, 4, 4, 4, 8, 8, 8, 32, 32];
# How many bytes and runs a block holds before it's written.
const block_symbols: u64 = 16384;
# How many bits the chains are found by, of the three bytes they begin with.
const hash_bits: u32 = 15;
# Finds the runs of data, and where each three bytes were seen before.
struct deflater {
var data: span<u8>;
var heads: vector<u32>; #! The last place, plus 1, each three bytes' hash was seen, or 0.
var links: vector<u32>; #! The place, plus 1, the same hash was seen before each in the window, or 0.
var chain: u32;
var nice: u64;
var limit: u64; #! The longest run looked past lazily, or each of whose bytes is noted.
var good: u64;
var lazy: bool;
}
# Compresses data as zlib's.
# @param data The data.
# @param level How hard to look for runs, from 0, storing the data as it is,
# to 9.
# @returns The data compressed, then its Adler-32.
def deflate(data: span<u8>, level: u32): vector<u8> {
val effort := level > 9 ? 9u : level as u64;
var out := bit_writer { out = vector::<u8>::new() };
out.out.reserve(data.length / 2 + 64);
# Deflate, of a 32 KiB window, and how hard it looked.
val method: u32 = 0x78;
var flags: u32 = (effort < 2 ? 0 : (effort < 6 ? 1 : (effort == 6 ? 2 : 3))) << 6;
flags += 31 - (method * 256 + flags) % 31;
out.put(method, 8);
out.put(flags, 8);
if effort == 0 {
out.stored(data, true);
} else {
var found := deflater {
data = data,
heads = vector::<u32>::new(),
links = vector::<u32>::new(),
chain = chain_lengths[effort],
nice = nice_lengths[effort] as u64,
limit = lazy_lengths[effort] as u64,
good = good_lengths[effort] as u64,
lazy = effort >= 4
};
found.heads.resize(1u << hash_bits as u64);
found.links.resize(window);
found.compress(&mut out);
}
out.align();
val check := adler32(data);
out.out.append((check >> 24) as u8);
out.out.append((check >> 16) as u8);
out.out.append((check >> 8) as u8);
out.out.append(check as u8);
return move(out.out);
}
# Finds the data's runs, and writes its blocks.
def deflater::compress(&mut this, out: &mut bit_writer): void {
val size := this.data.length;
val fixed := codes::fixed();
var held := block::new();
var at: u64 = 0;
var found: u64[2] = [0, 0];
var carried := false; # Whether the run at `at` was found already, looking past the byte before.
while at < size {
if held.lengths.length >= block_symbols {
out.block(&mut held, this.data, at, false, &fixed);
held.reset(at);
}
if !carried {
found = this.longest_at(at, this.chain);
}
carried = false;
this.insert(at);
if found[0] >= shortest && this.lazy && found[0] < this.limit && at + 1 < size {
val next := this.longest_at(at + 1, found[0] >= this.good ? this.chain / 4 : this.chain);
if next[0] > found[0] {
held.byte(this.data[at]);
at++;
found = next;
carried = true;
continue;
}
}
if found[0] < shortest {
held.byte(this.data[at]);
at++;
continue;
}
held.run(found[0], found[1]);
if this.lazy || found[0] <= this.limit {
for step in 1..found[0] {
this.insert(at + step);
}
}
at += found[0];
}
out.block(&mut held, this.data, size, true, &fixed);
}
# The longest run at a place that repeats bytes before it, within the window,
# looking so many places back: its length and distance, or a length less than
# 3 where there's none.
def deflater::longest_at(&this, at: u64, chain: u32): u64[2] {
val data := this.data;
val most := data.length - at < longest ? data.length - at : longest;
if most < shortest {
return [0, 0];
}
var best: u64 = shortest - 1;
var distance: u64 = 0;
val links := this.links.view();
var seen := this.heads[hash_at(data, at)] as u64;
var left := chain;
while seen != 0 && left > 0 {
val from := seen - 1;
if at - from > window {
break;
}
# One that differs where the best ends, just before, or where it begins,
# as another three bytes of the same hash do, is no longer, as zlib finds.
if data[from + best] == data[at + best] && data[from + best - 1] == data[at + best - 1]
&& data[from] == data[at] && data[from + 1] == data[at + 1] {
var length: u64 = 2;
while length < most && data[from + length] == data[at + length] {
length++;
}
if length > best {
best = length;
distance = at - from;
if length >= most || length >= this.nice {
break;
}
}
}
seen = links[from % window] as u64;
left--;
}
return [best, distance];
}
# Notes where the three bytes at a place were seen, where there are three.
def deflater::insert(&mut this, at: u64): void {
if at + shortest > this.data.length {
return;
}
val hash := hash_at(this.data, at);
this.links[at % window] = this.heads[hash];
this.heads[hash] = (at + 1) as u32;
}
# The hash of the three bytes at a place.
def hash_at(data: span<u8>, at: u64): u64 {
val key := (data[at] as u32) | (data[at + 1] as u32 << 8) | (data[at + 2] as u32 << 16);
return ((key * 2654435761) >> (32 - hash_bits)) as u64;
}
+117
View File
@@ -0,0 +1,117 @@
#! Contains PNG's encoder, which writes an image's pixels exactly, in the least
#! color type and depth that holds them: gray of 1, 2, 4, or 8 bits; gray with
#! alpha; RGB; RGBA; or a palette of up to 256 colors, of 1, 2, 4, or 8 bits.
#! Each row is filtered by whichever of PNG's filters leaves the least to
#! compress, as libpng chooses, and the rows deflated, after an `sRGB` chunk
#! saying the colors are sRGB's.
module image::png;
#! How a PNG is written.
pub struct options {
pub var level: u32 = 6; #! How hard deflate looks for repeats: from 0, which stores the data as it is, to 9.
pub var reduced: bool = true; #! Whether the least color type and depth holding the pixels is written, or RGBA of 8 bits whatever they are.
pub var interlaced: bool = false; #! Whether it's written in Adam7's seven passes, which a reader may show coarse, then finer.
}
#! Writes a PNG.
#! @param picture The image.
#! @param given How to write it.
#! @returns The file's bytes, or `malformed` where the image has no pixels, or
#! other than `width * height * 4` bytes of them.
pub def encode(picture: &image, given: options = options {}): result<vector<u8>, image_error> {
if !image::is_whole(picture) {
return image_error::malformed;
}
if picture.width > 0x7FFFFFFF || picture.height > 0x7FFFFFFF {
return image_error::too_large;
}
var found := colors {};
var head := header_for(picture, given.reduced, &mut found);
head.interlaced = given.interlaced;
# Each pass's rows, each its filter's byte then it, after the last pass's; one
# pass where it's not interlaced.
var raw := vector::<u8>::new();
raw.reserve(inflated_size(&head));
val step := bytes_per_pixel(&head);
val chosen := head.color != indexed && head.depth == 8;
var line := vector::<u8>::new();
var above := vector::<u8>::new();
for pass in 0u..7u {
val x0 := head.interlaced ? pass_x[pass] : 0;
val y0 := head.interlaced ? pass_y[pass] : 0;
val dx := head.interlaced ? pass_dx[pass] : 1;
val dy := head.interlaced ? pass_dy[pass] : 1;
val columns := head.width > x0 ? (head.width - x0 + dx - 1) / dx : 0;
val rows := head.height > y0 ? (head.height - y0 + dy - 1) / dy : 0;
if columns != 0 && rows != 0 {
val row_bytes := row_size(&head, columns);
line.resize(row_bytes);
above.clear();
above.resize(row_bytes);
for row in 0..rows as u64 {
take_row(&head, picture, &found, y0 + row as u32 * dy, x0, dx, columns, line.slice());
filter_row(line.view(), above.view(), step, chosen, &mut raw);
for index in 0..row_bytes {
above[index] = line[index];
}
}
}
if !head.interlaced {
break;
}
}
var out := vector::<u8>::new();
out.extend(signature[:]);
var described: u8[13];
put_big_endian(described[:], 0, head.width);
put_big_endian(described[:], 4, head.height);
described[8] = head.depth as u8;
described[9] = head.color;
described[12] = head.interlaced ? 1 : 0;
chunk(&mut out, "IHDR", described[:]);
# Its colors are sRGB's, as a renderer means them perceptually.
var intent: u8[1];
chunk(&mut out, "sRGB", intent[:]);
if head.color == indexed {
var colors_of := vector::<u8>::new();
var alphas := vector::<u8>::new();
for entry in 0..head.entries as u64 {
colors_of.extend(head.palette[entry * 4:3]);
if head.palette[entry * 4 + 3] != 255 {
alphas.append(head.palette[entry * 4 + 3]);
}
}
chunk(&mut out, "PLTE", colors_of.view());
if !alphas.is_empty {
chunk(&mut out, "tRNS", alphas.view());
}
}
val compressed := deflate(raw.view(), given.level);
chunk(&mut out, "IDAT", compressed.view());
chunk(&mut out, "IEND", described[0:0]);
return move(out);
}
# Appends a chunk: its length, its type, its data, and the CRC of the last two.
def chunk(out: &mut vector<u8>, kind: strview, data: span<u8>): void {
val start := out.length;
out.resize(start + 4);
put_big_endian(out.slice(), start, data.length as u32);
out.extend(kind);
out.extend(data);
val crc := crc32(out.view()[start + 4:4 + data.length]);
val end := out.length;
out.resize(end + 4);
put_big_endian(out.slice(), end, crc);
}
def put_big_endian(bytes: slice<u8>, at: u64, value: u32): void {
bytes[at] = (value >> 24) as u8;
bytes[at + 1] = (value >> 16) as u8;
bytes[at + 2] = (value >> 8) as u8;
bytes[at + 3] = value as u8;
}
+108
View File
@@ -0,0 +1,108 @@
#! Contains PNG's filters, which write each byte of a row as what it differs by
#! from a guess at it, of the bytes to its left and above: undone as a row is
#! read, and chosen as one is written.
module image::png;
# Undoes each row's filter, in place, from the one above it.
def unfilter(raw: slice<u8>, start: u64, rows: u64, row_bytes: u64, step: u64): bool {
for row in 0..rows {
val line := start + row * (row_bytes + 1);
val at := line + 1;
val above := line - row_bytes; # The row above's first byte, where there is one.
match raw[line] {
0 => {}
1 => {
for index in step..row_bytes {
raw[at + index] = raw[at + index] + raw[at + index - step];
}
}
2 => {
if row > 0 {
for index in 0..row_bytes {
raw[at + index] = raw[at + index] + raw[above + index];
}
}
}
3 => {
for index in 0..row_bytes {
val left: u32 = index >= step ? raw[at + index - step] as u32 : 0;
val up: u32 = row > 0 ? raw[above + index] as u32 : 0;
raw[at + index] = raw[at + index] + ((left + up) / 2) as u8;
}
}
4 => {
for index in 0..row_bytes {
val left: i32 = index >= step ? raw[at + index - step] as i32 : 0;
val up: i32 = row > 0 ? raw[above + index] as i32 : 0;
val corner: i32 = index >= step && row > 0 ? raw[above + index - step] as i32 : 0;
raw[at + index] = raw[at + index] + paeth(left, up, corner);
}
}
else => return false;
}
}
return true;
}
# Paeth's predictor: whichever of the left, upper, and upper left bytes is
# nearest what the first two less the third makes.
def paeth(left: i32, up: i32, corner: i32): u8 {
val guess := left + up - corner;
val to_left := guess > left ? guess - left : left - guess;
val to_up := guess > up ? guess - up : up - guess;
val to_corner := guess > corner ? guess - corner : corner - guess;
if to_left <= to_up && to_left <= to_corner {
return left as u8;
}
return to_up <= to_corner ? up as u8 : corner as u8;
}
# Appends a row, filtered, after its filter's byte, from the row above it, which
# is zeros above a pass's first. Where it's chosen, the filter is whichever
# leaves the least, by the sum of its bytes taken as signed, as libpng chooses;
# otherwise none, as libpng leaves rows of palette indices and of samples less
# than a byte.
def filter_row(line: span<u8>, above: span<u8>, step: u64, chosen: bool, into: &mut vector<u8>): void {
var best: u8 = 0;
if chosen {
var costs: u64[5];
for index in 0..line.length {
val byte := line[index];
val left: u8 = index >= step ? line[index - step] : 0;
val up := above[index];
val corner: u8 = index >= step ? above[index - step] : 0;
costs[0] += magnitude(byte);
costs[1] += magnitude(byte - left);
costs[2] += magnitude(byte - up);
costs[3] += magnitude(byte - ((left as u32 + up as u32) / 2) as u8);
costs[4] += magnitude(byte - paeth(left as i32, up as i32, corner as i32));
}
for kind in 1u..5u {
if costs[kind] < costs[best as u64] {
best = kind as u8;
}
}
}
into.append(best);
for index in 0..line.length {
val byte := line[index];
val left: u8 = index >= step ? line[index - step] : 0;
val up := above[index];
val guess: u8 = match best {
0 => 0,
1 => left,
2 => up,
3 => ((left as u32 + up as u32) / 2) as u8,
else => paeth(left as i32, up as i32, index >= step ? above[index - step] as i32 : 0),
};
into.append(byte - guess);
}
}
# How far a byte taken as signed is from zero.
def magnitude(byte: u8): u64 {
return byte < 128 ? byte as u64 : 256 - byte as u64;
}
+105
View File
@@ -0,0 +1,105 @@
#! Contains PNG's header, and the chunks that say what its pixels' samples are:
#! `IHDR`, `PLTE`, and `tRNS`.
module image::png;
# What `IHDR` says, and what the chunks after it give.
struct header {
var width: u32;
var height: u32;
var depth: u32; #! Bits a sample.
var color: u8;
var interlaced: bool;
var channels: u32; #! Samples a pixel.
var palette: u8[1024]; #! Each entry's RGBA.
var entries: u32;
var keyed: bool; #! Whether `tRNS` names a gray or RGB that is clear.
var key: u32[3]; #! The samples of that color, at the image's depth.
}
# Reads `IHDR`, checking the depth is one the color type allows.
def read_header(body: span<u8>): result<header, image_error> {
if body.length != 13 {
return image_error::malformed;
}
var head := header {
width = big_endian(body, 0),
height = big_endian(body, 4),
depth = body[8] as u32,
color = body[9],
interlaced = body[12] == 1
};
if head.width == 0 || head.height == 0 || head.width > 0x7FFFFFFF || head.height > 0x7FFFFFFF
|| body[10] != 0 || body[11] != 0 || body[12] > 1 {
return image_error::malformed;
}
val depth := head.depth;
val allowed := match head.color {
0 => depth == 1 || depth == 2 || depth == 4 || depth == 8 || depth == 16,
3 => depth == 1 || depth == 2 || depth == 4 || depth == 8,
2, 4, 6 => depth == 8 || depth == 16,
else => false,
};
if !allowed {
return image_error::malformed;
}
head.channels = channels_of(head.color);
if (head.width as u64) * (head.height as u64) > image::max_pixels {
return image_error::too_large;
}
return head;
}
# How many samples a pixel of a color type has.
def channels_of(color: u8): u32 {
return match color { 0 => 1, 2 => 3, 3 => 1, 4 => 2, else => 4 };
}
# Reads `PLTE`, which only paletted images need, and the others may give as a
# suggestion, which is left.
def read_palette(head: &mut header, body: span<u8>): bool {
if head.color == gray || head.color == gray_alpha || body.length % 3 != 0 || body.length == 0 || body.length > 768 {
return false;
}
if head.color != indexed {
return true;
}
head.entries = (body.length / 3) as u32;
for entry in 0..head.entries as u64 {
head.palette[entry * 4] = body[entry * 3];
head.palette[entry * 4 + 1] = body[entry * 3 + 1];
head.palette[entry * 4 + 2] = body[entry * 3 + 2];
head.palette[entry * 4 + 3] = 255;
}
return true;
}
# Reads `tRNS`: the alpha of each palette entry it names, or the one gray or RGB
# that is clear.
def read_transparency(head: &mut header, body: span<u8>): bool {
if head.color == indexed {
if body.length > head.entries as u64 {
return false;
}
for entry in 0..body.length {
head.palette[entry * 4 + 3] = body[entry];
}
return true;
}
if head.color == gray && body.length == 2 {
head.keyed = true;
head.key[0] = big_endian16(body, 0);
return true;
}
if head.color == truecolor && body.length == 6 {
head.keyed = true;
for channel in 0u..3u {
head.key[channel] = big_endian16(body, channel * 2);
}
return true;
}
# Alpha a pixel has already makes it no use.
return head.color == gray_alpha || head.color == rgba;
}
+231
View File
@@ -0,0 +1,231 @@
#! Contains DEFLATE's Huffman codes: the tables inflate decodes symbols by, read
#! as stb_image reads them, by a table of codes up to 9 bits long and longer ones
#! by where each length's codes end; and the codes deflate gives symbols, by how
#! often each is used, no longer than a limit, as miniz makes them.
module image::png;
# How many bits the fast table reads at once.
const fast_bits: u64 = 9;
# A Huffman code: each symbol's code, as the lengths of all of them give it.
struct huffman {
var fast: u16[512]; #! `length << 9 | symbol` by a code's first 9 bits, read reversed, or 0 for a longer one.
var first_code: u32[16];
var first_symbol: u32[16];
var max_code: u32[17]; #! Just past the last code of each length, shifted to be 16 bits long.
var size: u8[288];
var value: u16[288];
}
# Builds a code from each symbol's length, which may leave codes unused, but not
# give more than there are.
def huffman::build(&mut this, lengths: span<u8>): bool {
var counts: u32[17];
for length in lengths {
counts[length as u64]++;
}
counts[0] = 0;
for bits in 1u..16u {
if counts[bits] as u64 > (1u << bits) {
return false;
}
}
var next: u32[16];
var code: u32 = 0;
var symbols: u32 = 0;
for bits in 1u..16u {
next[bits] = code;
this.first_code[bits] = code;
this.first_symbol[bits] = symbols;
code += counts[bits];
if counts[bits] != 0 && (code - 1) as u64 >= (1u << bits) {
return false;
}
this.max_code[bits] = code << (16 - bits) as u32;
code <<= 1;
symbols += counts[bits];
}
this.max_code[16] = 0x10000;
for symbol, length in lengths {
if length == 0 {
continue;
}
val bits := length as u64;
val slot := (next[bits] - this.first_code[bits] + this.first_symbol[bits]) as u64;
this.size[slot] = length;
this.value[slot] = symbol as u16;
if bits <= fast_bits {
var at := reverse(next[bits], bits) as u64;
while at < 512 {
this.fast[at] = ((bits << 9) | symbol) as u16;
at += 1u << bits;
}
}
next[bits]++;
}
return true;
}
# A symbol deflate gives a code, and how often it's used, which becomes the
# length of its code.
struct leaf {
var symbol: u64;
var weight: u64;
}
# The lengths of a code for symbols, by how often each is used, none longer than
# a limit: Huffman's, found by Moffat and Katajainen's method in place, then
# those too long shortened and others lengthened to make room, as miniz does. A
# symbol never used has none, but two at least have one, so the code is
# complete and each symbol of it a bit long at least.
def code_lengths(counts: span<u32>, limit: u64, lengths: slice<u8>): void {
var leaves := vector::<leaf>::new();
for symbol in 0..counts.length {
lengths[symbol] = 0;
if counts[symbol] != 0 {
leaves.append(leaf { symbol = symbol, weight = counts[symbol] as u64 });
}
}
var extra: u64 = 0;
while leaves.length < 2 {
if counts[extra] == 0 {
leaves.append(leaf { symbol = extra, weight = 1 });
}
extra++;
}
leaves.sort_by(def(a: &leaf, b: &leaf): bool => a.weight < b.weight || (a.weight == b.weight && a.symbol < b.symbol));
# Each leaf's weight, then each node's parent, then each leaf's depth.
val n := leaves.length;
var a := vector::<u64>::new();
for held in leaves {
a.append(held.weight);
}
a[0] += a[1];
var root: u64 = 0;
var next_leaf: u64 = 2;
for next in 1..n - 1 {
if next_leaf >= n || a[root] < a[next_leaf] {
a[next] = a[root];
a[root] = next;
root++;
} else {
a[next] = a[next_leaf];
next_leaf++;
}
if next_leaf >= n || (root < next && a[root] < a[next_leaf]) {
a[next] += a[root];
a[root] = next;
root++;
} else {
a[next] += a[next_leaf];
next_leaf++;
}
}
a[n - 2] = 0;
var node := n as i64 - 3;
while node >= 0 {
a[node as u64] = a[a[node as u64]] + 1;
node--;
}
var available: u64 = 1;
var used: u64 = 0;
var depth: u64 = 0;
var parent := n as i64 - 2;
var filling := n as i64 - 1;
while available > 0 {
while parent >= 0 && a[parent as u64] == depth {
used++;
parent--;
}
while available > used {
a[filling as u64] = depth;
filling--;
available--;
}
available = 2 * used;
depth++;
used = 0;
}
# How many codes of each length, those longer than the limit at it, then
# moved until the code fits: a code taken from the longest, and one shorter
# split into two a bit longer, until there are no more than room for.
var of_length: u64[17];
for depth_of in a {
of_length[depth_of < limit ? depth_of : limit]++;
}
var total: u64 = 0;
for bits in 1..=limit {
total += of_length[bits] << (limit - bits);
}
while total > (1u << limit) {
of_length[limit]--;
var bits := limit - 1;
while bits > 0 {
if of_length[bits] != 0 {
of_length[bits]--;
of_length[bits + 1] += 2;
break;
}
bits--;
}
total--;
}
# The shortest codes to those used most, which sort last.
var taken := n;
for bits in 1..=limit {
for _ in 0..of_length[bits] {
taken--;
lengths[leaves[taken].symbol] = bits as u8;
}
}
}
# The codes of each symbol's length, as DEFLATE gives them: those of each length
# in the order of their symbols, after all those shorter, each reversed, as
# DEFLATE writes a code's first bit as the least significant.
def codes_of(lengths: span<u8>, codes: slice<u16>): void {
var counts: u32[16];
for length in lengths {
counts[length as u64]++;
}
counts[0] = 0;
var next: u32[16];
var code: u32 = 0;
for bits in 1u..16u {
code = (code + counts[bits - 1]) << 1;
next[bits] = code;
}
for symbol, length in lengths {
if length != 0 {
codes[symbol] = reverse(next[length as u64], length as u64) as u16;
next[length as u64]++;
}
}
}
# The lowest bits of a number, in the opposite order.
def reverse(code: u32, bits: u64): u32 {
var from := code;
var made: u32 = 0;
for _ in 0..bits {
made = (made << 1) | (from & 1);
from >>= 1;
}
return made;
}
# The 16 lowest bits of a number, in the opposite order.
def reverse16(code: u32): u32 {
var made := code;
made = ((made & 0xAAAA) >> 1) | ((made & 0x5555) << 1);
made = ((made & 0xCCCC) >> 2) | ((made & 0x3333) << 2);
made = ((made & 0xF0F0) >> 4) | ((made & 0x0F0F) << 4);
return ((made & 0xFF00) >> 8) | ((made & 0x00FF) << 8);
}
+286
View File
@@ -0,0 +1,286 @@
#! Contains inflate, which undoes the compression of PNG's image data: DEFLATE, as
#! RFC 1951 writes it, within zlib's wrapping, as RFC 1950 writes it, by the
#! codes `huffman.sakura` reads.
module image::png;
# Reads DEFLATE's bits, least significant first, into the bytes made.
struct inflater {
var data: span<u8>;
var at: u64; #! The next byte to read, which runs past the end where bits read past it.
var buffer: u64;
var count: u64; #! How many bits the buffer holds.
var out: slice<u8>;
var written: u64;
}
# Inflates zlib's data into memory exactly as long as it should be, which it must
# not go past, checking its Adler-32.
# @returns How many bytes it inflated to, or `nothing` where it's broken.
def inflate(data: span<u8>, out: slice<u8>): maybe<u64> {
if data.length < 6 {
return nothing {};
}
val method := data[0];
val flags := data[1];
if (method & 0x0F) != 8 || (method >> 4) > 7 || (flags & 0x20) != 0 || ((method as u32) * 256 + flags as u32) % 31 != 0 {
return nothing {};
}
var z := inflater { data = data, at = 2, out = out };
var last := false;
while !last {
last = z.take(1) == 1;
val kind := z.take(2);
var read := false;
if kind == 0 {
read = z.stored();
} else if kind == 1 {
read = z.fixed();
} else if kind == 2 {
read = z.dynamic();
}
if !read || z.overran() {
return nothing {};
}
}
# The checksum is in the next whole bytes, the most significant first.
z.align();
var expected: u32 = 0;
for _ in 0..4 {
expected = (expected << 8) | z.take(8);
}
if z.overran() || adler32(z.out[0:z.written]) != expected {
return nothing {};
}
return z.written;
}
# Copies a stored block, whose length follows from the next whole byte.
def inflater::stored(&mut this): bool {
this.align();
val length := this.take(16);
if (length ^ 0xFFFF) != this.take(16) {
return false;
}
# What the buffer holds first, then the rest straight from the data.
var left := length as u64;
while left > 0 && this.count > 0 {
if !this.put(this.take(8) as u8) {
return false;
}
left--;
}
if this.at + left > this.data.length || this.written + left > this.out.length {
return false;
}
for index in 0..left {
this.out[this.written + index] = this.data[this.at + index];
}
this.at += left;
this.written += left;
return true;
}
# Inflates a block of the fixed codes RFC 1951 gives.
def inflater::fixed(&mut this): bool {
val lengths := fixed_lengths();
var distances: u8[30];
for symbol in 0u..30u {
distances[symbol] = 5;
}
var literal_code := huffman {};
var distance_code := huffman {};
_ = literal_code.build(lengths[:]);
_ = distance_code.build(distances[:]);
return this.codes(&literal_code, &distance_code);
}
# The lengths of the fixed codes of literals and lengths RFC 1951 gives.
def fixed_lengths(): u8[288] {
var lengths: u8[288];
for symbol in 0u..288u {
lengths[symbol] = symbol < 144 ? 8 : (symbol < 256 ? 9 : (symbol < 280 ? 7 : 8));
}
return lengths;
}
# Inflates a block of codes of its own, whose lengths it gives first, in a code of
# their own.
def inflater::dynamic(&mut this): bool {
val literals := this.take(5) as u64 + 257;
val distances := this.take(5) as u64 + 1;
val count := this.take(4) as u64 + 4;
var length_lengths: u8[19];
for index in 0..count {
length_lengths[length_order[index]] = this.take(3) as u8;
}
var length_code := huffman {};
if !length_code.build(length_lengths[:]) {
return false;
}
# The lengths, where 16 repeats the last, and 17 and 18 give runs of zeros.
var lengths: u8[320];
val total := literals + distances;
var read: u64 = 0;
while read < total {
val symbol := this.decode(&length_code);
if symbol < 0 {
return false;
}
var length: u8 = 0;
var repeat: u64 = 1;
if symbol < 16 {
length = symbol as u8;
} else if symbol == 16 {
if read == 0 {
return false;
}
length = lengths[read - 1];
repeat = 3 + this.take(2) as u64;
} else if symbol == 17 {
repeat = 3 + this.take(3) as u64;
} else {
repeat = 11 + this.take(7) as u64;
}
if read + repeat > total {
return false;
}
for _ in 0..repeat {
lengths[read] = length;
read++;
}
}
if lengths[256] == 0 {
return false;
}
var literal_code := huffman {};
var distance_code := huffman {};
if !literal_code.build(lengths[0:literals]) || !distance_code.build(lengths[literals:distances]) {
return false;
}
return this.codes(&literal_code, &distance_code);
}
# Inflates a block's symbols: bytes, then runs of what came before, to its end.
def inflater::codes(&mut this, literals: &huffman, distances: &huffman): bool {
while true {
val symbol := this.decode(literals);
if symbol < 0 {
return false;
}
if symbol < 256 {
if !this.put(symbol as u8) {
return false;
}
continue;
}
if symbol == 256 {
return true;
}
val index := (symbol - 257) as u64;
if index >= 29 {
return false;
}
val length := (length_base[index] + this.take(length_extra[index] as u64)) as u64;
val which := this.decode(distances);
if which < 0 || which >= 30 {
return false;
}
val distance := (distance_base[which as u64] + this.take(distance_extra[which as u64] as u64)) as u64;
if distance > this.written || this.written + length > this.out.length || this.overran() {
return false;
}
# A run may overlap itself, repeating what it copies, so it goes a byte at a time.
var from := this.written - distance;
for _ in 0..length {
this.out[this.written] = this.out[from];
this.written++;
from++;
}
}
return true;
}
# Decodes a symbol of a code.
# @returns The symbol, or -1 where the bits are no code's.
def inflater::decode(&mut this, code: &huffman): i32 {
if this.count < 16 {
this.fill();
}
val entry := code.fast[this.buffer & 511];
if entry != 0 {
val length := (entry >> 9) as u64;
this.buffer >>= length;
this.count -= length;
return (entry & 511) as i32;
}
# Longer than the table reads: the code's length is the first whose codes end
# past the bits, read most significant first.
val bits := reverse16((this.buffer & 0xFFFF) as u32);
var length: u64 = fast_bits + 1;
while bits >= code.max_code[length] {
length++;
}
if length >= 16 {
return -1;
}
val slot := ((bits >> (16 - length) as u32) - code.first_code[length] + code.first_symbol[length]) as u64;
if slot >= 288 || code.size[slot] as u64 != length {
return -1;
}
this.buffer >>= length;
this.count -= length;
return code.value[slot] as i32;
}
# Reads a number of bits, up to 16, the first the least significant.
def inflater::take(&mut this, bits: u64): u32 {
if this.count < bits {
this.fill();
}
val made := (this.buffer & ((1u << bits) - 1)) as u32;
this.buffer >>= bits;
this.count -= bits;
return made;
}
# Fills the buffer, with zeros past the end of the data, which `overran` tells.
def inflater::fill(&mut this): void {
while this.count <= 56 {
if this.at < this.data.length {
this.buffer |= (this.data[this.at] as u64) << this.count;
}
this.at++;
this.count += 8;
}
}
# Drops the bits up to the next whole byte.
def inflater::align(&mut this): void {
val extra := this.count % 8;
this.buffer >>= extra;
this.count -= extra;
}
# Whether more bits have been read than the data holds.
def inflater::overran(&this): bool {
return this.at * 8 - this.count > this.data.length * 8;
}
def inflater::put(&mut this, byte: u8): bool {
if this.written >= this.out.length {
return false;
}
this.out[this.written] = byte;
this.written++;
return true;
}
+177
View File
@@ -0,0 +1,177 @@
#! Contains PNG's rows and the pixels they hold: a row's samples made RGBA as
#! it's read, an image's pixels made a row's samples as it's written, and how
#! many bytes rows take.
module image::png;
# Writes a row's pixels into the image as RGBA, from the column it begins at, so
# far apart.
# @returns Whether every palette index is one the palette has.
def put_row(head: &header, line: span<u8>, made: &mut image, y: u32, x0: u32, dx: u32, columns: u32): bool {
val depth := head.depth;
var out := ((y as u64) * (made.width as u64) + (x0 as u64)) * 4;
val step := (dx as u64) * 4;
for column in 0..columns as u64 {
var r: u32 = 0;
var g: u32 = 0;
var b: u32 = 0;
var a: u32 = 255;
match head.color {
0 => {
val value := sample(line, column, depth);
r = scaled(value, depth);
g = r;
b = r;
if head.keyed && value == head.key[0] {
a = 0;
}
}
2 => {
val sr := sample(line, column * 3, depth);
val sg := sample(line, column * 3 + 1, depth);
val sb := sample(line, column * 3 + 2, depth);
r = scaled(sr, depth);
g = scaled(sg, depth);
b = scaled(sb, depth);
if head.keyed && sr == head.key[0] && sg == head.key[1] && sb == head.key[2] {
a = 0;
}
}
3 => {
val entry := sample(line, column, depth) as u64;
if entry >= head.entries as u64 {
return false;
}
r = head.palette[entry * 4] as u32;
g = head.palette[entry * 4 + 1] as u32;
b = head.palette[entry * 4 + 2] as u32;
a = head.palette[entry * 4 + 3] as u32;
}
4 => {
r = scaled(sample(line, column * 2, depth), depth);
g = r;
b = r;
a = scaled(sample(line, column * 2 + 1, depth), depth);
}
else => {
r = scaled(sample(line, column * 4, depth), depth);
g = scaled(sample(line, column * 4 + 1, depth), depth);
b = scaled(sample(line, column * 4 + 2, depth), depth);
a = scaled(sample(line, column * 4 + 3, depth), depth);
}
}
made.pixels[out] = r as u8;
made.pixels[out + 1] = g as u8;
made.pixels[out + 2] = b as u8;
made.pixels[out + 3] = a as u8;
out += step;
}
return true;
}
# The sample at an index of a row, packed from the most significant bit where it
# is less than a byte.
def sample(line: span<u8>, index: u64, depth: u32): u32 {
if depth == 8 {
return line[index] as u32;
}
if depth == 16 {
return (line[index * 2] as u32 << 8) | line[index * 2 + 1] as u32;
}
val bit := index * depth as u64;
val shift := (8 - depth as u64 - bit % 8) as u32;
return ((line[bit / 8] as u32) >> shift) & ((1 << depth) - 1);
}
# A sample of a depth, as eight bits: those less spread over all 255, and 16 rounded.
def scaled(value: u32, depth: u32): u32 {
return match depth {
1 => value * 255,
2 => value * 85,
4 => value * 17,
8 => value,
else => (value * 255 + 32767) / 65535,
};
}
# Writes a row's samples from the image's pixels, from the column it begins at,
# so far apart, at the header's color type and depth, which hold them exactly,
# each palette index found among the colors the palette was made of.
def take_row(head: &header, picture: &image, found: &colors, y: u32, x0: u32, dx: u32, columns: u32, line: slice<u8>): void {
val depth := head.depth;
if depth < 8 {
for index in 0..line.length {
line[index] = 0;
}
}
val pixels := picture.pixels.view();
var at := ((y as u64) * (picture.width as u64) + (x0 as u64)) * 4;
val step := (dx as u64) * 4;
var out: u64 = 0;
for column in 0..columns as u64 {
match head.color {
0 => put_sample(line, column, depth, pixels[at] as u32 / (255 / ((1 << depth) - 1)));
2 => {
line[out] = pixels[at];
line[out + 1] = pixels[at + 1];
line[out + 2] = pixels[at + 2];
out += 3;
}
3 => put_sample(line, column, depth, found.entry_of(key_of(pixels, at)));
4 => {
line[out] = pixels[at];
line[out + 1] = pixels[at + 3];
out += 2;
}
else => {
line[out] = pixels[at];
line[out + 1] = pixels[at + 1];
line[out + 2] = pixels[at + 2];
line[out + 3] = pixels[at + 3];
out += 4;
}
}
at += step;
}
}
# Sets the sample at an index of a row, packed from the most significant bit
# where it is less than a byte, whose bits are clear before.
def put_sample(line: slice<u8>, index: u64, depth: u32, value: u32): void {
if depth == 8 {
line[index] = value as u8;
return;
}
val bit := index * depth as u64;
val shift := (8 - depth as u64 - bit % 8) as u32;
line[bit / 8] = line[bit / 8] | (value << shift) as u8;
}
# How many bytes a row of so many pixels takes, without its filter's.
def row_size(head: &header, columns: u32): u64 {
return ((columns as u64) * (head.channels as u64) * (head.depth as u64) + 7) / 8;
}
# How many bytes back the byte of the pixel before is, which is 1 for those
# smaller than a byte.
def bytes_per_pixel(head: &header): u64 {
val bits := (head.channels as u64) * (head.depth as u64);
return bits < 8 ? 1 : bits / 8;
}
# How long the image's data is inflated: each pass's rows, each with its filter.
def inflated_size(head: &header): u64 {
if !head.interlaced {
return (head.height as u64) * (row_size(head, head.width) + 1);
}
var total: u64 = 0;
for pass in 0u..7u {
val columns := head.width > pass_x[pass] ? (head.width - pass_x[pass] + pass_dx[pass] - 1) / pass_dx[pass] : 0;
val rows := head.height > pass_y[pass] ? (head.height - pass_y[pass] + pass_dy[pass] - 1) / pass_dy[pass] : 0;
if columns != 0 && rows != 0 {
total += (rows as u64) * (row_size(head, columns) + 1);
}
}
return total;
}
+136
View File
@@ -0,0 +1,136 @@
#! Contains PNG's chunks read, which the rest of PNG's module makes an image of.
#!
#! Every image PNG writes is read, as its second edition says: gray, gray with
#! alpha, RGB, RGBA, and paletted, of every bit depth, interlaced or not, with
#! transparency from `tRNS`. Sixteen-bit samples are rounded to eight. Ancillary
#! chunks are skipped, so color is taken as sRGB whatever `gAMA`, `cHRM`, or
#! `iCCP` say; an animated PNG gives its default image.
#!
#! An image is written with every pixel kept exactly, in the least color type
#! and depth that holds them, as `encode.sakura` says.
module image::png;
# The color types, which say what each pixel's samples are.
const gray: u8 = 0;
const truecolor: u8 = 2;
const indexed: u8 = 3;
const gray_alpha: u8 = 4;
const rgba: u8 = 6;
# Where each of Adam7's seven passes begins, and how far apart its pixels are.
const pass_x: u32[7] = [0, 4, 0, 2, 0, 1, 0];
const pass_y: u32[7] = [0, 0, 4, 0, 2, 0, 1];
const pass_dx: u32[7] = [8, 8, 4, 4, 2, 2, 1];
const pass_dy: u32[7] = [8, 8, 8, 4, 4, 2, 2];
# The bytes every PNG begins with.
const signature: u8[8] = [0x89, 'P', 'N', 'G', 0x0D, 0x0A, 0x1A, 0x0A];
#! Reads a PNG.
#! @param bytes The file's bytes.
#! @returns The image, or `unrecognized` where the bytes don't begin with PNG's
#! signature, `malformed` where a chunk is broken or its CRC wrong,
#! `unsupported` where a chunk the image needs is one PNG doesn't
#! define, and `too_large` where it has too many pixels.
pub def decode(bytes: span<u8>): result<image, image_error> {
val found := image::format_of(bytes) else { return image_error::unrecognized; };
if found != format::png {
return image_error::unrecognized;
}
var head := header {};
var data := vector::<u8>::new();
var headed := false;
var at: u64 = 8;
while true {
if at + 12 > bytes.length {
return image_error::malformed;
}
val length := big_endian(bytes, at) as u64;
if length > 0x7FFFFFFF || at + 12 + length > bytes.length {
return image_error::malformed;
}
val kind: strview = bytes[at + 4:4];
val body := bytes[at + 8:length];
if crc32(bytes[at + 4:length + 4]) != big_endian(bytes, at + 8 + length) {
return image_error::malformed;
}
at += 12 + length;
if !headed {
if kind != "IHDR" {
return image_error::malformed;
}
head = read_header(body) else (e) { return e; };
headed = true;
continue;
}
if kind == "IDAT" {
data.extend(body);
} else if kind == "PLTE" {
if !read_palette(&mut head, body) {
return image_error::malformed;
}
} else if kind == "tRNS" {
if !read_transparency(&mut head, body) {
return image_error::malformed;
}
} else if kind == "IEND" {
break;
} else if kind == "IHDR" {
return image_error::malformed;
} else if (kind[0] & 0x20) == 0 {
# A critical chunk this doesn't know, which the image can't be read without.
return image_error::unsupported;
}
}
if data.is_empty || (head.color == indexed && head.entries == 0) {
return image_error::malformed;
}
var made := image::blank(head.width, head.height) else (e) { return e; };
var raw := vector::<u8>::new();
raw.resize(inflated_size(&head));
val written := inflate(data.view(), raw.slice()) else { return image_error::malformed; };
if written != raw.length {
return image_error::malformed;
}
# Each pass's rows, filtered, after the last's; one pass where it's not interlaced.
var start: u64 = 0;
for pass in 0u..7u {
val x0 := head.interlaced ? pass_x[pass] : 0;
val y0 := head.interlaced ? pass_y[pass] : 0;
val dx := head.interlaced ? pass_dx[pass] : 1;
val dy := head.interlaced ? pass_dy[pass] : 1;
val columns := head.width > x0 ? (head.width - x0 + dx - 1) / dx : 0;
val rows := head.height > y0 ? (head.height - y0 + dy - 1) / dy : 0;
if columns != 0 && rows != 0 {
val row_bytes := row_size(&head, columns);
if !unfilter(raw.slice(), start, rows as u64, row_bytes, bytes_per_pixel(&head)) {
return image_error::malformed;
}
for row in 0..rows as u64 {
val line := raw.view()[start + row * (row_bytes + 1) + 1:row_bytes];
if !put_row(&head, line, &mut made, y0 + row as u32 * dy, x0, dx, columns) {
return image_error::malformed;
}
}
start += rows as u64 * (row_bytes + 1);
}
if !head.interlaced {
break;
}
}
return move(made);
}
def big_endian(bytes: span<u8>, at: u64): u32 {
return (bytes[at] as u32 << 24) | (bytes[at + 1] as u32 << 16) | (bytes[at + 2] as u32 << 8) | bytes[at + 3] as u32;
}
def big_endian16(bytes: span<u8>, at: u64): u32 {
return (bytes[at] as u32 << 8) | bytes[at + 1] as u32;
}
+63
View File
@@ -0,0 +1,63 @@
#! Contains DEFLATE's alphabets, as RFC 1951 gives them: the length of the run
#! each length symbol stands for, and the distance back each distance symbol
#! does, each with how many bits more add to it; which symbol stands for each
#! run's length and distance; and the order a dynamic block gives the lengths
#! of the code its lengths are in.
module image::png;
# The lengths of each length symbol's run, from 257, and how many bits more add to
# each, then the same of each distance symbol.
const length_base: u32[29] = [3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258];
const length_extra: u32[29] = [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0];
const distance_base: u32[30] = [1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577];
const distance_extra: u32[30] = [0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13];
# The order a dynamic block gives the lengths of the code its lengths are in.
const length_order: u64[19] = [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15];
# The symbol, less 257, of each length of run, from 3 to 258: the last whose
# length is no more than it.
def length_symbols(): u8[259] {
var table: u8[259];
var symbol: u64 = 0;
for length in 3u..259u {
while symbol + 1 < 29 && length_base[symbol + 1] as u64 <= length {
symbol++;
}
table[length] = symbol as u8;
}
return table;
}
const length_symbol: u8[259] = length_symbols();
# The symbol of each distance, as zlib finds them: of the first 256 by the
# distance less 1, and of those past by the distance less 1 over 128, which
# every distance of the same 128 shares.
def distance_symbols(): u8[512] {
var table: u8[512];
var symbol: u64 = 0;
for index in 0u..256u {
while symbol + 1 < 30 && distance_base[symbol + 1] as u64 <= index + 1 {
symbol++;
}
table[index] = symbol as u8;
}
symbol = 0;
for index in 0u..256u {
while symbol + 1 < 30 && distance_base[symbol + 1] as u64 <= index * 128 + 1 {
symbol++;
}
table[256 + index] = symbol as u8;
}
return table;
}
const distance_symbols_of: u8[512] = distance_symbols();
# The symbol of a distance, from 1 to 32768.
def distance_symbol(distance: u64): u64 {
return distance <= 256 ? distance_symbols_of[distance - 1] as u64 : distance_symbols_of[256 + ((distance - 1) >> 7)] as u64;
}