Initial Commit
No files matched your search
@@ -0,0 +1,9 @@
|
|||||||
|
root = true
|
||||||
|
|
||||||
|
[*]
|
||||||
|
indent_style = space
|
||||||
|
indent_size = 2
|
||||||
|
end_of_line = lf
|
||||||
|
charset = utf-8
|
||||||
|
trim_trailing_whitespace = true
|
||||||
|
insert_final_newline = true
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
.blossom
|
||||||
|
tests/written.*
|
||||||
@@ -0,0 +1,133 @@
|
|||||||
|
# image
|
||||||
|
Images read from PNG, JPEG, and SVG, and written to PNG and JPEG, each the same `image`: RGBA, eight bits a channel, in sRGB, with straight alpha, rows from the top. That's what a GPU takes as `rgba8_srgb`, so an image is a texture as it is. It's Sakura's, built with [blossom](https://git.malunal.studio/sakura/blossom), and reads std's `containers`, `io`, `math`, and `xml`.
|
||||||
|
|
||||||
|
```sakura
|
||||||
|
import malunal::image;
|
||||||
|
|
||||||
|
val icon := image::load("assets/icon.svg", image::svg_size { width = 256 }) else (e) { ... };
|
||||||
|
val photo := image::load("assets/photo.jpg") else (e) { ... };
|
||||||
|
image::save(&photo, "out/photo.png") else (e) { ... }; # PNG, by the extension
|
||||||
|
val small := image::jpeg::encode(&photo, image::jpeg::options { quality = 80 }) else (e) { ... };
|
||||||
|
val tight := image::png::encode(&icon, image::png::options { level = 9 }) else (e) { ... };
|
||||||
|
```
|
||||||
|
`image::decode(bytes)` reads bytes already in memory, and `image::format_of(bytes)` says which format they're in, by their first few. `image::encode(&picture, format)` writes bytes, `image::write_to` writes them into any `writable`, as std's `json::write_to` does, and `image::save` writes a file in the format its extension names. Each format's own `encode` takes its options. An SVG is drawn at the size asked for, its own by default, and a raster image is read at its own whatever is asked. SVG is read, and not written.
|
||||||
|
|
||||||
|
A project reads it by requiring this folder, or its remote, and naming `malunal.image`, whose module is `malunal::image`, among a target's `deps`:
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
requires:
|
||||||
|
- ../image
|
||||||
|
targets:
|
||||||
|
- name: game
|
||||||
|
type: program
|
||||||
|
deps: [malunal.image]
|
||||||
|
```
|
||||||
|
|
||||||
|
## Layout
|
||||||
|
`image/` is the module `malunal::image`, and each format a module beneath it, as `malunal::image::png`.
|
||||||
|
|
||||||
|
| Path | Holds |
|
||||||
|
|---|---|
|
||||||
|
| `image.sakura` | `image`, `image_error`, and `max_pixels` |
|
||||||
|
| `formats.sakura` | `format`, `svg_size`, and which format bytes, or an extension, say |
|
||||||
|
| `reading.sakura` | `decode` and `load`, by the format the bytes are in |
|
||||||
|
| `writing.sakura` | `encode`, `write_to`, and `save`, in the format asked for or the extension names |
|
||||||
|
|
||||||
|
`png/`, `image::png`:
|
||||||
|
|
||||||
|
| Path | Holds |
|
||||||
|
|---|---|
|
||||||
|
| `png.sakura` | The color types, Adam7's passes, and the chunks read: `decode` |
|
||||||
|
| `header.sakura` | `IHDR`, `PLTE`, and `tRNS` |
|
||||||
|
| `pixels.sakura` | Rows of samples made RGBA, RGBA made rows, and the sizes of rows |
|
||||||
|
| `filters.sakura` | Filters undone, and the one leaving the least chosen |
|
||||||
|
| `inflate.sakura` | zlib's data inflated |
|
||||||
|
| `deflate.sakura` | Runs found back through chains of hashes, at each level |
|
||||||
|
| `blocks.sakura` | Bits written, and each block written stored, by the fixed codes, or by its own |
|
||||||
|
| `huffman.sakura` | Codes read by table, and codes made of how often each symbol is used |
|
||||||
|
| `symbols.sakura` | DEFLATE's lengths and distances, and their symbols |
|
||||||
|
| `checksums.sakura` | CRC-32 and Adler-32 |
|
||||||
|
| `colors.sakura` | What colors an image holds, and the color type and depth chosen of them |
|
||||||
|
| `encode.sakura` | `options` and `encode`: rows filtered and deflated, then the chunks |
|
||||||
|
|
||||||
|
`jpeg/`, `image::jpeg`:
|
||||||
|
|
||||||
|
| Path | Holds |
|
||||||
|
|---|---|
|
||||||
|
| `jpeg.sakura` | Zigzag order, and the markers read: `decode` |
|
||||||
|
| `markers.sakura` | The decoder's state, and the frame, tables, and scans' headers |
|
||||||
|
| `huffman.sakura` | Huffman tables, and the bits of a scan read |
|
||||||
|
| `scan.sakura` | A scan's blocks decoded, sequential and progressive |
|
||||||
|
| `idct.sakura` | The inverse DCT |
|
||||||
|
| `color.sakura` | Components upsampled, and pixels' colors of them |
|
||||||
|
| `tables.sakura` | Annex K's quantization and Huffman tables, and quality's scaling |
|
||||||
|
| `planes.sakura` | YCbCr, or gray, of an image's pixels, padded and subsampled |
|
||||||
|
| `fdct.sakura` | The forward DCT, and quantizing |
|
||||||
|
| `entropy.sakura` | Huffman codes, the bits of a scan written, and each block coded |
|
||||||
|
| `encode.sakura` | `options`, `subsampling`, and `encode`: the markers, then the scan |
|
||||||
|
|
||||||
|
`svg/`, `image::svg`:
|
||||||
|
|
||||||
|
| Path | Holds |
|
||||||
|
|---|---|
|
||||||
|
| `svg.sakura` | The renderer, and its size worked out: `render` |
|
||||||
|
| `draw.sakura` | The document indexed, styled, and walked, and layers for opacity, clips, and masks |
|
||||||
|
| `viewports.sakura` | Nested `svg`s, `use`, `symbol`, `viewBox`, and `preserveAspectRatio` |
|
||||||
|
| `shapes.sakura` | Each shape's path, filled and stroked |
|
||||||
|
| `gradients.sakura` | Paints, and linear and radial gradients by their `href` chains |
|
||||||
|
| `masks.sakura` | `clipPath` and `mask` |
|
||||||
|
| `style.sakura` | Each element's properties, set and inherited |
|
||||||
|
| `sheet.sakura` | `<style>` sheets' rules, matched by specificity |
|
||||||
|
| `color.sakura` | Colors as CSS writes them |
|
||||||
|
| `named_colors.sakura` | CSS's named colors |
|
||||||
|
| `paint.sakura` | Fills' and strokes' paints |
|
||||||
|
| `lengths.sakura` | Lengths, their units, and percentages |
|
||||||
|
| `matrix.sakura` | Points, transforms, and `transform` lists |
|
||||||
|
| `path.sakura` | Paths of lines and cubics, arcs, rectangles, and ellipses |
|
||||||
|
| `path_data.sakura` | A `d` attribute read |
|
||||||
|
| `numbers.sakura` | Numbers as CSS and SVG write them |
|
||||||
|
| `outline.sakura` | Paths flattened to polygons |
|
||||||
|
| `stroke.sakura` | Strokes made polygons, with caps, joins, and dashes |
|
||||||
|
| `painter.sakura` | The color of each pixel, of a color or a gradient |
|
||||||
|
| `raster.sakura` | Polygons filled by their coverage |
|
||||||
|
| `canvas.sakura` | Layers, and their compositing |
|
||||||
|
|
||||||
|
## What's read
|
||||||
|
- **PNG**: every color type and bit depth, interlaced or not, with `tRNS`. Sixteen-bit samples are rounded to eight. Chunks' CRCs and zlib's Adler-32 are checked; ancillary chunks are skipped, so color is taken as sRGB whatever `gAMA`, `cHRM`, or `iCCP` say. An animated PNG gives its default image.
|
||||||
|
- **JPEG**: baseline, extended, and progressive Huffman coding, any sampling factors, and restart markers; gray, YCbCr, RGB, and Adobe's CMYK and YCCK, without color profiles. Its samples are libjpeg's: its accurate integer IDCT, its fancy upsampling, and its YCbCr constants. Data cut short gives the image as far as it goes. Arithmetic coding, lossless JPEG, and 12-bit samples are `unsupported`, and EXIF's orientation isn't applied.
|
||||||
|
- **SVG**: the static part of SVG 1.1 icons and illustrations are made of: paths and the basic shapes; `g`, `use`, `symbol`, `switch`, and nested `svg` viewports with `viewBox` and `preserveAspectRatio`; fills by either rule; strokes with caps, joins, miter limits, and dashes; colors as CSS writes them, linear and radial gradients with every spread and `href` inheritance; `opacity`, `clip-path`, and `mask`. Styles come from presentation attributes, then `<style>` sheets, whose selectors may be types, classes, IDs, and descendant and child combinators, then `style` attributes, with `inherit` and `currentColor`. Its XML is read by `std::xml`, entities and all, as Illustrator's files need. Text, embedded images, patterns, markers, filters, and nested viewports' clipping aren't drawn.
|
||||||
|
|
||||||
|
The SVG rasterizer covers each pixel with sixteen rows of samples, each span's coverage across them worked out exactly, and blends onto layers of premultiplied RGBA, one for each group with opacity, a clip, or a mask. Gradients' stops are blended before they're premultiplied, as browsers blend them.
|
||||||
|
|
||||||
|
## What's written
|
||||||
|
- **PNG**: every pixel exactly, in the least color type and depth that holds them all: gray of 1, 2, 4, or 8 bits, where every pixel is gray and opaque; a palette of up to 256 colors, of 1, 2, 4, or 8 bits, its alpha in `tRNS`, where that's fewer bits than gray takes; and otherwise gray with alpha, RGB, or RGBA, of 8 bits. `png::options { reduced = false }` writes RGBA of 8 bits whatever the pixels are, and `interlaced = true` writes Adam7's passes. Rows of 8-bit samples are each filtered by whichever of PNG's five filters leaves the least, by the sum of its bytes taken as signed, as libpng chooses, and rows of palette indices or of samples less than a byte by none. Deflate is zlib's: chains of where each three bytes were seen, its levels' table from 0, which stores, to 9, with lazy matching from 4, and each block of 16384 symbols written stored, by the fixed codes, or by Huffman codes of its own, limited to 15 bits as miniz limits them, whichever is shortest. An `sRGB` chunk says the colors are sRGB's; nothing else ancillary is written.
|
||||||
|
- **JPEG**: baseline, as libjpeg writes it by default: JFIF's YCbCr, by libjpeg's constants; Annex K's quantization tables, scaled by quality as libjpeg scales them, 90 by default; libjpeg's accurate integer DCT; and Annex K's Huffman tables. Chrominance is halved across and down by default, as libjpeg halves it, `subsampling::across` halves it across alone, and `none` keeps every sample. An image every pixel of which is gray is written as gray alone. JPEG holds no alpha, so each pixel's color is written however clear it is. It may be 65535 across and down at most, past which is `too_large`.
|
||||||
|
|
||||||
|
## Limits
|
||||||
|
`max_pixels`, 64 M, bounds every image read, refused as `too_large` before its pixels are read or drawn. PNG's data is inflated into exactly as much memory as the image needs, and no more. SVG's references nest at most 64 deep, so a `use` within what it refers to ends.
|
||||||
|
|
||||||
|
## Speed
|
||||||
|
`blossom build`, then run `malunal.image.bench`, which writes and reads two images of 1024 by 1024 pixels, the best of three, on a Ryzen 9 9950X3D: one as a photograph is, gradients with a little noise over them, and one as an interface is, panels of flat colors. Windows' own encoders, WIC's, write the same as PNG and as JPEG of quality 90 for comparison:
|
||||||
|
|
||||||
|
| What | Written | Read | Size | WIC writes |
|
||||||
|
|---|---|---|---|---|
|
||||||
|
| PNG level 1, photograph | 58 ms | 19 ms | 1256 KiB | |
|
||||||
|
| PNG level 6, photograph | 284 ms | 17 ms | 1079 KiB | 40 ms, 1071 KiB |
|
||||||
|
| PNG level 9, photograph | 546 ms | 16 ms | 1042 KiB | |
|
||||||
|
| PNG level 6, interface | 8 ms | 3 ms | 2 KiB | 5 ms, 6 KiB |
|
||||||
|
| JPEG 90, 4:2:0, photograph | 19 ms | 15 ms | 115 KiB | 2 ms, 116 KiB |
|
||||||
|
| JPEG 90, 4:4:4, photograph | 30 ms | 17 ms | 163 KiB | |
|
||||||
|
| JPEG 90, 4:2:0, interface | 16 ms | 13 ms | 66 KiB | 1 ms, 67 KiB |
|
||||||
|
|
||||||
|
Deflate's time is in walking its chains, as zlib's is, so a level's time follows how far it looks: a noisy photograph at level 6, which looks 128 places back, takes five times level 1's. What's flat, as interfaces and icons are, is quick at any level.
|
||||||
|
|
||||||
|
## Testing
|
||||||
|
`blossom test` runs `tests/`, which reads the images in `tests/images/`, and writes images of patterns it makes in memory and reads them back: PNG of every color type, depth, level, and interlacing, exactly; JPEG of each subsampling and of sizes of part of a block, near its colors, gray as gray, and smaller at lower quality; and files saved by their extensions. `tools/test_images.ps1` writes the test images again with Windows' own encoders, from a pattern the tests work out again.
|
||||||
|
|
||||||
|
What's read was checked further against outside references, which aren't part of the repository:
|
||||||
|
- **PNG:** every image of PngSuite, against WIC. Those of eight bits or fewer match exactly, those of sixteen within the 1 rounding gives, and every broken one is refused.
|
||||||
|
- **JPEG:** `jpeg-decoder`'s reference images, made by libjpeg, all within 3 but a progressive one cut short, which libjpeg smooths.
|
||||||
|
- **SVG:** drawings against Chrome's, the Ghostscript Tiger and Wikipedia's logo among them.
|
||||||
|
- **Fuzzing:** a checked build was given each of those cut short and with bytes changed, CRCs fixed so the changes reach past them, and faulted at none.
|
||||||
|
|
||||||
|
And what's written, against WIC's decoders: 47 PNGs of every color type, depth, level, and interlacing, 300 by 300 of noise and of a photograph among them, each read back exactly; and JPEGs of every subsampling at odd sizes, each read to the same colors this reads them as.
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
name: image
|
||||||
|
gpid: malunal
|
||||||
|
semv: 1.0.0
|
||||||
|
|
||||||
|
options:
|
||||||
|
level: 2
|
||||||
|
|
||||||
|
requires:
|
||||||
|
- https://git.malunal.studio/sakura/std@v1.0.0
|
||||||
|
|
||||||
|
targets:
|
||||||
|
- name: malunal.image
|
||||||
|
type: library
|
||||||
|
root: ./image
|
||||||
|
deps:
|
||||||
|
- std.containers
|
||||||
|
- std.io
|
||||||
|
- std.math
|
||||||
|
- std.xml
|
||||||
|
|
||||||
|
# Times reading and writing each format; see its header.
|
||||||
|
- name: malunal.image.bench
|
||||||
|
type: program
|
||||||
|
level: ${level}
|
||||||
|
deps:
|
||||||
|
- malunal.image
|
||||||
|
- std.io
|
||||||
|
- std.time
|
||||||
|
srcs:
|
||||||
|
- tools/bench.sakura
|
||||||
|
|
||||||
|
tests:
|
||||||
|
# They read the images in `tests/images/`, from the package's root.
|
||||||
|
- name: malunal.image.tests
|
||||||
|
type: program
|
||||||
|
deps: [malunal.image, std.io, std.testing]
|
||||||
|
srcs:
|
||||||
|
- tests/main.sakura
|
||||||
|
- tests/support.sakura
|
||||||
|
- tests/formats.sakura
|
||||||
|
- tests/png.sakura
|
||||||
|
- tests/jpeg.sakura
|
||||||
|
- tests/svg.sakura
|
||||||
|
|
||||||
|
exports:
|
||||||
|
- malunal.image
|
||||||
|
|
||||||
|
package:
|
||||||
|
desc: Images read from PNG, JPEG, and SVG, and written to PNG and JPEG, as RGBA of eight bits a channel in sRGB.
|
||||||
|
auth: John Christman <sorakatadzuma@gmail.com>
|
||||||
@@ -0,0 +1,98 @@
|
|||||||
|
#! Contains the formats, and how bytes, or a file's name, say which one they're
|
||||||
|
#! in.
|
||||||
|
|
||||||
|
module malunal::image;
|
||||||
|
|
||||||
|
|
||||||
|
#! The formats an image is read from, the first two of which it's written to.
|
||||||
|
pub enum format: u8 {
|
||||||
|
png, #! PNG, of any bit depth and color type, interlaced or not.
|
||||||
|
jpeg, #! JPEG, baseline or progressive, gray, YCbCr, RGB, CMYK, or YCCK.
|
||||||
|
svg, #! SVG, drawn at the size asked for, and never written.
|
||||||
|
}
|
||||||
|
|
||||||
|
#! The size an SVG is drawn at. Left as it is, that's the size the SVG gives
|
||||||
|
#! itself, by its `width` and `height`, or its `viewBox` without them. A width or
|
||||||
|
#! height asked for alone sets the other to keep the SVG's shape, and `scale`
|
||||||
|
#! multiplies whichever size is chosen. Raster formats are read at their own size
|
||||||
|
#! whatever this says.
|
||||||
|
pub struct svg_size {
|
||||||
|
pub var width: u32 = 0;
|
||||||
|
pub var height: u32 = 0;
|
||||||
|
pub var scale: f64 = 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
#! Which format bytes are in, by how they begin: PNG's signature, JPEG's start of
|
||||||
|
#! image, or text whose first element is `<svg`.
|
||||||
|
#! @param bytes The bytes.
|
||||||
|
#! @returns The format, or `nothing` where they're none of those.
|
||||||
|
pub def format_of(bytes: span<u8>): maybe<format> {
|
||||||
|
if bytes.length >= 8 && bytes[0] == 0x89 && bytes[1] == 'P' && bytes[2] == 'N' && bytes[3] == 'G'
|
||||||
|
&& bytes[4] == 0x0D && bytes[5] == 0x0A && bytes[6] == 0x1A && bytes[7] == 0x0A {
|
||||||
|
return format::png;
|
||||||
|
}
|
||||||
|
if bytes.length >= 3 && bytes[0] == 0xFF && bytes[1] == 0xD8 && bytes[2] == 0xFF {
|
||||||
|
return format::jpeg;
|
||||||
|
}
|
||||||
|
if looks_like_svg(bytes) {
|
||||||
|
return format::svg;
|
||||||
|
}
|
||||||
|
return nothing {};
|
||||||
|
}
|
||||||
|
|
||||||
|
#! Which format a file's extension names, whatever the case of its letters:
|
||||||
|
#! `png`, `jpg`, `jpeg`, `jpe`, `jfif`, or `svg`.
|
||||||
|
#! @param extension The extension, without its `.`.
|
||||||
|
#! @returns The format, or `nothing` where it names none.
|
||||||
|
pub def format_named(extension: strview): maybe<format> {
|
||||||
|
val lowered := extension.lower();
|
||||||
|
val name := lowered.span;
|
||||||
|
if name == "png" {
|
||||||
|
return format::png;
|
||||||
|
}
|
||||||
|
if name == "jpg" || name == "jpeg" || name == "jpe" || name == "jfif" {
|
||||||
|
return format::jpeg;
|
||||||
|
}
|
||||||
|
if name == "svg" {
|
||||||
|
return format::svg;
|
||||||
|
}
|
||||||
|
return nothing {};
|
||||||
|
}
|
||||||
|
|
||||||
|
# Whether bytes are text, after a byte order mark and whitespace, whose markup
|
||||||
|
# reaches an `svg` element before anything else: only declarations, comments,
|
||||||
|
# instructions, and the document type may come first.
|
||||||
|
def looks_like_svg(bytes: span<u8>): bool {
|
||||||
|
val text: strview = bytes;
|
||||||
|
var at: u64 = text.starts_with("\xEF\xBB\xBF") ? 3 : 0;
|
||||||
|
while at < text.length {
|
||||||
|
while at < text.length && text[at].is_space {
|
||||||
|
at++;
|
||||||
|
}
|
||||||
|
if at >= text.length || text[at] != '<' {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
val rest := text.substr(at, text.length - at);
|
||||||
|
if rest.starts_with("<?") || rest.starts_with("<!") {
|
||||||
|
# Past it: a comment to `-->`, and the rest to the `>` closing them, past
|
||||||
|
# any internal subset of a document type, which `[` begins before it.
|
||||||
|
var closing: strview = rest.starts_with("<!--") ? "-->" : ">";
|
||||||
|
val end := rest.find(closing) else { return false; };
|
||||||
|
if rest.starts_with("<!DOCTYPE") && rest.substr(0, end).find("[") is some(_) {
|
||||||
|
closing = "]>";
|
||||||
|
}
|
||||||
|
val past := rest.find(closing) else { return false; };
|
||||||
|
at += past + closing.length;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
# The first element: `svg`, with or without a prefix.
|
||||||
|
var end: u64 = 1;
|
||||||
|
while end < rest.length && !rest[end].is_space && rest[end] != '>' && rest[end] != '/' {
|
||||||
|
end++;
|
||||||
|
}
|
||||||
|
val name := rest.substr(1, end - 1);
|
||||||
|
return name == "svg" || name.ends_with(":svg");
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
@@ -0,0 +1,63 @@
|
|||||||
|
#! Contains `image`, pixels read from PNG, JPEG, or SVG, or written to PNG or
|
||||||
|
#! JPEG, and why one couldn't be.
|
||||||
|
#!
|
||||||
|
#! Each format is a module of its own beneath this one, `image::png`,
|
||||||
|
#! `image::jpeg`, and `image::svg`, which this one's functions choose between:
|
||||||
|
#! by the bytes' first few to read them, and by the format asked for, or a
|
||||||
|
#! file's extension, to write them. Each gives and takes the same `image`: RGBA,
|
||||||
|
#! eight bits a channel, in sRGB, its alpha straight rather than premultiplied,
|
||||||
|
#! its rows from the top, which is what a GPU takes as `rgba8_srgb`.
|
||||||
|
|
||||||
|
module malunal::image;
|
||||||
|
|
||||||
|
|
||||||
|
#! The most pixels an image may have: 64 M, or 256 MiB of RGBA. One said to have
|
||||||
|
#! more is refused before its pixels are read, as `too_large`.
|
||||||
|
pub const max_pixels: u64 = 0x4000000;
|
||||||
|
|
||||||
|
#! Why an image could not be read or written.
|
||||||
|
pub enum image_error: u8 {
|
||||||
|
unreadable, #! The file could not be read.
|
||||||
|
unwritable, #! The file, or the stream, could not be written.
|
||||||
|
unrecognized, #! The bytes are none of the formats read, PNG, JPEG, or SVG, or a file's extension none of those written.
|
||||||
|
malformed, #! The data breaks its format, or is cut short; or an image written has no pixels, or other than `width * height * 4` bytes of them.
|
||||||
|
unsupported, #! The data is well formed, but uses what isn't read, as JPEG's arithmetic coding; or the format isn't written, as SVG isn't.
|
||||||
|
too_large, #! The image has more pixels than `max_pixels`, or is wider or taller than its format holds.
|
||||||
|
}
|
||||||
|
|
||||||
|
#! Pixels: RGBA, eight bits a channel, in sRGB, with straight alpha, a row of
|
||||||
|
#! `width` after another from the top.
|
||||||
|
pub struct image {
|
||||||
|
pub var width: u32;
|
||||||
|
pub var height: u32;
|
||||||
|
pub var pixels: vector<u8>; #! `width * height * 4` bytes.
|
||||||
|
}
|
||||||
|
|
||||||
|
#! The color of a pixel.
|
||||||
|
#! @param this The image.
|
||||||
|
#! @param x The column, from the left, below `width`.
|
||||||
|
#! @param y The row, from the top, below `height`.
|
||||||
|
#! @returns Its red, green, blue, and alpha.
|
||||||
|
pub def image::at(&this, x: u32, y: u32): u8[4] {
|
||||||
|
val start := ((y as u64) * (this.width as u64) + (x as u64)) * 4;
|
||||||
|
return [this.pixels[start], this.pixels[start + 1], this.pixels[start + 2], this.pixels[start + 3]];
|
||||||
|
}
|
||||||
|
|
||||||
|
# An image of a size, every pixel clear, or `too_large` where it has more pixels
|
||||||
|
# than may be.
|
||||||
|
def blank(width: u32, height: u32): result<image, image_error> {
|
||||||
|
val count := (width as u64) * (height as u64);
|
||||||
|
if count > max_pixels {
|
||||||
|
return image_error::too_large;
|
||||||
|
}
|
||||||
|
var pixels := vector::<u8>::new();
|
||||||
|
pixels.resize(count * 4);
|
||||||
|
return image { width = width, height = height, pixels = move(pixels) };
|
||||||
|
}
|
||||||
|
|
||||||
|
# Whether an image is whole, as writing it needs: it has pixels, and as many
|
||||||
|
# bytes of them as its size says.
|
||||||
|
def is_whole(picture: &image): bool {
|
||||||
|
return picture.width != 0 && picture.height != 0
|
||||||
|
&& picture.pixels.length == (picture.width as u64) * (picture.height as u64) * 4;
|
||||||
|
}
|
||||||
@@ -0,0 +1,143 @@
|
|||||||
|
#! Contains the image made of a frame's coefficients: each block's samples, each
|
||||||
|
#! component's upsampled where it's subsampled, and each pixel's color from
|
||||||
|
#! them, as gray, YCbCr, RGB, CMYK, or YCCK.
|
||||||
|
|
||||||
|
module malunal::image::jpeg;
|
||||||
|
|
||||||
|
|
||||||
|
# Makes the image from the coefficients: each block's IDCT into its component's
|
||||||
|
# samples, then each pixel's color from them, upsampled where they're fewer.
|
||||||
|
def decoder::finish(&mut this): result<image, image_error> {
|
||||||
|
val tables := this.quant;
|
||||||
|
for index in 0..this.components.length {
|
||||||
|
val held := &mut this.components[index];
|
||||||
|
val stride := (held.blocks_wide as u64) * 8;
|
||||||
|
held.plane.resize(stride * (held.blocks_high as u64) * 8);
|
||||||
|
val quant := tables[held.table * 64:64];
|
||||||
|
val samples := held.plane.slice;
|
||||||
|
for block_y in 0..held.blocks_high as u64 {
|
||||||
|
for block_x in 0..held.blocks_wide as u64 {
|
||||||
|
val block := held.coefficients.span[(block_y * held.blocks_wide as u64 + block_x) * 64:64];
|
||||||
|
idct(block, quant, samples, block_y * 8 * stride + block_x * 8, stride);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var made := image::blank(this.width, this.height) else (e) { return e; };
|
||||||
|
val count := this.components.length;
|
||||||
|
val width := this.width as u64;
|
||||||
|
var rows := vector::<u8>::new();
|
||||||
|
rows.resize(width * count);
|
||||||
|
val rgb := count == 3 && ((this.adobe && this.transform == 0) || (this.components[0].id == 'R' && this.components[1].id == 'G' && this.components[2].id == 'B'));
|
||||||
|
for y in 0..this.height {
|
||||||
|
for index in 0..count {
|
||||||
|
upsample_row(&this.components[index], y, this.h_max, this.v_max, this.width, rows.slice[index * width:width]);
|
||||||
|
}
|
||||||
|
var out := (y as u64) * width * 4;
|
||||||
|
for x in 0..width {
|
||||||
|
var r: i32 = rows[x] as i32;
|
||||||
|
var g: i32 = r;
|
||||||
|
var b: i32 = r;
|
||||||
|
if count >= 3 {
|
||||||
|
val c1: i32 = rows[width + x] as i32;
|
||||||
|
val c2: i32 = rows[width * 2 + x] as i32;
|
||||||
|
if rgb {
|
||||||
|
g = c1;
|
||||||
|
b = c2;
|
||||||
|
} else {
|
||||||
|
r = r + ((91881 * (c2 - 128) + 32768) >> 16);
|
||||||
|
g = g + ((-22554 * (c1 - 128) - 46802 * (c2 - 128) + 32768) >> 16);
|
||||||
|
b = b + ((116130 * (c1 - 128) + 32768) >> 16);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if count == 4 {
|
||||||
|
# Adobe's CMYK is inverted, so each ink's sample is how much it leaves, and
|
||||||
|
# YCCK's color is the inks it leaves, so less of it is more ink.
|
||||||
|
val k: i32 = rows[width * 3 + x] as i32;
|
||||||
|
if this.adobe && this.transform == 2 {
|
||||||
|
r = 255 - clamp(r);
|
||||||
|
g = 255 - clamp(g);
|
||||||
|
b = 255 - clamp(b);
|
||||||
|
} else {
|
||||||
|
r = rows[x] as i32;
|
||||||
|
g = rows[width + x] as i32;
|
||||||
|
b = rows[width * 2 + x] as i32;
|
||||||
|
}
|
||||||
|
r = blend(clamp(r), k);
|
||||||
|
g = blend(clamp(g), k);
|
||||||
|
b = blend(clamp(b), k);
|
||||||
|
}
|
||||||
|
made.pixels[out] = clamp(r) as u8;
|
||||||
|
made.pixels[out + 1] = clamp(g) as u8;
|
||||||
|
made.pixels[out + 2] = clamp(b) as u8;
|
||||||
|
made.pixels[out + 3] = 255;
|
||||||
|
out += 4;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return move(made);
|
||||||
|
}
|
||||||
|
|
||||||
|
# A component's samples of a row of the image: its own, or, where it's
|
||||||
|
# subsampled, made from them as libjpeg's fancy upsampling does where it's halved
|
||||||
|
# across, down, or both, each sample three parts the nearest and one the next,
|
||||||
|
# and the nearest of them otherwise, as libjpeg does too where it's no wider than
|
||||||
|
# two.
|
||||||
|
def upsample_row(held: &component, y: u32, h_max: u32, v_max: u32, width: u32, out: slice<u8>): void {
|
||||||
|
val stride := (held.blocks_wide as u64) * 8;
|
||||||
|
val plane := held.plane.span;
|
||||||
|
val last_x := (held.width - 1) as u64;
|
||||||
|
val last_y := (held.height - 1) as i64;
|
||||||
|
if held.h == h_max && held.v == v_max {
|
||||||
|
for x in 0..width as u64 {
|
||||||
|
out[x] = plane[(y as u64) * stride + x];
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
# libjpeg halves across fancily only where the component is wider than two.
|
||||||
|
val exact := h_max % held.h == 0 && v_max % held.v == 0;
|
||||||
|
val across := h_max / held.h;
|
||||||
|
val down := v_max / held.v;
|
||||||
|
if exact && across <= 2 && down <= 2 && (across == 1 || held.width > 2) {
|
||||||
|
# The row nearest, and the next nearest, above or below.
|
||||||
|
val near := (y / down) as i64;
|
||||||
|
var far := near;
|
||||||
|
if down == 2 {
|
||||||
|
far = y % 2 == 0 ? near - 1 : near + 1;
|
||||||
|
far = far < 0 ? 0 : (far > last_y ? last_y : far);
|
||||||
|
}
|
||||||
|
val near_row := (near as u64) * stride;
|
||||||
|
val far_row := (far as u64) * stride;
|
||||||
|
for x in 0..width as u64 {
|
||||||
|
if across == 1 {
|
||||||
|
# Halved down alone: three parts the nearest row, one the next.
|
||||||
|
val sum := plane[near_row + x] as u32 * 3 + plane[far_row + x] as u32;
|
||||||
|
out[x] = ((sum + (y % 2 == 0 ? 1 : 2)) >> 2) as u8;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
val column := x / 2;
|
||||||
|
var other := x % 2 == 0 ? (column == 0 ? 0 : column - 1) : column + 1;
|
||||||
|
other = other > last_x ? last_x : other;
|
||||||
|
if down == 1 {
|
||||||
|
val sum := plane[near_row + column] as u32 * 3 + plane[near_row + other] as u32;
|
||||||
|
out[x] = ((sum + (x % 2 == 0 ? 1 : 2)) >> 2) as u8;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
val here := plane[near_row + column] as u32 * 3 + plane[far_row + column] as u32;
|
||||||
|
val there := plane[near_row + other] as u32 * 3 + plane[far_row + other] as u32;
|
||||||
|
out[x] = ((here * 3 + there + (x % 2 == 0 ? 8 : 7)) >> 4) as u8;
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
val row := ((y as u64) * (held.v as u64) / (v_max as u64)) * stride;
|
||||||
|
for x in 0..width as u64 {
|
||||||
|
out[x] = plane[row + x * (held.h as u64) / (h_max as u64)];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
# Scales one value by another, each from 0 to 255 for 0 to 1, rounded.
|
||||||
|
def blend(value: i32, by: i32): i32 {
|
||||||
|
val product := value * by + 128;
|
||||||
|
return (product + (product >> 8)) >> 8;
|
||||||
|
}
|
||||||
@@ -0,0 +1,170 @@
|
|||||||
|
#! Contains JPEG's encoder, which writes an image as baseline JPEG, as libjpeg
|
||||||
|
#! writes one by default: JFIF's YCbCr, of the quality asked for, by Annex K's
|
||||||
|
#! tables, scaled, its chrominance subsampled as asked, its samples made
|
||||||
|
#! coefficients by libjpeg's accurate integer DCT. An image every pixel of
|
||||||
|
#! which is gray is written as gray alone. JPEG holds no alpha, so each pixel's
|
||||||
|
#! color is written as it is, however clear it is.
|
||||||
|
|
||||||
|
module malunal::image::jpeg;
|
||||||
|
|
||||||
|
|
||||||
|
#! How much of a JPEG's chrominance is kept, which the eye misses less than its
|
||||||
|
#! luminance.
|
||||||
|
pub enum subsampling: u8 {
|
||||||
|
none, #! 4:4:4: every sample of it.
|
||||||
|
across, #! 4:2:2: half of it across.
|
||||||
|
both, #! 4:2:0: half of it across, and half down, as most JPEGs are.
|
||||||
|
}
|
||||||
|
|
||||||
|
# JFIF's segment: 1.01, its pixels square, without a thumbnail.
|
||||||
|
const jfif: u8[14] = ['J', 'F', 'I', 'F', 0, 1, 1, 0, 0, 1, 0, 1, 0, 0];
|
||||||
|
|
||||||
|
#! How a JPEG is written.
|
||||||
|
pub struct options {
|
||||||
|
pub var quality: u32 = 90; #! From 1 to 100, as libjpeg scales its tables: the higher, the more kept, in more bytes.
|
||||||
|
pub var chroma: subsampling = subsampling::both; #! How much of its chrominance is kept.
|
||||||
|
}
|
||||||
|
|
||||||
|
#! Writes a JPEG.
|
||||||
|
#! @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, and `too_large` where
|
||||||
|
#! it's wider or taller than JPEG's 65535.
|
||||||
|
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 > 65535 || picture.height > 65535 {
|
||||||
|
return image_error::too_large;
|
||||||
|
}
|
||||||
|
|
||||||
|
# The components: gray alone, or Y, then Cb and Cr, sampled as asked.
|
||||||
|
val gray := is_gray(picture);
|
||||||
|
val h_max: u64 = gray || given.chroma == subsampling::none ? 1 : 2;
|
||||||
|
val v_max: u64 = gray || given.chroma != subsampling::both ? 1 : 2;
|
||||||
|
val mcus_wide := ((picture.width as u64) + 8 * h_max - 1) / (8 * h_max);
|
||||||
|
val mcus_high := ((picture.height as u64) + 8 * v_max - 1) / (8 * v_max);
|
||||||
|
var coded := planes_of(picture, gray, mcus_wide * 8 * h_max, mcus_high * 8 * v_max);
|
||||||
|
if !gray && h_max * v_max != 1 {
|
||||||
|
var blue := averaged(&coded.blue, h_max, v_max);
|
||||||
|
var red := averaged(&coded.red, h_max, v_max);
|
||||||
|
coded.blue = move(blue);
|
||||||
|
coded.red = move(red);
|
||||||
|
}
|
||||||
|
|
||||||
|
# The quantization tables, and what the DCT's coefficients are divided by.
|
||||||
|
var luminance: u16[64];
|
||||||
|
var chrominance: u16[64];
|
||||||
|
scaled(luminance_quantization[:], given.quality, luminance[:]);
|
||||||
|
scaled(chrominance_quantization[:], given.quality, chrominance[:]);
|
||||||
|
var divisors: i32[128];
|
||||||
|
for index in 0u..64u {
|
||||||
|
divisors[index] = (luminance[index] as i32) << 3;
|
||||||
|
divisors[64 + index] = (chrominance[index] as i32) << 3;
|
||||||
|
}
|
||||||
|
|
||||||
|
var out := vector::<u8>::new();
|
||||||
|
out.append(0xFF);
|
||||||
|
out.append(0xD8);
|
||||||
|
write_markers(&mut out, picture, gray, h_max, v_max, luminance[:], chrominance[:]);
|
||||||
|
|
||||||
|
# The scan: each MCU's blocks, Y's across then down, then Cb's and Cr's.
|
||||||
|
val dc_luminance := coder::of(dc_luminance_counts[:], dc_luminance_values[:]);
|
||||||
|
val ac_luminance := coder::of(ac_luminance_counts[:], ac_luminance_values[:]);
|
||||||
|
val dc_chrominance := coder::of(dc_chrominance_counts[:], dc_chrominance_values[:]);
|
||||||
|
val ac_chrominance := coder::of(ac_chrominance_counts[:], ac_chrominance_values[:]);
|
||||||
|
var bits := bit_writer { out = move(out) };
|
||||||
|
var predictions: i32[3];
|
||||||
|
for mcu_y in 0..mcus_high {
|
||||||
|
for mcu_x in 0..mcus_wide {
|
||||||
|
for block_y in 0..v_max {
|
||||||
|
for block_x in 0..h_max {
|
||||||
|
bits.block(&coded.luma, (mcu_x * h_max + block_x) * 8, (mcu_y * v_max + block_y) * 8, divisors[0:64],
|
||||||
|
&mut predictions[0], &dc_luminance, &ac_luminance);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !gray {
|
||||||
|
bits.block(&coded.blue, mcu_x * 8, mcu_y * 8, divisors[64:64], &mut predictions[1], &dc_chrominance, &ac_chrominance);
|
||||||
|
bits.block(&coded.red, mcu_x * 8, mcu_y * 8, divisors[64:64], &mut predictions[2], &dc_chrominance, &ac_chrominance);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
bits.flush();
|
||||||
|
var made := move(bits.out);
|
||||||
|
made.append(0xFF);
|
||||||
|
made.append(0xD9);
|
||||||
|
return move(made);
|
||||||
|
}
|
||||||
|
|
||||||
|
# Writes the markers before the scan: JFIF's, the quantization tables, the
|
||||||
|
# frame's header, the Huffman tables, and the scan's header.
|
||||||
|
def write_markers(out: &mut vector<u8>, picture: &image, gray: bool, h_max: u64, v_max: u64, luminance: span<u16>, chrominance: span<u16>): void {
|
||||||
|
val count: u64 = gray ? 1 : 3;
|
||||||
|
var body := vector::<u8>::new();
|
||||||
|
body.extend(jfif[:]);
|
||||||
|
segment(out, 0xE0, &mut body);
|
||||||
|
|
||||||
|
# Each table, its values in zigzag order.
|
||||||
|
val tables: u64 = gray ? 1 : 2;
|
||||||
|
for table in 0..tables {
|
||||||
|
body.append(table as u8);
|
||||||
|
for index in 0u..64u {
|
||||||
|
body.append((table == 0 ? luminance[zigzag[index]] : chrominance[zigzag[index]]) as u8);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
segment(out, 0xDB, &mut body);
|
||||||
|
|
||||||
|
# Baseline, of 8 bits a sample: Y sampled most, then Cb and Cr once each MCU.
|
||||||
|
body.append(8);
|
||||||
|
body.append((picture.height >> 8) as u8);
|
||||||
|
body.append(picture.height as u8);
|
||||||
|
body.append((picture.width >> 8) as u8);
|
||||||
|
body.append(picture.width as u8);
|
||||||
|
body.append(count as u8);
|
||||||
|
for index in 0..count {
|
||||||
|
body.append((index + 1) as u8);
|
||||||
|
body.append(index == 0 ? ((h_max << 4) | v_max) as u8 : 0x11);
|
||||||
|
body.append(index == 0 ? 0 : 1);
|
||||||
|
}
|
||||||
|
segment(out, 0xC0, &mut body);
|
||||||
|
|
||||||
|
table_of(&mut body, 0x00, dc_luminance_counts[:], dc_luminance_values[:]);
|
||||||
|
table_of(&mut body, 0x10, ac_luminance_counts[:], ac_luminance_values[:]);
|
||||||
|
if !gray {
|
||||||
|
table_of(&mut body, 0x01, dc_chrominance_counts[:], dc_chrominance_values[:]);
|
||||||
|
table_of(&mut body, 0x11, ac_chrominance_counts[:], ac_chrominance_values[:]);
|
||||||
|
}
|
||||||
|
segment(out, 0xC4, &mut body);
|
||||||
|
|
||||||
|
# Every component, Y by the first tables and Cb and Cr by the second, every
|
||||||
|
# coefficient at once.
|
||||||
|
body.append(count as u8);
|
||||||
|
for index in 0..count {
|
||||||
|
body.append((index + 1) as u8);
|
||||||
|
body.append(index == 0 ? 0x00 : 0x11);
|
||||||
|
}
|
||||||
|
body.append(0);
|
||||||
|
body.append(63);
|
||||||
|
body.append(0);
|
||||||
|
segment(out, 0xDA, &mut body);
|
||||||
|
}
|
||||||
|
|
||||||
|
# Appends a Huffman table's class and place, its counts, and its values.
|
||||||
|
def table_of(body: &mut vector<u8>, which: u8, counts: span<u8>, values: span<u8>): void {
|
||||||
|
body.append(which);
|
||||||
|
body.extend(counts);
|
||||||
|
body.extend(values);
|
||||||
|
}
|
||||||
|
|
||||||
|
# Appends a marker's segment: the marker, the length, then the body, which is
|
||||||
|
# emptied for the next.
|
||||||
|
def segment(out: &mut vector<u8>, marker: u8, body: &mut vector<u8>): void {
|
||||||
|
val length := body.length + 2;
|
||||||
|
out.append(0xFF);
|
||||||
|
out.append(marker);
|
||||||
|
out.append((length >> 8) as u8);
|
||||||
|
out.append(length as u8);
|
||||||
|
out.extend(body.span);
|
||||||
|
body.clear();
|
||||||
|
}
|
||||||
@@ -0,0 +1,123 @@
|
|||||||
|
#! Contains JPEG's entropy coding as it's written: Huffman codes made of a
|
||||||
|
#! table's counts and values, bits written the first the most significant, a
|
||||||
|
#! zero after each `0xFF`, and each block's coefficients coded as the decoder
|
||||||
|
#! reads a sequential scan's.
|
||||||
|
|
||||||
|
module malunal::image::jpeg;
|
||||||
|
|
||||||
|
|
||||||
|
# A Huffman table as it's written by: each value's code, and its length.
|
||||||
|
struct coder {
|
||||||
|
var code: u16[256];
|
||||||
|
var size: u8[256];
|
||||||
|
}
|
||||||
|
|
||||||
|
# The codes of a table, as JPEG gives them: those of each length in turn, of
|
||||||
|
# the values in order, after all those shorter.
|
||||||
|
def coder::of(counts: span<u8>, values: span<u8>): coder {
|
||||||
|
var made := coder {};
|
||||||
|
var code: u32 = 0;
|
||||||
|
var at: u64 = 0;
|
||||||
|
for length in 1u..17u {
|
||||||
|
for _ in 0..counts[length - 1] as u64 {
|
||||||
|
made.code[values[at] as u64] = code as u16;
|
||||||
|
made.size[values[at] as u64] = length as u8;
|
||||||
|
code++;
|
||||||
|
at++;
|
||||||
|
}
|
||||||
|
code <<= 1;
|
||||||
|
}
|
||||||
|
return made;
|
||||||
|
}
|
||||||
|
|
||||||
|
# Writes a scan's entropy-coded data, the first bit the most significant, a zero
|
||||||
|
# after each `0xFF`, so no marker stands within it.
|
||||||
|
struct bit_writer {
|
||||||
|
var out: vector<u8>;
|
||||||
|
var buffer: u32;
|
||||||
|
var count: u32; #! How many bits the buffer holds, fewer than 8 between writes.
|
||||||
|
}
|
||||||
|
|
||||||
|
# Writes the lowest bits of a number, up to 16.
|
||||||
|
def bit_writer::put(&mut this, bits: u32, size: u32): void {
|
||||||
|
this.buffer = (this.buffer << size) | bits;
|
||||||
|
this.count += size;
|
||||||
|
while this.count >= 8 {
|
||||||
|
val byte := (this.buffer >> (this.count - 8)) as u8;
|
||||||
|
this.out.append(byte);
|
||||||
|
if byte == 0xFF {
|
||||||
|
this.out.append(0);
|
||||||
|
}
|
||||||
|
this.count -= 8;
|
||||||
|
}
|
||||||
|
this.buffer &= ((1 as u32) << this.count) - 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
# Writes ones up to the next whole byte, as the data ends.
|
||||||
|
def bit_writer::flush(&mut this): void {
|
||||||
|
if this.count > 0 {
|
||||||
|
this.put(((1 as u32) << (8 - this.count)) - 1, 8 - this.count);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
# Codes a block of a plane: its samples, at a place, made coefficients, each
|
||||||
|
# divided by its divisor, then its DC coefficient's difference from the last,
|
||||||
|
# and its AC coefficients, as runs of zeros and the value after each.
|
||||||
|
def bit_writer::block(&mut this, from: &plane, x: u64, y: u64, divisors: span<i32>, prediction: &mut i32, dc: &coder, ac: &coder): void {
|
||||||
|
var work: i32[64] = undefined;
|
||||||
|
val samples := from.samples.span;
|
||||||
|
for row in 0u..8u {
|
||||||
|
val at := (y + row) * from.width + x;
|
||||||
|
for column in 0u..8u {
|
||||||
|
work[row * 8 + column] = samples[at + column] as i32 - 128;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fdct(work[:]);
|
||||||
|
for index in 0u..64u {
|
||||||
|
work[index] = quantize(work[index], divisors[index]);
|
||||||
|
}
|
||||||
|
|
||||||
|
val difference := work[0] - prediction;
|
||||||
|
prediction = work[0];
|
||||||
|
val size := bit_size(difference);
|
||||||
|
this.put(dc.code[size as u64] as u32, dc.size[size as u64] as u32);
|
||||||
|
this.put(bits_of(difference, size), size);
|
||||||
|
|
||||||
|
var run: u32 = 0;
|
||||||
|
for at in 1u..64u {
|
||||||
|
val value := work[zigzag[at]];
|
||||||
|
if value == 0 {
|
||||||
|
run++;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
while run > 15 {
|
||||||
|
this.put(ac.code[0xF0] as u32, ac.size[0xF0] as u32);
|
||||||
|
run -= 16;
|
||||||
|
}
|
||||||
|
val bits := bit_size(value);
|
||||||
|
val symbol := ((run << 4) | bits) as u64;
|
||||||
|
this.put(ac.code[symbol] as u32, ac.size[symbol] as u32);
|
||||||
|
this.put(bits_of(value, bits), bits);
|
||||||
|
run = 0;
|
||||||
|
}
|
||||||
|
if run > 0 {
|
||||||
|
this.put(ac.code[0] as u32, ac.size[0] as u32);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
# How many bits a value's magnitude takes.
|
||||||
|
def bit_size(value: i32): u32 {
|
||||||
|
var magnitude := value < 0 ? -value : value;
|
||||||
|
var size: u32 = 0;
|
||||||
|
while magnitude != 0 {
|
||||||
|
size++;
|
||||||
|
magnitude >>= 1;
|
||||||
|
}
|
||||||
|
return size;
|
||||||
|
}
|
||||||
|
|
||||||
|
# The bits a value is written as: itself, or, below zero, itself less one, of as
|
||||||
|
# many bits as its magnitude takes, as `bit_reader::extend` reads them.
|
||||||
|
def bits_of(value: i32, size: u32): u32 {
|
||||||
|
return (value < 0 ? value + (1 << size) - 1 : value) as u32;
|
||||||
|
}
|
||||||
@@ -0,0 +1,86 @@
|
|||||||
|
#! Contains the forward DCT, which makes a block's samples its coefficients, as
|
||||||
|
#! libjpeg's accurate integer one does, and the coefficients quantized.
|
||||||
|
|
||||||
|
module malunal::image::jpeg;
|
||||||
|
|
||||||
|
|
||||||
|
# libjpeg's accurate integer forward DCT, `jpeg_fdct_islow`: a block's samples,
|
||||||
|
# centered on 0, made its coefficients, in place, eight times as large as they
|
||||||
|
# are, which quantizing divides out.
|
||||||
|
def fdct(block: slice<i32>): void {
|
||||||
|
# Rows first, keeping two bits more.
|
||||||
|
for row in 0u..8u {
|
||||||
|
val at := row * 8;
|
||||||
|
val made := fdct_1d(block[at], block[at + 1], block[at + 2], block[at + 3],
|
||||||
|
block[at + 4], block[at + 5], block[at + 6], block[at + 7], 2, 11);
|
||||||
|
for column in 0u..8u {
|
||||||
|
block[at + column] = made[column];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
# Then columns, those two bits taken off.
|
||||||
|
for column in 0u..8u {
|
||||||
|
val made := fdct_1d(block[column], block[column + 8], block[column + 16], block[column + 24],
|
||||||
|
block[column + 32], block[column + 40], block[column + 48], block[column + 56], 0, 15);
|
||||||
|
for row in 0u..8u {
|
||||||
|
val value := made[row];
|
||||||
|
# The even part's first and fifth keep their two bits until here.
|
||||||
|
block[row * 8 + column] = row == 0 || row == 4 ? (value + 2) >> 2 : value;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
# One dimension of the forward DCT, at 13 bits of fixed point: the first and
|
||||||
|
# fifth coefficients shifted up by a number of bits, and the rest shifted down by
|
||||||
|
# another, rounded.
|
||||||
|
def fdct_1d(d0: i32, d1: i32, d2: i32, d3: i32, d4: i32, d5: i32, d6: i32, d7: i32, up: u32, down: u32): i32[8] {
|
||||||
|
val tmp0 := d0 + d7;
|
||||||
|
val tmp7 := d0 - d7;
|
||||||
|
val tmp1 := d1 + d6;
|
||||||
|
val tmp6 := d1 - d6;
|
||||||
|
val tmp2 := d2 + d5;
|
||||||
|
val tmp5 := d2 - d5;
|
||||||
|
val tmp3 := d3 + d4;
|
||||||
|
val tmp4 := d3 - d4;
|
||||||
|
|
||||||
|
# The even part.
|
||||||
|
val tmp10 := tmp0 + tmp3;
|
||||||
|
val tmp13 := tmp0 - tmp3;
|
||||||
|
val tmp11 := tmp1 + tmp2;
|
||||||
|
val tmp12 := tmp1 - tmp2;
|
||||||
|
val round: i32 = 1 << (down - 1);
|
||||||
|
var made: i32[8];
|
||||||
|
made[0] = (tmp10 + tmp11) << up;
|
||||||
|
made[4] = (tmp10 - tmp11) << up;
|
||||||
|
val even := (tmp12 + tmp13) * 4433;
|
||||||
|
made[2] = (even + tmp13 * 6270 + round) >> down;
|
||||||
|
made[6] = (even - tmp12 * 15137 + round) >> down;
|
||||||
|
|
||||||
|
# The odd part.
|
||||||
|
var z1 := tmp4 + tmp7;
|
||||||
|
var z2 := tmp5 + tmp6;
|
||||||
|
var z3 := tmp4 + tmp6;
|
||||||
|
var z4 := tmp5 + tmp7;
|
||||||
|
val z5 := (z3 + z4) * 9633;
|
||||||
|
val odd4 := tmp4 * 2446;
|
||||||
|
val odd5 := tmp5 * 16819;
|
||||||
|
val odd6 := tmp6 * 25172;
|
||||||
|
val odd7 := tmp7 * 12299;
|
||||||
|
z1 = z1 * -7373;
|
||||||
|
z2 = z2 * -20995;
|
||||||
|
z3 = z3 * -16069 + z5;
|
||||||
|
z4 = z4 * -3196 + z5;
|
||||||
|
made[7] = (odd4 + z1 + z3 + round) >> down;
|
||||||
|
made[5] = (odd5 + z2 + z4 + round) >> down;
|
||||||
|
made[3] = (odd6 + z2 + z3 + round) >> down;
|
||||||
|
made[1] = (odd7 + z1 + z4 + round) >> down;
|
||||||
|
return made;
|
||||||
|
}
|
||||||
|
|
||||||
|
# A coefficient divided by its divisor, rounded to the nearest, as libjpeg
|
||||||
|
# quantizes, halves away from zero.
|
||||||
|
def quantize(value: i32, divisor: i32): i32 {
|
||||||
|
if value < 0 {
|
||||||
|
return -((divisor / 2 - value) / divisor);
|
||||||
|
}
|
||||||
|
return (value + divisor / 2) / divisor;
|
||||||
|
}
|
||||||
@@ -0,0 +1,159 @@
|
|||||||
|
#! Contains JPEG's Huffman tables and the bits of a scan's entropy-coded data:
|
||||||
|
#! tables read as stb_image reads them, codes up to 9 bits long by a table and
|
||||||
|
#! longer ones by where each length's codes end, and the bits read the first
|
||||||
|
#! the most significant, the zero after each `0xFF` taken out.
|
||||||
|
|
||||||
|
module malunal::image::jpeg;
|
||||||
|
|
||||||
|
|
||||||
|
# How many bits of a code the fast table reads at once.
|
||||||
|
const fast_bits: u32 = 9;
|
||||||
|
|
||||||
|
# A Huffman table, read as stb_image reads them: codes up to 9 bits long by a
|
||||||
|
# table, and longer ones by where each length's codes end.
|
||||||
|
struct huffman {
|
||||||
|
var fast: u8[512]; #! The index of a code by its first 9 bits, or 255 for a longer one.
|
||||||
|
var code: u16[256];
|
||||||
|
var values: u8[256];
|
||||||
|
var size: u8[257];
|
||||||
|
var max_code: u32[18]; #! Just past the last code of each length, shifted to be 16 bits long.
|
||||||
|
var delta: i32[17]; #! What makes a code of each length its index.
|
||||||
|
}
|
||||||
|
|
||||||
|
# Reads the entropy-coded data of a scan, the first bit the most significant,
|
||||||
|
# taking out the zero after each `0xFF`, and stopping at a marker.
|
||||||
|
struct bit_reader {
|
||||||
|
var data: span<u8>;
|
||||||
|
var at: u64;
|
||||||
|
var buffer: u32; #! The bits read, from the most significant.
|
||||||
|
var count: u32;
|
||||||
|
var marker: u8; #! The marker found, which ends the data, or 0.
|
||||||
|
}
|
||||||
|
|
||||||
|
# Builds a table from how many codes there are of each length, and the values of
|
||||||
|
# them in order.
|
||||||
|
def huffman::build(&mut this, counts: span<u8>, values: span<u8>): bool {
|
||||||
|
var index: u64 = 0;
|
||||||
|
for length in 0u..16u {
|
||||||
|
for _ in 0..counts[length] as u64 {
|
||||||
|
this.size[index] = (length + 1) as u8;
|
||||||
|
index++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
this.size[index] = 0;
|
||||||
|
|
||||||
|
var code: u32 = 0;
|
||||||
|
index = 0;
|
||||||
|
for length in 1u..17u {
|
||||||
|
this.delta[length] = index as i32 - code as i32;
|
||||||
|
while this.size[index] as u64 == length {
|
||||||
|
this.code[index] = code as u16;
|
||||||
|
code++;
|
||||||
|
index++;
|
||||||
|
}
|
||||||
|
if (code as u64) > (1u << length) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
this.max_code[length] = code << (16 - length) as u32;
|
||||||
|
code <<= 1;
|
||||||
|
}
|
||||||
|
this.max_code[17] = 0xFFFFFFFF;
|
||||||
|
|
||||||
|
for slot in 0u..512u {
|
||||||
|
this.fast[slot] = 255;
|
||||||
|
}
|
||||||
|
for at in 0..index {
|
||||||
|
val length := this.size[at] as u32;
|
||||||
|
if length <= fast_bits {
|
||||||
|
val first := (this.code[at] as u64) << (fast_bits - length) as u64;
|
||||||
|
for slot in 0..(1u << (fast_bits - length) as u64) {
|
||||||
|
this.fast[first + slot] = at as u8;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for at in 0..values.length {
|
||||||
|
this.values[at] = values[at];
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
# Decodes a value of a table.
|
||||||
|
# @returns The value, or -1 where the bits are no code's.
|
||||||
|
def bit_reader::decode(&mut this, table: &huffman): i32 {
|
||||||
|
if this.count < 16 {
|
||||||
|
this.fill();
|
||||||
|
}
|
||||||
|
val at := table.fast[(this.buffer >> (32 - fast_bits)) as u64];
|
||||||
|
if at != 255 {
|
||||||
|
val length := table.size[at as u64] as u32;
|
||||||
|
this.buffer <<= length;
|
||||||
|
this.count -= length;
|
||||||
|
return table.values[at as u64] as i32;
|
||||||
|
}
|
||||||
|
|
||||||
|
# Longer than the table reads: the code's length is the first whose codes end
|
||||||
|
# past the bits.
|
||||||
|
val top := this.buffer >> 16;
|
||||||
|
var length: u64 = (fast_bits + 1) as u64;
|
||||||
|
while top >= table.max_code[length] {
|
||||||
|
length++;
|
||||||
|
}
|
||||||
|
if length == 17 {
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
val index := ((this.buffer >> (32 - length) as u32) as i32 + table.delta[length]) as u64;
|
||||||
|
if index > 255 || table.size[index] as u64 != length {
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
this.buffer <<= length as u32;
|
||||||
|
this.count -= length as u32;
|
||||||
|
return table.values[index] as i32;
|
||||||
|
}
|
||||||
|
|
||||||
|
# Reads bits, and makes them the signed value they stand for: those beginning
|
||||||
|
# with 0 are below zero.
|
||||||
|
def bit_reader::extend(&mut this, size: u32): i32 {
|
||||||
|
val value := this.take(size) as i32;
|
||||||
|
if value < (1 << (size - 1)) {
|
||||||
|
return value - (1 << size) + 1;
|
||||||
|
}
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
|
||||||
|
# Reads a number of bits, up to 16, the first the most significant.
|
||||||
|
def bit_reader::take(&mut this, size: u32): u32 {
|
||||||
|
if size == 0 {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
if this.count < size {
|
||||||
|
this.fill();
|
||||||
|
}
|
||||||
|
val made := this.buffer >> (32 - size);
|
||||||
|
this.buffer <<= size;
|
||||||
|
this.count -= size;
|
||||||
|
return made;
|
||||||
|
}
|
||||||
|
|
||||||
|
# Fills the buffer to more than 24 bits, with zeros once a marker ends the data.
|
||||||
|
def bit_reader::fill(&mut this): void {
|
||||||
|
while this.count <= 24 {
|
||||||
|
var byte: u32 = 0;
|
||||||
|
if this.marker == 0 && this.at < this.data.length {
|
||||||
|
byte = this.data[this.at] as u32;
|
||||||
|
this.at++;
|
||||||
|
if byte == 0xFF {
|
||||||
|
while this.at < this.data.length && this.data[this.at] == 0xFF {
|
||||||
|
this.at++;
|
||||||
|
}
|
||||||
|
val next: u8 = this.at < this.data.length ? this.data[this.at] : 0xD9;
|
||||||
|
this.at++;
|
||||||
|
if next != 0 {
|
||||||
|
this.marker = next;
|
||||||
|
byte = 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
this.buffer |= byte << (24 - this.count);
|
||||||
|
this.count += 8;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,99 @@
|
|||||||
|
#! Contains the inverse DCT, which makes a block's coefficients its samples, as
|
||||||
|
#! libjpeg's accurate integer one does.
|
||||||
|
|
||||||
|
module malunal::image::jpeg;
|
||||||
|
|
||||||
|
|
||||||
|
# libjpeg's accurate integer IDCT, `jpeg_idct_islow`: a block's coefficients,
|
||||||
|
# their quantization undone, made samples, written at a place in a component's.
|
||||||
|
def idct(block: span<i16>, quant: span<u16>, out: slice<u8>, at: u64, stride: u64): void {
|
||||||
|
var work: i32[64] = undefined;
|
||||||
|
|
||||||
|
# Columns first, keeping two bits more than a sample's.
|
||||||
|
for column in 0u..8u {
|
||||||
|
if block[column + 8] == 0 && block[column + 16] == 0 && block[column + 24] == 0 && block[column + 32] == 0
|
||||||
|
&& block[column + 40] == 0 && block[column + 48] == 0 && block[column + 56] == 0 {
|
||||||
|
val dc := (block[column] as i32 * quant[column] as i32) << 2;
|
||||||
|
for row in 0u..8u {
|
||||||
|
work[row * 8 + column] = dc;
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
val s0 := block[column] as i32 * quant[column] as i32;
|
||||||
|
val s1 := block[column + 8] as i32 * quant[column + 8] as i32;
|
||||||
|
val s2 := block[column + 16] as i32 * quant[column + 16] as i32;
|
||||||
|
val s3 := block[column + 24] as i32 * quant[column + 24] as i32;
|
||||||
|
val s4 := block[column + 32] as i32 * quant[column + 32] as i32;
|
||||||
|
val s5 := block[column + 40] as i32 * quant[column + 40] as i32;
|
||||||
|
val s6 := block[column + 48] as i32 * quant[column + 48] as i32;
|
||||||
|
val s7 := block[column + 56] as i32 * quant[column + 56] as i32;
|
||||||
|
val made := idct_1d(s0, s1, s2, s3, s4, s5, s6, s7, 13, 11);
|
||||||
|
for row in 0u..8u {
|
||||||
|
work[row * 8 + column] = made[row];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
# Then rows, to samples, centered on 128.
|
||||||
|
for row in 0u..8u {
|
||||||
|
val w := row * 8;
|
||||||
|
val made := idct_1d(work[w], work[w + 1], work[w + 2], work[w + 3], work[w + 4], work[w + 5], work[w + 6], work[w + 7], 13, 18);
|
||||||
|
for column in 0u..8u {
|
||||||
|
out[at + row * stride + column] = clamp(made[column] + 128) as u8;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
# One dimension of the IDCT, at 13 bits of fixed point, the results shifted down
|
||||||
|
# by a number of bits, rounded.
|
||||||
|
def idct_1d(s0: i32, s1: i32, s2: i32, s3: i32, s4: i32, s5: i32, s6: i32, s7: i32, bits: u32, shift: u32): i32[8] {
|
||||||
|
# The even part.
|
||||||
|
var z1 := (s2 + s6) * 4433;
|
||||||
|
val even2 := z1 + s6 * -15137;
|
||||||
|
val even3 := z1 + s2 * 6270;
|
||||||
|
val even0 := (s0 + s4) << bits;
|
||||||
|
val even1 := (s0 - s4) << bits;
|
||||||
|
val t10 := even0 + even3;
|
||||||
|
val t13 := even0 - even3;
|
||||||
|
val t11 := even1 + even2;
|
||||||
|
val t12 := even1 - even2;
|
||||||
|
|
||||||
|
# The odd part.
|
||||||
|
var t0 := s7;
|
||||||
|
var t1 := s5;
|
||||||
|
var t2 := s3;
|
||||||
|
var t3 := s1;
|
||||||
|
z1 = t0 + t3;
|
||||||
|
var z2 := t1 + t2;
|
||||||
|
var z3 := t0 + t2;
|
||||||
|
var z4 := t1 + t3;
|
||||||
|
val z5 := (z3 + z4) * 9633;
|
||||||
|
t0 = t0 * 2446;
|
||||||
|
t1 = t1 * 16819;
|
||||||
|
t2 = t2 * 25172;
|
||||||
|
t3 = t3 * 12299;
|
||||||
|
z1 = z1 * -7373;
|
||||||
|
z2 = z2 * -20995;
|
||||||
|
z3 = z3 * -16069 + z5;
|
||||||
|
z4 = z4 * -3196 + z5;
|
||||||
|
t0 += z1 + z3;
|
||||||
|
t1 += z2 + z4;
|
||||||
|
t2 += z2 + z3;
|
||||||
|
t3 += z1 + z4;
|
||||||
|
|
||||||
|
val round: i32 = 1 << (shift - 1);
|
||||||
|
return [
|
||||||
|
(t10 + t3 + round) >> shift,
|
||||||
|
(t11 + t2 + round) >> shift,
|
||||||
|
(t12 + t1 + round) >> shift,
|
||||||
|
(t13 + t0 + round) >> shift,
|
||||||
|
(t13 - t0 + round) >> shift,
|
||||||
|
(t12 - t1 + round) >> shift,
|
||||||
|
(t11 - t2 + round) >> shift,
|
||||||
|
(t10 - t3 + round) >> shift,
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
def clamp(value: i32): i32 {
|
||||||
|
return value < 0 ? 0 : (value > 255 ? 255 : value);
|
||||||
|
}
|
||||||
@@ -0,0 +1,80 @@
|
|||||||
|
#! Contains JPEG's markers read, which the rest of JPEG's module makes an image
|
||||||
|
#! of.
|
||||||
|
#!
|
||||||
|
#! What JPEG's Huffman coding writes is read: baseline and extended sequential,
|
||||||
|
#! and progressive, of 8-bit samples, with any sampling factors and restart
|
||||||
|
#! intervals. Gray, YCbCr, and RGB are read, and CMYK and YCCK as Adobe writes
|
||||||
|
#! them, without a color profile. Arithmetic coding, lossless JPEG, and 12-bit
|
||||||
|
#! samples are `unsupported`. Samples are made as libjpeg makes them by default:
|
||||||
|
#! its accurate integer IDCT, its "fancy" upsampling of chroma halved across,
|
||||||
|
#! down, or both, and its YCbCr constants. EXIF's orientation is not applied.
|
||||||
|
#!
|
||||||
|
#! An image is written as baseline JPEG, as `encode.sakura` says.
|
||||||
|
|
||||||
|
module malunal::image::jpeg;
|
||||||
|
|
||||||
|
|
||||||
|
# The natural index of each coefficient, by its place in zigzag order.
|
||||||
|
const zigzag: u64[64] = [
|
||||||
|
0, 1, 8, 16, 9, 2, 3, 10, 17, 24, 32, 25, 18, 11, 4, 5,
|
||||||
|
12, 19, 26, 33, 40, 48, 41, 34, 27, 20, 13, 6, 7, 14, 21, 28,
|
||||||
|
35, 42, 49, 56, 57, 50, 43, 36, 29, 22, 15, 23, 30, 37, 44, 51,
|
||||||
|
58, 59, 52, 45, 38, 31, 39, 46, 53, 60, 61, 54, 47, 55, 62, 63,
|
||||||
|
];
|
||||||
|
|
||||||
|
#! Reads a JPEG.
|
||||||
|
#! @param bytes The file's bytes.
|
||||||
|
#! @returns The image, or `unrecognized` where the bytes don't begin a JPEG,
|
||||||
|
#! `malformed` where its markers or data are broken, `unsupported` where
|
||||||
|
#! it's coded in a way not read, and `too_large` where it has too many
|
||||||
|
#! pixels. Data cut short gives the image as far as it goes.
|
||||||
|
pub def decode(bytes: span<u8>): result<image, image_error> {
|
||||||
|
if bytes.length < 4 || bytes[0] != 0xFF || bytes[1] != 0xD8 {
|
||||||
|
return image_error::unrecognized;
|
||||||
|
}
|
||||||
|
|
||||||
|
var state := decoder { data = bytes, at = 2, components = vector::<component>::new() };
|
||||||
|
while true {
|
||||||
|
val marker := state.next_marker() else { break; };
|
||||||
|
match marker {
|
||||||
|
0xC0, 0xC1, 0xC2 => {
|
||||||
|
if state.framed {
|
||||||
|
return image_error::malformed;
|
||||||
|
}
|
||||||
|
state.read_frame(marker == 0xC2) else (e) { return e; };
|
||||||
|
}
|
||||||
|
0xC3, 0xC5, 0xC6, 0xC7, 0xC9, 0xCA, 0xCB, 0xCD, 0xCE, 0xCF => return image_error::unsupported;
|
||||||
|
0xC4 => state.read_huffman() else (e) { return e; };
|
||||||
|
0xDB => state.read_quantization() else (e) { return e; };
|
||||||
|
0xDD => {
|
||||||
|
val body := state.segment() else { return image_error::malformed; };
|
||||||
|
if body.length < 2 {
|
||||||
|
return image_error::malformed;
|
||||||
|
}
|
||||||
|
state.restart = (body[0] as u32 << 8) | body[1] as u32;
|
||||||
|
}
|
||||||
|
0xDA => {
|
||||||
|
if !state.framed {
|
||||||
|
return image_error::malformed;
|
||||||
|
}
|
||||||
|
state.read_scan() else (e) { return e; };
|
||||||
|
}
|
||||||
|
0xD9 => break;
|
||||||
|
0xD0, 0xD1, 0xD2, 0xD3, 0xD4, 0xD5, 0xD6, 0xD7 => {}
|
||||||
|
0xEE => {
|
||||||
|
val body := state.segment() else { return image_error::malformed; };
|
||||||
|
if body.length >= 12 && body[0:5] == "Adobe" {
|
||||||
|
state.adobe = true;
|
||||||
|
state.transform = body[11];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else => {
|
||||||
|
_ = state.segment() else { return image_error::malformed; };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !state.framed {
|
||||||
|
return image_error::malformed;
|
||||||
|
}
|
||||||
|
return state.finish();
|
||||||
|
}
|
||||||
@@ -0,0 +1,256 @@
|
|||||||
|
#! Contains the decoder's state across JPEG's markers, and the segments it
|
||||||
|
#! reads: the frame's header, Huffman and quantization tables, and each scan's
|
||||||
|
#! header.
|
||||||
|
|
||||||
|
module malunal::image::jpeg;
|
||||||
|
|
||||||
|
|
||||||
|
# A component of the frame, and what its scans have given it.
|
||||||
|
struct component {
|
||||||
|
var id: u8;
|
||||||
|
var h: u32; #! Its sampling factors.
|
||||||
|
var v: u32;
|
||||||
|
var table: u64; #! Its quantization table.
|
||||||
|
var dc: u64; #! Its Huffman tables, in the scan being read.
|
||||||
|
var ac: u64;
|
||||||
|
var prediction: i32; #! The last DC coefficient, which the next is a difference from.
|
||||||
|
var width: u32; #! Its samples across, and down, which are fewer where it's subsampled.
|
||||||
|
var height: u32;
|
||||||
|
var blocks_wide: u32; #! Its blocks across, and down, to whole MCUs.
|
||||||
|
var blocks_high: u32;
|
||||||
|
var coefficients: vector<i16>; #! Each block's 64, in natural order, before quantization is undone.
|
||||||
|
var plane: vector<u8>; #! Its samples, once the IDCT has made them, `blocks_wide * 8` a row.
|
||||||
|
}
|
||||||
|
|
||||||
|
# The decoder's state across the markers.
|
||||||
|
struct decoder {
|
||||||
|
var data: span<u8>;
|
||||||
|
var at: u64;
|
||||||
|
var quant: u16[256]; #! The four quantization tables, in natural order.
|
||||||
|
var dc_tables: huffman[4];
|
||||||
|
var ac_tables: huffman[4];
|
||||||
|
var components: vector<component>;
|
||||||
|
var framed: bool;
|
||||||
|
var progressive: bool;
|
||||||
|
var width: u32;
|
||||||
|
var height: u32;
|
||||||
|
var h_max: u32;
|
||||||
|
var v_max: u32;
|
||||||
|
var mcus_wide: u32;
|
||||||
|
var mcus_high: u32;
|
||||||
|
var restart: u32; #! MCUs between restart markers, or 0.
|
||||||
|
var adobe: bool; #! Whether an Adobe segment says how color is transformed.
|
||||||
|
var transform: u8;
|
||||||
|
var marker: u8; #! A marker the last scan stopped at, which is read next.
|
||||||
|
}
|
||||||
|
|
||||||
|
# What a scan reads: which components, which coefficients, and which bits of them.
|
||||||
|
struct scan_of {
|
||||||
|
var which: u64[4];
|
||||||
|
var count: u64;
|
||||||
|
var start: u64; #! The first coefficient, and the last.
|
||||||
|
var end: u64;
|
||||||
|
var high: u32; #! The bit read before, or 0 for the first scan of these coefficients.
|
||||||
|
var low: u32; #! The bit read.
|
||||||
|
}
|
||||||
|
|
||||||
|
# The next marker, past any bytes before it, or `nothing` at the end of the data.
|
||||||
|
def decoder::next_marker(&mut this): maybe<u8> {
|
||||||
|
if this.marker != 0 {
|
||||||
|
val held := this.marker;
|
||||||
|
this.marker = 0;
|
||||||
|
return held;
|
||||||
|
}
|
||||||
|
while this.at + 1 < this.data.length {
|
||||||
|
if this.data[this.at] != 0xFF {
|
||||||
|
this.at++;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
# Fill bytes of 0xFF may stand before a marker.
|
||||||
|
var at := this.at + 1;
|
||||||
|
while at < this.data.length && this.data[at] == 0xFF {
|
||||||
|
at++;
|
||||||
|
}
|
||||||
|
if at >= this.data.length {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
val byte := this.data[at];
|
||||||
|
this.at = at + 1;
|
||||||
|
if byte != 0 {
|
||||||
|
return byte;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
this.at = this.data.length;
|
||||||
|
return nothing {};
|
||||||
|
}
|
||||||
|
|
||||||
|
# A marker's segment, after the length that begins it.
|
||||||
|
def decoder::segment(&mut this): maybe<span<u8>> {
|
||||||
|
if this.at + 2 > this.data.length {
|
||||||
|
return nothing {};
|
||||||
|
}
|
||||||
|
val length := ((this.data[this.at] as u64) << 8) | this.data[this.at + 1] as u64;
|
||||||
|
if length < 2 || this.at + length > this.data.length {
|
||||||
|
return nothing {};
|
||||||
|
}
|
||||||
|
val body := this.data[this.at + 2:length - 2];
|
||||||
|
this.at += length;
|
||||||
|
return body;
|
||||||
|
}
|
||||||
|
|
||||||
|
# Reads the frame's header: its size, and each component's sampling and table.
|
||||||
|
def decoder::read_frame(&mut this, progressive: bool): result<void, image_error> {
|
||||||
|
val body := this.segment() else { return image_error::malformed; };
|
||||||
|
if body.length < 6 {
|
||||||
|
return image_error::malformed;
|
||||||
|
}
|
||||||
|
if body[0] != 8 {
|
||||||
|
return image_error::unsupported;
|
||||||
|
}
|
||||||
|
this.height = (body[1] as u32 << 8) | body[2] as u32;
|
||||||
|
this.width = (body[3] as u32 << 8) | body[4] as u32;
|
||||||
|
val count := body[5] as u64;
|
||||||
|
if this.height == 0 {
|
||||||
|
# A height given after the first scan, by a DNL marker.
|
||||||
|
return image_error::unsupported;
|
||||||
|
}
|
||||||
|
if this.width == 0 || (count != 1 && count != 3 && count != 4) || body.length < 6 + count * 3 {
|
||||||
|
return image_error::malformed;
|
||||||
|
}
|
||||||
|
if (this.width as u64) * (this.height as u64) > image::max_pixels {
|
||||||
|
return image_error::too_large;
|
||||||
|
}
|
||||||
|
|
||||||
|
this.h_max = 1;
|
||||||
|
this.v_max = 1;
|
||||||
|
for index in 0..count {
|
||||||
|
val at := 6 + index * 3;
|
||||||
|
val h := (body[at + 1] >> 4) as u32;
|
||||||
|
val v := (body[at + 1] & 15) as u32;
|
||||||
|
val table := body[at + 2] as u64;
|
||||||
|
if h == 0 || h > 4 || v == 0 || v > 4 || table > 3 {
|
||||||
|
return image_error::malformed;
|
||||||
|
}
|
||||||
|
this.h_max = h > this.h_max ? h : this.h_max;
|
||||||
|
this.v_max = v > this.v_max ? v : this.v_max;
|
||||||
|
this.components.append(component {
|
||||||
|
id = body[at], h = h, v = v, table = table,
|
||||||
|
coefficients = vector::<i16>::new(), plane = vector::<u8>::new()
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
this.mcus_wide = (this.width + this.h_max * 8 - 1) / (this.h_max * 8);
|
||||||
|
this.mcus_high = (this.height + this.v_max * 8 - 1) / (this.v_max * 8);
|
||||||
|
for index in 0..count {
|
||||||
|
val held := &mut this.components[index];
|
||||||
|
held.width = (this.width * held.h + this.h_max - 1) / this.h_max;
|
||||||
|
held.height = (this.height * held.v + this.v_max - 1) / this.v_max;
|
||||||
|
held.blocks_wide = this.mcus_wide * held.h;
|
||||||
|
held.blocks_high = this.mcus_high * held.v;
|
||||||
|
held.coefficients.resize((held.blocks_wide as u64) * (held.blocks_high as u64) * 64);
|
||||||
|
}
|
||||||
|
this.framed = true;
|
||||||
|
this.progressive = progressive;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
# Reads Huffman tables, each a class, DC or AC, and a place among four.
|
||||||
|
def decoder::read_huffman(&mut this): result<void, image_error> {
|
||||||
|
val body := this.segment() else { return image_error::malformed; };
|
||||||
|
var at: u64 = 0;
|
||||||
|
while at < body.length {
|
||||||
|
if at + 17 > body.length {
|
||||||
|
return image_error::malformed;
|
||||||
|
}
|
||||||
|
val class := body[at] >> 4;
|
||||||
|
val place := (body[at] & 15) as u64;
|
||||||
|
if class > 1 || place > 3 {
|
||||||
|
return image_error::malformed;
|
||||||
|
}
|
||||||
|
var total: u64 = 0;
|
||||||
|
for length in 0u..16u {
|
||||||
|
total += body[at + 1 + length] as u64;
|
||||||
|
}
|
||||||
|
if total > 256 || at + 17 + total > body.length {
|
||||||
|
return image_error::malformed;
|
||||||
|
}
|
||||||
|
var made := huffman {};
|
||||||
|
if !made.build(body[at + 1:16], body[at + 17:total]) {
|
||||||
|
return image_error::malformed;
|
||||||
|
}
|
||||||
|
if class == 0 {
|
||||||
|
this.dc_tables[place] = made;
|
||||||
|
} else {
|
||||||
|
this.ac_tables[place] = made;
|
||||||
|
}
|
||||||
|
at += 17 + total;
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
# Reads quantization tables, of 8 or 16 bits a value, in zigzag order.
|
||||||
|
def decoder::read_quantization(&mut this): result<void, image_error> {
|
||||||
|
val body := this.segment() else { return image_error::malformed; };
|
||||||
|
var at: u64 = 0;
|
||||||
|
while at < body.length {
|
||||||
|
val wide := (body[at] >> 4) != 0;
|
||||||
|
val place := (body[at] & 15) as u64;
|
||||||
|
val size: u64 = wide ? 128 : 64;
|
||||||
|
if place > 3 || at + 1 + size > body.length {
|
||||||
|
return image_error::malformed;
|
||||||
|
}
|
||||||
|
for index in 0u..64u {
|
||||||
|
val value: u16 = wide ? ((body[at + 1 + index * 2] as u16) << 8) | body[at + 2 + index * 2] as u16 : body[at + 1 + index] as u16;
|
||||||
|
this.quant[place * 64 + zigzag[index]] = value;
|
||||||
|
}
|
||||||
|
at += 1 + size;
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
# Reads a scan's header, then its data, into the coefficients of its components.
|
||||||
|
def decoder::read_scan(&mut this): result<void, image_error> {
|
||||||
|
val body := this.segment() else { return image_error::malformed; };
|
||||||
|
if body.length < 1 {
|
||||||
|
return image_error::malformed;
|
||||||
|
}
|
||||||
|
var scan := scan_of { count = body[0] as u64 };
|
||||||
|
if scan.count == 0 || scan.count > 4 || body.length < 4 + scan.count * 2 {
|
||||||
|
return image_error::malformed;
|
||||||
|
}
|
||||||
|
for index in 0..scan.count {
|
||||||
|
val id := body[1 + index * 2];
|
||||||
|
val tables := body[2 + index * 2];
|
||||||
|
var found := false;
|
||||||
|
for which in 0..this.components.length {
|
||||||
|
if this.components[which].id == id {
|
||||||
|
scan.which[index] = which;
|
||||||
|
this.components[which].dc = (tables >> 4) as u64;
|
||||||
|
this.components[which].ac = (tables & 15) as u64;
|
||||||
|
found = (tables >> 4) <= 3 && (tables & 15) <= 3;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !found {
|
||||||
|
return image_error::malformed;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
val after := 1 + scan.count * 2;
|
||||||
|
scan.start = body[after] as u64;
|
||||||
|
scan.end = body[after + 1] as u64;
|
||||||
|
scan.high = (body[after + 2] >> 4) as u32;
|
||||||
|
scan.low = (body[after + 2] & 15) as u32;
|
||||||
|
if this.progressive {
|
||||||
|
if scan.start > scan.end || scan.end > 63 || scan.low > 13 || (scan.start == 0 && scan.end != 0)
|
||||||
|
|| (scan.start != 0 && scan.count != 1) {
|
||||||
|
return image_error::malformed;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
scan.start = 0;
|
||||||
|
scan.end = 63;
|
||||||
|
}
|
||||||
|
|
||||||
|
if !this.decode_scan(&scan) {
|
||||||
|
return image_error::malformed;
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
@@ -0,0 +1,100 @@
|
|||||||
|
#! Contains the planes of samples JPEG's encoder codes: an image's luminance and
|
||||||
|
#! chrominance, as libjpeg makes them of RGB, or its gray alone, each padded to
|
||||||
|
#! whole MCUs by its last column and row repeated, its chrominance averaged
|
||||||
|
#! down where it's subsampled, as libjpeg averages it.
|
||||||
|
|
||||||
|
module malunal::image::jpeg;
|
||||||
|
|
||||||
|
|
||||||
|
# A plane of samples, `width` a row.
|
||||||
|
struct plane {
|
||||||
|
var samples: vector<u8>;
|
||||||
|
var width: u64;
|
||||||
|
var height: u64;
|
||||||
|
}
|
||||||
|
|
||||||
|
# The planes of an image: its luminance, and its chrominance, blue's and red's,
|
||||||
|
# which a gray image has none of.
|
||||||
|
struct planes {
|
||||||
|
var luma: plane;
|
||||||
|
var blue: plane;
|
||||||
|
var red: plane;
|
||||||
|
}
|
||||||
|
|
||||||
|
def plane::of(width: u64, height: u64): plane {
|
||||||
|
var made := plane { samples = vector::<u8>::new(), width = width, height = height };
|
||||||
|
made.samples.resize(width * height);
|
||||||
|
return made;
|
||||||
|
}
|
||||||
|
|
||||||
|
# Whether every pixel of an image is gray, its red, green, and blue the same.
|
||||||
|
def is_gray(picture: &image): bool {
|
||||||
|
val pixels := picture.pixels.span;
|
||||||
|
var at: u64 = 0;
|
||||||
|
while at < pixels.length {
|
||||||
|
if pixels[at] != pixels[at + 1] || pixels[at] != pixels[at + 2] {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
at += 4;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
# The planes of an image, as wide and high as a number of samples, past its own
|
||||||
|
# width and height its last column and row repeated: gray alone, as its red is,
|
||||||
|
# or its Y, Cb, and Cr, as JFIF makes them of RGB, with libjpeg's constants.
|
||||||
|
def planes_of(picture: &image, gray: bool, width: u64, height: u64): planes {
|
||||||
|
val chroma_width := gray ? 0u : width;
|
||||||
|
val chroma_height := gray ? 0u : height;
|
||||||
|
var made := planes {
|
||||||
|
luma = plane::of(width, height),
|
||||||
|
blue = plane::of(chroma_width, chroma_height),
|
||||||
|
red = plane::of(chroma_width, chroma_height)
|
||||||
|
};
|
||||||
|
val pixels := picture.pixels.span;
|
||||||
|
val last_x := (picture.width - 1) as u64;
|
||||||
|
val last_y := (picture.height - 1) as u64;
|
||||||
|
for y in 0..height {
|
||||||
|
val row := (y < last_y ? y : last_y) * (picture.width as u64);
|
||||||
|
for x in 0..width {
|
||||||
|
val at := (row + (x < last_x ? x : last_x)) * 4;
|
||||||
|
val out := y * width + x;
|
||||||
|
if gray {
|
||||||
|
made.luma.samples[out] = pixels[at];
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
val r := pixels[at] as i32;
|
||||||
|
val g := pixels[at + 1] as i32;
|
||||||
|
val b := pixels[at + 2] as i32;
|
||||||
|
made.luma.samples[out] = ((19595 * r + 38470 * g + 7471 * b + 32768) >> 16) as u8;
|
||||||
|
made.blue.samples[out] = ((-11059 * r - 21709 * g + 32768 * b + 8388608 + 32767) >> 16) as u8;
|
||||||
|
made.red.samples[out] = ((32768 * r - 27439 * g - 5329 * b + 8388608 + 32767) >> 16) as u8;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return made;
|
||||||
|
}
|
||||||
|
|
||||||
|
# A plane averaged down by half across, and by half down or not, as libjpeg's
|
||||||
|
# `h2v1_downsample` and `h2v2_downsample` do: each sample the mean of those it
|
||||||
|
# stands for, rounded up and down by turns, so none drifts.
|
||||||
|
def averaged(from: &plane, across: u64, down: u64): plane {
|
||||||
|
var made := plane::of(from.width / across, from.height / down);
|
||||||
|
val samples := from.samples.span;
|
||||||
|
for y in 0..made.height {
|
||||||
|
val top := y * down * from.width;
|
||||||
|
val bottom := top + (down - 1) * from.width;
|
||||||
|
for x in 0..made.width {
|
||||||
|
val left := x * across;
|
||||||
|
var sum: u32 = 0;
|
||||||
|
if down == 1 {
|
||||||
|
sum = samples[top + left] as u32 + samples[top + left + 1] as u32 + (x % 2) as u32;
|
||||||
|
made.samples[y * made.width + x] = (sum >> 1) as u8;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
sum = samples[top + left] as u32 + samples[top + left + 1] as u32
|
||||||
|
+ samples[bottom + left] as u32 + samples[bottom + left + 1] as u32 + (x % 2 == 0 ? 1 : 2);
|
||||||
|
made.samples[y * made.width + x] = (sum >> 2) as u8;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return made;
|
||||||
|
}
|
||||||
@@ -0,0 +1,248 @@
|
|||||||
|
#! Contains a scan's data decoded into its components' coefficients, block by
|
||||||
|
#! block: a sequential scan's whole, and a progressive one's, its DC and bands
|
||||||
|
#! of AC coefficients a few bits at a time.
|
||||||
|
|
||||||
|
module malunal::image::jpeg;
|
||||||
|
|
||||||
|
|
||||||
|
# Decodes a scan's data, block by block: an interleaved scan's by MCU, each of its
|
||||||
|
# components' blocks in turn, and a scan of one component's by its blocks alone.
|
||||||
|
def decoder::decode_scan(&mut this, scan: &scan_of): bool {
|
||||||
|
# The tables the scan reads, copied out of the decoder, which the blocks then
|
||||||
|
# don't borrow.
|
||||||
|
val dc_tables := this.dc_tables;
|
||||||
|
val ac_tables := this.ac_tables;
|
||||||
|
val progressive := this.progressive;
|
||||||
|
val restart := this.restart;
|
||||||
|
var bits := bit_reader { data = this.data, at = this.at };
|
||||||
|
var eob_run: u32 = 0;
|
||||||
|
var left := restart;
|
||||||
|
for index in 0..scan.count {
|
||||||
|
this.components[scan.which[index]].prediction = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
var units_wide: u64 = this.mcus_wide as u64;
|
||||||
|
var units_high: u64 = this.mcus_high as u64;
|
||||||
|
if scan.count == 1 {
|
||||||
|
val alone := &this.components[scan.which[0]];
|
||||||
|
units_wide = ((alone.width + 7) / 8) as u64;
|
||||||
|
units_high = ((alone.height + 7) / 8) as u64;
|
||||||
|
}
|
||||||
|
|
||||||
|
var ended := false;
|
||||||
|
for unit_y in 0..units_high {
|
||||||
|
for unit_x in 0..units_wide {
|
||||||
|
for index in 0..scan.count {
|
||||||
|
val held := &mut this.components[scan.which[index]];
|
||||||
|
val across: u64 = scan.count == 1 ? 1 : held.h as u64;
|
||||||
|
val down: u64 = scan.count == 1 ? 1 : held.v as u64;
|
||||||
|
for block_y in 0..down {
|
||||||
|
for block_x in 0..across {
|
||||||
|
val x := unit_x * across + block_x;
|
||||||
|
val y := unit_y * down + block_y;
|
||||||
|
val block := held.coefficients.slice[(y * held.blocks_wide as u64 + x) * 64:64];
|
||||||
|
val dc := &dc_tables[held.dc];
|
||||||
|
val ac := &ac_tables[held.ac];
|
||||||
|
var read := false;
|
||||||
|
if !progressive {
|
||||||
|
read = decode_block(&mut bits, dc, ac, block, &mut held.prediction);
|
||||||
|
} else if scan.start == 0 {
|
||||||
|
read = scan.high == 0 ? decode_dc_first(&mut bits, dc, block, &mut held.prediction, scan.low)
|
||||||
|
: decode_dc_refine(&mut bits, block, scan.low);
|
||||||
|
} else {
|
||||||
|
read = scan.high == 0 ? decode_ac_first(&mut bits, ac, block, scan, &mut eob_run)
|
||||||
|
: decode_ac_refine(&mut bits, ac, block, scan, &mut eob_run);
|
||||||
|
}
|
||||||
|
if !read {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
# After each interval, a restart marker sets the predictions and bits anew;
|
||||||
|
# any other marker ends the scan early.
|
||||||
|
if restart != 0 {
|
||||||
|
left--;
|
||||||
|
if left == 0 {
|
||||||
|
bits.fill();
|
||||||
|
if bits.marker < 0xD0 || bits.marker > 0xD7 {
|
||||||
|
ended = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
bits.marker = 0;
|
||||||
|
bits.buffer = 0;
|
||||||
|
bits.count = 0;
|
||||||
|
eob_run = 0;
|
||||||
|
left = restart;
|
||||||
|
for index in 0..scan.count {
|
||||||
|
this.components[scan.which[index]].prediction = 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if ended {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
# The data's end is the marker the bits stopped at, or the next one after.
|
||||||
|
this.at = bits.at;
|
||||||
|
this.marker = bits.marker;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
# Decodes a block of a sequential scan: its DC coefficient's difference from the
|
||||||
|
# last, then its AC coefficients, as runs of zeros and the value after each.
|
||||||
|
def decode_block(bits: &mut bit_reader, dc: &huffman, ac: &huffman, block: slice<i16>, prediction: &mut i32): bool {
|
||||||
|
val size := bits.decode(dc);
|
||||||
|
if size < 0 || size > 16 {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
prediction += size == 0 ? 0 : bits.extend(size as u32);
|
||||||
|
block[0] = prediction as i16;
|
||||||
|
|
||||||
|
var at: u64 = 1;
|
||||||
|
while at < 64 {
|
||||||
|
val run_size := bits.decode(ac);
|
||||||
|
if run_size < 0 {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
val value_size := (run_size & 15) as u32;
|
||||||
|
val run := (run_size >> 4) as u64;
|
||||||
|
if value_size == 0 {
|
||||||
|
if run_size != 0xF0 {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
at += 16;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
at += run;
|
||||||
|
if at > 63 {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
block[zigzag[at]] = bits.extend(value_size) as i16;
|
||||||
|
at++;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
# Decodes the first bits of a block's DC coefficient, in a progressive scan.
|
||||||
|
def decode_dc_first(bits: &mut bit_reader, dc: &huffman, block: slice<i16>, prediction: &mut i32, low: u32): bool {
|
||||||
|
val size := bits.decode(dc);
|
||||||
|
if size < 0 || size > 16 {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
prediction += size == 0 ? 0 : bits.extend(size as u32);
|
||||||
|
block[0] = (prediction * (1 << low)) as i16;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
# Decodes a bit more of a block's DC coefficient.
|
||||||
|
def decode_dc_refine(bits: &mut bit_reader, block: slice<i16>, low: u32): bool {
|
||||||
|
if bits.take(1) != 0 {
|
||||||
|
block[0] = block[0] + (1 << low) as i16;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
# Decodes the first bits of a band of a block's AC coefficients, or counts down
|
||||||
|
# a run of blocks with none.
|
||||||
|
def decode_ac_first(bits: &mut bit_reader, ac: &huffman, block: slice<i16>, scan: &scan_of, eob_run: &mut u32): bool {
|
||||||
|
if eob_run > 0 {
|
||||||
|
eob_run--;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
var at := scan.start;
|
||||||
|
while at <= scan.end {
|
||||||
|
val run_size := bits.decode(ac);
|
||||||
|
if run_size < 0 {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
val value_size := (run_size & 15) as u32;
|
||||||
|
val run := (run_size >> 4) as u32;
|
||||||
|
if value_size == 0 {
|
||||||
|
if run < 15 {
|
||||||
|
eob_run = (1 as u32) << run;
|
||||||
|
if run != 0 {
|
||||||
|
eob_run += bits.take(run);
|
||||||
|
}
|
||||||
|
eob_run--;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
at += 16;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
at += run as u64;
|
||||||
|
if at > 63 {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
block[zigzag[at]] = (bits.extend(value_size) * (1 << scan.low)) as i16;
|
||||||
|
at++;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
# Decodes a bit more of a band of a block's AC coefficients: a bit of each that
|
||||||
|
# is not zero, and those that become so, as stb_image does.
|
||||||
|
def decode_ac_refine(bits: &mut bit_reader, ac: &huffman, block: slice<i16>, scan: &scan_of, eob_run: &mut u32): bool {
|
||||||
|
val bit := (1 << scan.low) as i16;
|
||||||
|
if eob_run > 0 {
|
||||||
|
eob_run--;
|
||||||
|
for at in scan.start..=scan.end {
|
||||||
|
refine(bits, block, zigzag[at], bit);
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
var at := scan.start;
|
||||||
|
while at <= scan.end {
|
||||||
|
val run_size := bits.decode(ac);
|
||||||
|
if run_size < 0 {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
val value_size := run_size & 15;
|
||||||
|
var run := (run_size >> 4) as u32;
|
||||||
|
var value: i16 = 0;
|
||||||
|
if value_size == 0 {
|
||||||
|
if run < 15 {
|
||||||
|
eob_run = ((1 as u32) << run) - 1;
|
||||||
|
if run != 0 {
|
||||||
|
eob_run += bits.take(run);
|
||||||
|
}
|
||||||
|
run = 64;
|
||||||
|
}
|
||||||
|
# Otherwise sixteen zeros: fifteen passed, and a zero set.
|
||||||
|
} else {
|
||||||
|
if value_size != 1 {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
value = bits.take(1) != 0 ? bit : -bit;
|
||||||
|
}
|
||||||
|
|
||||||
|
# Past as many zeros as the run says, refining those that aren't on the way,
|
||||||
|
# then the value is set at the next zero.
|
||||||
|
while at <= scan.end {
|
||||||
|
val natural := zigzag[at];
|
||||||
|
at++;
|
||||||
|
if block[natural] != 0 {
|
||||||
|
refine(bits, block, natural, bit);
|
||||||
|
} else {
|
||||||
|
if run == 0 {
|
||||||
|
block[natural] = value;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
run--;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
# Adds a bit to a coefficient that's not zero, away from zero, where it's set.
|
||||||
|
def refine(bits: &mut bit_reader, block: slice<i16>, natural: u64, bit: i16): void {
|
||||||
|
val held := block[natural];
|
||||||
|
if held != 0 && bits.take(1) != 0 && (held & bit) == 0 {
|
||||||
|
block[natural] = held > 0 ? held + bit : held - bit;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,81 @@
|
|||||||
|
#! Contains the tables JPEG's encoder writes with, as Annex K of the standard
|
||||||
|
#! gives them, and libjpeg writes them: the quantization tables of luminance and
|
||||||
|
#! chrominance, which quality scales, and the Huffman tables of each one's DC and
|
||||||
|
#! AC coefficients.
|
||||||
|
|
||||||
|
module malunal::image::jpeg;
|
||||||
|
|
||||||
|
|
||||||
|
# The quantization tables, of quality 50, in natural order.
|
||||||
|
const luminance_quantization: u16[64] = [
|
||||||
|
16, 11, 10, 16, 24, 40, 51, 61,
|
||||||
|
12, 12, 14, 19, 26, 58, 60, 55,
|
||||||
|
14, 13, 16, 24, 40, 57, 69, 56,
|
||||||
|
14, 17, 22, 29, 51, 87, 80, 62,
|
||||||
|
18, 22, 37, 56, 68, 109, 103, 77,
|
||||||
|
24, 35, 55, 64, 81, 104, 113, 92,
|
||||||
|
49, 64, 78, 87, 103, 121, 120, 101,
|
||||||
|
72, 92, 95, 98, 112, 100, 103, 99,
|
||||||
|
];
|
||||||
|
|
||||||
|
const chrominance_quantization: u16[64] = [
|
||||||
|
17, 18, 24, 47, 99, 99, 99, 99,
|
||||||
|
18, 21, 26, 66, 99, 99, 99, 99,
|
||||||
|
24, 26, 56, 99, 99, 99, 99, 99,
|
||||||
|
47, 66, 99, 99, 99, 99, 99, 99,
|
||||||
|
99, 99, 99, 99, 99, 99, 99, 99,
|
||||||
|
99, 99, 99, 99, 99, 99, 99, 99,
|
||||||
|
99, 99, 99, 99, 99, 99, 99, 99,
|
||||||
|
99, 99, 99, 99, 99, 99, 99, 99,
|
||||||
|
];
|
||||||
|
|
||||||
|
# The Huffman tables: how many codes there are of each length, from 1 to 16, and
|
||||||
|
# the values of them in order. A DC coefficient's value is how many bits its
|
||||||
|
# difference takes; an AC one's, the zeros before it, then how many bits it takes.
|
||||||
|
const dc_luminance_counts: u8[16] = [0, 1, 5, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0];
|
||||||
|
const dc_luminance_values: u8[12] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];
|
||||||
|
|
||||||
|
const dc_chrominance_counts: u8[16] = [0, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0];
|
||||||
|
const dc_chrominance_values: u8[12] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];
|
||||||
|
|
||||||
|
const ac_luminance_counts: u8[16] = [0, 2, 1, 3, 3, 2, 4, 3, 5, 5, 4, 4, 0, 0, 1, 0x7D];
|
||||||
|
const ac_luminance_values: u8[162] = [
|
||||||
|
0x01, 0x02, 0x03, 0x00, 0x04, 0x11, 0x05, 0x12, 0x21, 0x31, 0x41, 0x06, 0x13, 0x51, 0x61, 0x07,
|
||||||
|
0x22, 0x71, 0x14, 0x32, 0x81, 0x91, 0xA1, 0x08, 0x23, 0x42, 0xB1, 0xC1, 0x15, 0x52, 0xD1, 0xF0,
|
||||||
|
0x24, 0x33, 0x62, 0x72, 0x82, 0x09, 0x0A, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x25, 0x26, 0x27, 0x28,
|
||||||
|
0x29, 0x2A, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3A, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49,
|
||||||
|
0x4A, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5A, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69,
|
||||||
|
0x6A, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7A, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89,
|
||||||
|
0x8A, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9A, 0xA2, 0xA3, 0xA4, 0xA5, 0xA6, 0xA7,
|
||||||
|
0xA8, 0xA9, 0xAA, 0xB2, 0xB3, 0xB4, 0xB5, 0xB6, 0xB7, 0xB8, 0xB9, 0xBA, 0xC2, 0xC3, 0xC4, 0xC5,
|
||||||
|
0xC6, 0xC7, 0xC8, 0xC9, 0xCA, 0xD2, 0xD3, 0xD4, 0xD5, 0xD6, 0xD7, 0xD8, 0xD9, 0xDA, 0xE1, 0xE2,
|
||||||
|
0xE3, 0xE4, 0xE5, 0xE6, 0xE7, 0xE8, 0xE9, 0xEA, 0xF1, 0xF2, 0xF3, 0xF4, 0xF5, 0xF6, 0xF7, 0xF8,
|
||||||
|
0xF9, 0xFA,
|
||||||
|
];
|
||||||
|
|
||||||
|
const ac_chrominance_counts: u8[16] = [0, 2, 1, 2, 4, 4, 3, 4, 7, 5, 4, 4, 0, 1, 2, 0x77];
|
||||||
|
const ac_chrominance_values: u8[162] = [
|
||||||
|
0x00, 0x01, 0x02, 0x03, 0x11, 0x04, 0x05, 0x21, 0x31, 0x06, 0x12, 0x41, 0x51, 0x07, 0x61, 0x71,
|
||||||
|
0x13, 0x22, 0x32, 0x81, 0x08, 0x14, 0x42, 0x91, 0xA1, 0xB1, 0xC1, 0x09, 0x23, 0x33, 0x52, 0xF0,
|
||||||
|
0x15, 0x62, 0x72, 0xD1, 0x0A, 0x16, 0x24, 0x34, 0xE1, 0x25, 0xF1, 0x17, 0x18, 0x19, 0x1A, 0x26,
|
||||||
|
0x27, 0x28, 0x29, 0x2A, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3A, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48,
|
||||||
|
0x49, 0x4A, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5A, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68,
|
||||||
|
0x69, 0x6A, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7A, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
|
||||||
|
0x88, 0x89, 0x8A, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9A, 0xA2, 0xA3, 0xA4, 0xA5,
|
||||||
|
0xA6, 0xA7, 0xA8, 0xA9, 0xAA, 0xB2, 0xB3, 0xB4, 0xB5, 0xB6, 0xB7, 0xB8, 0xB9, 0xBA, 0xC2, 0xC3,
|
||||||
|
0xC4, 0xC5, 0xC6, 0xC7, 0xC8, 0xC9, 0xCA, 0xD2, 0xD3, 0xD4, 0xD5, 0xD6, 0xD7, 0xD8, 0xD9, 0xDA,
|
||||||
|
0xE2, 0xE3, 0xE4, 0xE5, 0xE6, 0xE7, 0xE8, 0xE9, 0xEA, 0xF2, 0xF3, 0xF4, 0xF5, 0xF6, 0xF7, 0xF8,
|
||||||
|
0xF9, 0xFA,
|
||||||
|
];
|
||||||
|
|
||||||
|
# A quantization table of a quality, from 1 to 100, as libjpeg scales one:
|
||||||
|
# quality 50 is the table itself, those below it larger, and those above it
|
||||||
|
# smaller, to 1 at 100, each no more than 255, as baseline JPEG holds.
|
||||||
|
def scaled(table: span<u16>, quality: u32, into: slice<u16>): void {
|
||||||
|
val clamped := quality < 1 ? 1 : (quality > 100 ? 100 : quality);
|
||||||
|
val scale: u32 = clamped < 50 ? 5000 / clamped : 200 - clamped * 2;
|
||||||
|
for index in 0u..64u {
|
||||||
|
val value := (table[index] as u32 * scale + 50) / 100;
|
||||||
|
into[index] = (value < 1 ? 1 : (value > 255 ? 255 : value)) as u16;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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 malunal::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]++;
|
||||||
|
}
|
||||||
@@ -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 malunal::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;
|
||||||
|
}
|
||||||
@@ -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 malunal::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.span;
|
||||||
|
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;
|
||||||
|
}
|
||||||
@@ -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 malunal::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.span;
|
||||||
|
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;
|
||||||
|
}
|
||||||
@@ -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 malunal::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.span, above.span, 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.span);
|
||||||
|
if !alphas.empty {
|
||||||
|
chunk(&mut out, "tRNS", alphas.span);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
val compressed := deflate(raw.span, given.level);
|
||||||
|
chunk(&mut out, "IDAT", compressed.span);
|
||||||
|
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.span[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;
|
||||||
|
}
|
||||||
@@ -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 malunal::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;
|
||||||
|
}
|
||||||
@@ -0,0 +1,105 @@
|
|||||||
|
#! Contains PNG's header, and the chunks that say what its pixels' samples are:
|
||||||
|
#! `IHDR`, `PLTE`, and `tRNS`.
|
||||||
|
|
||||||
|
module malunal::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;
|
||||||
|
}
|
||||||
@@ -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 malunal::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);
|
||||||
|
}
|
||||||
@@ -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 malunal::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;
|
||||||
|
}
|
||||||
@@ -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 malunal::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.span;
|
||||||
|
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;
|
||||||
|
}
|
||||||
@@ -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 malunal::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.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.span, 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.span[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;
|
||||||
|
}
|
||||||
@@ -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 malunal::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;
|
||||||
|
}
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
#! Contains reading an image, from bytes or a file, in whichever format the
|
||||||
|
#! bytes are in, as their first few say.
|
||||||
|
|
||||||
|
import std::io;
|
||||||
|
module malunal::image;
|
||||||
|
|
||||||
|
|
||||||
|
#! Reads an image from bytes in any of the formats, which their first few say.
|
||||||
|
#! @param bytes The bytes.
|
||||||
|
#! @param size The size to draw an SVG at.
|
||||||
|
#! @returns The image, or why it couldn't be read.
|
||||||
|
pub def decode(bytes: span<u8>, size: svg_size = svg_size {}): result<image, image_error> {
|
||||||
|
val which := format_of(bytes) else { return image_error::unrecognized; };
|
||||||
|
return match which {
|
||||||
|
png => image::png::decode(bytes),
|
||||||
|
jpeg => image::jpeg::decode(bytes),
|
||||||
|
svg => image::svg::render(bytes, size),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
#! Reads an image from a file in any of the formats.
|
||||||
|
#! @param at The file's path.
|
||||||
|
#! @param size The size to draw an SVG at.
|
||||||
|
#! @returns The image, or why it couldn't be read: `unreadable` where the file
|
||||||
|
#! couldn't be.
|
||||||
|
pub def load(at: &path, size: svg_size = svg_size {}): result<image, image_error> {
|
||||||
|
val bytes := io::read_file(at) else (_) { return image_error::unreadable; };
|
||||||
|
return decode(bytes.span, size);
|
||||||
|
}
|
||||||
|
|
||||||
|
#! Reads an image from a file named by text, as `load` does.
|
||||||
|
#! @param at The file's path, as text.
|
||||||
|
#! @param size The size to draw an SVG at.
|
||||||
|
#! @returns The image, or why it couldn't be read.
|
||||||
|
pub def load(at: strview, size: svg_size = svg_size {}): result<image, image_error> {
|
||||||
|
val named := path::parse(at) else (_) { return image_error::unreadable; };
|
||||||
|
return load(&named, size);
|
||||||
|
}
|
||||||
@@ -0,0 +1,62 @@
|
|||||||
|
#! Contains the canvas: its pixels, and the layers drawn apart before they're
|
||||||
|
#! composited onto it, as a group with opacity, a clip, or a mask is, each of
|
||||||
|
#! premultiplied RGBA.
|
||||||
|
|
||||||
|
module malunal::image::svg;
|
||||||
|
|
||||||
|
|
||||||
|
# The canvas: its pixels, and the layers drawn apart before they're composited
|
||||||
|
# onto it, as a group with opacity, a clip, or a mask is, each premultiplied.
|
||||||
|
struct canvas {
|
||||||
|
var width: u64;
|
||||||
|
var height: u64;
|
||||||
|
var layers: vector<vector<u8>>;
|
||||||
|
var raster: raster;
|
||||||
|
}
|
||||||
|
|
||||||
|
def canvas::new(width: u64, height: u64): canvas {
|
||||||
|
var made := canvas { width = width, height = height, layers = vector::<vector<u8>>::new(), raster = raster::new(width, height) };
|
||||||
|
made.push();
|
||||||
|
return made;
|
||||||
|
}
|
||||||
|
|
||||||
|
# Begins a layer, clear, which what's drawn goes onto until it's popped.
|
||||||
|
def canvas::push(&mut this): void {
|
||||||
|
var layer := vector::<u8>::new();
|
||||||
|
layer.resize(this.width * this.height * 4);
|
||||||
|
this.layers.append(move(layer));
|
||||||
|
}
|
||||||
|
|
||||||
|
# Takes the top layer off.
|
||||||
|
def canvas::pop(&mut this): vector<u8> {
|
||||||
|
var taken := move(this.layers.last);
|
||||||
|
this.layers.truncate();
|
||||||
|
return taken;
|
||||||
|
}
|
||||||
|
|
||||||
|
def canvas::fill(&mut this, shape: &outline, even_odd: bool, paint: &painter): void {
|
||||||
|
val target := this.layers.last.slice;
|
||||||
|
this.raster.fill(shape, even_odd, paint, target);
|
||||||
|
}
|
||||||
|
|
||||||
|
# Draws a layer over the top one, scaled by an opacity, and by a mask's alpha,
|
||||||
|
# or its luminance, where there is one.
|
||||||
|
def canvas::composite(&mut this, layer: span<u8>, opacity: f64, mask: span<u8>, luminance: bool): void {
|
||||||
|
val target := this.layers.last.slice;
|
||||||
|
val scale := opacity as f32 / 255;
|
||||||
|
var at: u64 = 0;
|
||||||
|
while at < layer.length {
|
||||||
|
if layer[at + 3] != 0 {
|
||||||
|
var factor := scale;
|
||||||
|
if mask.length != 0 {
|
||||||
|
val masked: f32 = luminance
|
||||||
|
? mask[at] as f32 * 0.2125 + mask[at + 1] as f32 * 0.7154 + mask[at + 2] as f32 * 0.0721
|
||||||
|
: mask[at + 3] as f32;
|
||||||
|
factor *= masked / 255;
|
||||||
|
}
|
||||||
|
val color: f32[4] = [layer[at] as f32 * factor, layer[at + 1] as f32 * factor, layer[at + 2] as f32 * factor, layer[at + 3] as f32 * factor];
|
||||||
|
blend(target, at, color, 1);
|
||||||
|
}
|
||||||
|
at += 4;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,156 @@
|
|||||||
|
#! Contains colors, as CSS writes them: by name, by hexadecimal digits, and by
|
||||||
|
#! `rgb()`, `rgba()`, `hsl()`, and `hsla()`.
|
||||||
|
|
||||||
|
import std::math;
|
||||||
|
module malunal::image::svg;
|
||||||
|
|
||||||
|
|
||||||
|
# A color, each channel from 0 to 1, its alpha straight.
|
||||||
|
struct color {
|
||||||
|
var r: f64;
|
||||||
|
var g: f64;
|
||||||
|
var b: f64;
|
||||||
|
var a: f64 = 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
# Reads a color as CSS writes one: by name, `#` and 3, 4, 6, or 8 hexadecimal
|
||||||
|
# digits, `rgb()` and `rgba()`, or `hsl()` and `hsla()`.
|
||||||
|
def parse_color(text: strview): maybe<color> {
|
||||||
|
val trimmed := text.trim();
|
||||||
|
if trimmed.length == 0 {
|
||||||
|
return nothing {};
|
||||||
|
}
|
||||||
|
if trimmed[0] == '#' {
|
||||||
|
return hex_color(trimmed.substr(1, trimmed.length - 1));
|
||||||
|
}
|
||||||
|
val open := trimmed.find("(");
|
||||||
|
if open is some(paren) {
|
||||||
|
if trimmed[trimmed.length - 1] != ')' {
|
||||||
|
return nothing {};
|
||||||
|
}
|
||||||
|
val name := trimmed.substr(0, paren).trim().lower();
|
||||||
|
val inside := trimmed.substr(paren + 1, trimmed.length - paren - 2);
|
||||||
|
if name.span == "rgb" || name.span == "rgba" {
|
||||||
|
return functional_color(inside, false);
|
||||||
|
}
|
||||||
|
if name.span == "hsl" || name.span == "hsla" {
|
||||||
|
return functional_color(inside, true);
|
||||||
|
}
|
||||||
|
return nothing {};
|
||||||
|
}
|
||||||
|
|
||||||
|
val name := trimmed.lower();
|
||||||
|
if name.span == "transparent" {
|
||||||
|
return color { a = 0 };
|
||||||
|
}
|
||||||
|
for &each in named_colors {
|
||||||
|
if each.name == name.span {
|
||||||
|
return color {
|
||||||
|
r = ((each.rgb >> 16) & 0xFF) as f64 / 255,
|
||||||
|
g = ((each.rgb >> 8) & 0xFF) as f64 / 255,
|
||||||
|
b = (each.rgb & 0xFF) as f64 / 255
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nothing {};
|
||||||
|
}
|
||||||
|
|
||||||
|
def hex_color(digits: strview): maybe<color> {
|
||||||
|
for byte in digits {
|
||||||
|
if !byte.is_hex {
|
||||||
|
return nothing {};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
var values: f64[4] = [0, 0, 0, 1];
|
||||||
|
if digits.length == 3 || digits.length == 4 {
|
||||||
|
for index in 0..digits.length {
|
||||||
|
values[index] = (digits[index].digit_value * 17) as f64 / 255;
|
||||||
|
}
|
||||||
|
} else if digits.length == 6 || digits.length == 8 {
|
||||||
|
for index in 0..digits.length / 2 {
|
||||||
|
values[index] = (digits[index * 2].digit_value * 16 + digits[index * 2 + 1].digit_value) as f64 / 255;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
return nothing {};
|
||||||
|
}
|
||||||
|
return color { r = values[0], g = values[1], b = values[2], a = values[3] };
|
||||||
|
}
|
||||||
|
|
||||||
|
# Reads what's within `rgb()` or `hsl()`: three values, then perhaps an alpha,
|
||||||
|
# split by commas, spaces, or a `/` before the alpha.
|
||||||
|
def functional_color(inside: strview, hsl: bool): maybe<color> {
|
||||||
|
var values: f64[4] = [0, 0, 0, 1];
|
||||||
|
var count: u64 = 0;
|
||||||
|
var at: u64 = 0;
|
||||||
|
while at < inside.length {
|
||||||
|
val byte := inside[at];
|
||||||
|
if byte.is_space || byte == ',' || byte == '/' {
|
||||||
|
at++;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if count >= 4 {
|
||||||
|
return nothing {};
|
||||||
|
}
|
||||||
|
val read := number_at(inside, at) else { return nothing {}; };
|
||||||
|
at = read.end;
|
||||||
|
var value := read.value;
|
||||||
|
val percent := at < inside.length && inside[at] == '%';
|
||||||
|
if percent {
|
||||||
|
at++;
|
||||||
|
}
|
||||||
|
if count == 3 {
|
||||||
|
value = percent ? value / 100 : value;
|
||||||
|
} else if hsl {
|
||||||
|
value = count == 0 ? value : value / 100;
|
||||||
|
} else {
|
||||||
|
value = percent ? value / 100 : value / 255;
|
||||||
|
}
|
||||||
|
values[count] = value;
|
||||||
|
count++;
|
||||||
|
}
|
||||||
|
if count < 3 {
|
||||||
|
return nothing {};
|
||||||
|
}
|
||||||
|
val alpha := math::clamp(values[3], 0.0, 1.0);
|
||||||
|
if !hsl {
|
||||||
|
return color {
|
||||||
|
r = math::clamp(values[0], 0.0, 1.0),
|
||||||
|
g = math::clamp(values[1], 0.0, 1.0),
|
||||||
|
b = math::clamp(values[2], 0.0, 1.0),
|
||||||
|
a = alpha
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
# Hue, saturation, and lightness, as CSS makes them RGB.
|
||||||
|
val hue := (values[0] % 360 + 360) % 360 / 360;
|
||||||
|
val saturation := math::clamp(values[1], 0.0, 1.0);
|
||||||
|
val lightness := math::clamp(values[2], 0.0, 1.0);
|
||||||
|
val high := lightness <= 0.5 ? lightness * (saturation + 1) : lightness + saturation - lightness * saturation;
|
||||||
|
val low := lightness * 2 - high;
|
||||||
|
return color {
|
||||||
|
r = hue_channel(low, high, hue + 1.0 / 3),
|
||||||
|
g = hue_channel(low, high, hue),
|
||||||
|
b = hue_channel(low, high, hue - 1.0 / 3),
|
||||||
|
a = alpha
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
def hue_channel(low: f64, high: f64, given: f64): f64 {
|
||||||
|
var hue := given;
|
||||||
|
if hue < 0 {
|
||||||
|
hue += 1;
|
||||||
|
}
|
||||||
|
if hue > 1 {
|
||||||
|
hue -= 1;
|
||||||
|
}
|
||||||
|
if hue * 6 < 1 {
|
||||||
|
return low + (high - low) * hue * 6;
|
||||||
|
}
|
||||||
|
if hue * 2 < 1 {
|
||||||
|
return high;
|
||||||
|
}
|
||||||
|
if hue * 3 < 2 {
|
||||||
|
return low + (high - low) * (2.0 / 3 - hue) * 6;
|
||||||
|
}
|
||||||
|
return low;
|
||||||
|
}
|
||||||
@@ -0,0 +1,170 @@
|
|||||||
|
#! Contains the document walked: every ID found and each style sheet read, then
|
||||||
|
#! each element drawn in its user space, in its style, those with opacity, a
|
||||||
|
#! clip, or a mask on a layer of their own.
|
||||||
|
|
||||||
|
import std::xml;
|
||||||
|
module malunal::image::svg;
|
||||||
|
|
||||||
|
|
||||||
|
# Finds every element's ID, the first of each kept, and reads each style sheet.
|
||||||
|
def renderer::index(&mut this, at: &xml::element): void {
|
||||||
|
if at.attribute("id") is some(id) {
|
||||||
|
_ = this.ids.insert(id, copy(at));
|
||||||
|
}
|
||||||
|
if at.local == "style" && is_svg(at) {
|
||||||
|
val kind := at.attribute("type") else "text/css";
|
||||||
|
if kind.length == 0 || kind == "text/css" {
|
||||||
|
val text := at.text();
|
||||||
|
this.sheet.add(text.span);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for child in at.elements() {
|
||||||
|
this.index(&child);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
# The style of an element: its presentation attributes, then the rules matching
|
||||||
|
# it, then its `style` attribute, over what it inherits.
|
||||||
|
def renderer::style_of(&this, at: &xml::element, parent: &style): style {
|
||||||
|
var made := parent.inherited();
|
||||||
|
for each in at.attributes() {
|
||||||
|
if each.namespace.length == 0 && is_presentation(each.local) {
|
||||||
|
made.set(each.local, each.value, parent, &this.view);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
this.sheet.apply(at, &mut made, parent, &this.view);
|
||||||
|
if at.attribute("style") is some(declared) {
|
||||||
|
made.declare(declared, parent, &this.view);
|
||||||
|
}
|
||||||
|
return made;
|
||||||
|
}
|
||||||
|
|
||||||
|
# Draws an element, and what it holds, in a user space.
|
||||||
|
def renderer::draw(&mut this, at: &xml::element, parent: &style, outer: &matrix): void {
|
||||||
|
if !is_svg(at) || this.depth >= deepest {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
val name := at.local;
|
||||||
|
for never in undrawn {
|
||||||
|
if name == never {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
val own := this.style_of(at, parent);
|
||||||
|
if !own.displayed {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
var placed := copy(outer);
|
||||||
|
if at.attribute("transform") is some(written) {
|
||||||
|
if parse_transform(written) is some(own_transform) {
|
||||||
|
placed = own_transform.then(outer);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
# A shape's opacity, where it's only filled or only stroked, scales its paint;
|
||||||
|
# anything else with opacity, a clip, or a mask is drawn on a layer of its own.
|
||||||
|
val shape := is_shape(name);
|
||||||
|
val painted_twice := own.fill.kind != paint_kind::none && own.stroke.kind != paint_kind::none && own.stroke_width > 0;
|
||||||
|
val clip := this.reference(own.clip_path, "clipPath");
|
||||||
|
val mask := this.reference(own.mask, "mask");
|
||||||
|
val layered := !this.clipping && ((own.opacity < 1 && (!shape || painted_twice)) || clip is some(_) || mask is some(_));
|
||||||
|
if layered {
|
||||||
|
this.canvas.push();
|
||||||
|
}
|
||||||
|
|
||||||
|
this.depth++;
|
||||||
|
var bounds: maybe<point[2]> = nothing {};
|
||||||
|
if shape {
|
||||||
|
bounds = this.shape(at, &own, &placed, layered ? 1.0 : own.opacity);
|
||||||
|
} else if name == "g" || name == "a" {
|
||||||
|
this.children(at, &own, &placed);
|
||||||
|
} else if name == "svg" {
|
||||||
|
if this.depth == 1 {
|
||||||
|
this.children(at, &own, &placed);
|
||||||
|
} else {
|
||||||
|
this.viewport(at, &own, &placed, at, nothing {}, nothing {});
|
||||||
|
}
|
||||||
|
} else if name == "use" {
|
||||||
|
this.use_element(at, &own, &placed);
|
||||||
|
} else if name == "switch" {
|
||||||
|
# The first child that would be drawn, its conditions taken as met.
|
||||||
|
for child in at.elements() {
|
||||||
|
if is_svg(&child) && (is_shape(child.local) || child.local == "g" || child.local == "svg" || child.local == "use") {
|
||||||
|
this.draw(&child, &own, &placed);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
this.depth--;
|
||||||
|
|
||||||
|
if !layered {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
var content := this.canvas.pop();
|
||||||
|
var masking := vector::<u8>::new();
|
||||||
|
if clip is some(clip_element) {
|
||||||
|
masking = this.clip_mask(&clip_element, &placed, bounds);
|
||||||
|
}
|
||||||
|
if mask is some(mask_element) {
|
||||||
|
var luminance := this.luminance_mask(&mask_element, &placed, bounds);
|
||||||
|
if masking.empty {
|
||||||
|
masking = move(luminance);
|
||||||
|
} else {
|
||||||
|
# Both: the clip's coverage times the mask's.
|
||||||
|
var at_pixel: u64 = 3;
|
||||||
|
while at_pixel < masking.length {
|
||||||
|
masking[at_pixel] = ((masking[at_pixel] as u32 * luminance[at_pixel] as u32 + 127) / 255) as u8;
|
||||||
|
at_pixel += 4;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
this.canvas.composite(content.span, own.opacity, masking.span, false);
|
||||||
|
}
|
||||||
|
|
||||||
|
def renderer::children(&mut this, at: &xml::element, own: &style, placed: &matrix): void {
|
||||||
|
for child in at.elements() {
|
||||||
|
this.draw(&child, own, placed);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
# The element an ID names, where it's of a kind.
|
||||||
|
def renderer::reference(&this, id: strview, kind: strview): maybe<xml::element> {
|
||||||
|
if id.length == 0 {
|
||||||
|
return nothing {};
|
||||||
|
}
|
||||||
|
val found := this.ids.get(&id) else { return nothing {}; };
|
||||||
|
if found.local != kind {
|
||||||
|
return nothing {};
|
||||||
|
}
|
||||||
|
return found;
|
||||||
|
}
|
||||||
|
|
||||||
|
# What an element refers to, by `xlink:href` or SVG 2's `href`, or empty.
|
||||||
|
def href_of(at: &xml::element): strview {
|
||||||
|
if at.attribute(xlink_namespace, "href") is some(linked) {
|
||||||
|
return linked;
|
||||||
|
}
|
||||||
|
return at.attribute("href") else "";
|
||||||
|
}
|
||||||
|
|
||||||
|
# Whether an element is SVG's: in its namespace, or in none, as SVG written
|
||||||
|
# without `xmlns` is.
|
||||||
|
def is_svg(at: &xml::element): bool {
|
||||||
|
val namespace := at.namespace;
|
||||||
|
return namespace.length == 0 || namespace == svg_namespace;
|
||||||
|
}
|
||||||
|
|
||||||
|
def is_shape(name: strview): bool {
|
||||||
|
return name == "path" || name == "rect" || name == "circle" || name == "ellipse" || name == "line"
|
||||||
|
|| name == "polyline" || name == "polygon";
|
||||||
|
}
|
||||||
|
|
||||||
|
def is_presentation(name: strview): bool {
|
||||||
|
for each in presentation {
|
||||||
|
if each == name {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
@@ -0,0 +1,184 @@
|
|||||||
|
#! Contains what paints a fill or a stroke: its color, or its gradient, linear
|
||||||
|
#! or radial, made of its attributes and stops and those of the gradients it
|
||||||
|
#! refers to by `href`, a table of its colors along it.
|
||||||
|
|
||||||
|
import std::math;
|
||||||
|
import std::xml;
|
||||||
|
module malunal::image::svg;
|
||||||
|
|
||||||
|
|
||||||
|
# What paints a fill or stroke: its color, or its gradient, scaled by an
|
||||||
|
# opacity, or `nothing` where it paints nothing.
|
||||||
|
def renderer::painter_for(&this, given: &paint, own: &style, opacity: f64, bounds: &point[2], placed: &matrix): maybe<painter> {
|
||||||
|
match given.kind {
|
||||||
|
none => return nothing {};
|
||||||
|
color => return painter::solid(&given.color, opacity);
|
||||||
|
current => return painter::solid(&own.color, opacity);
|
||||||
|
url => {
|
||||||
|
if this.ids.get(&given.url) is some(target) {
|
||||||
|
if target.local == "linearGradient" || target.local == "radialGradient" {
|
||||||
|
return this.gradient(&target, opacity, bounds, placed);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
# Where the gradient can't be found, what's given after it paints.
|
||||||
|
return match given.fallback {
|
||||||
|
color => painter::solid(&given.color, opacity),
|
||||||
|
current => painter::solid(&own.color, opacity),
|
||||||
|
else => nothing {},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nothing {};
|
||||||
|
}
|
||||||
|
|
||||||
|
# The painter of a gradient: its attributes, and its stops, from it or the
|
||||||
|
# gradients it refers to by `href`, the nearest giving each.
|
||||||
|
def renderer::gradient(&this, at: &xml::element, opacity: f64, bounds: &point[2], placed: &matrix): maybe<painter> {
|
||||||
|
var chain := vector::<xml::element>::new();
|
||||||
|
chain.append(copy(at));
|
||||||
|
while chain.length < 16 {
|
||||||
|
val href := href_of(&chain.last);
|
||||||
|
if !href.starts_with("#") {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
val id := href.substr(1, href.length - 1);
|
||||||
|
val next := this.ids.get(&id) else { break; };
|
||||||
|
if next.local != "linearGradient" && next.local != "radialGradient" {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
chain.append(next);
|
||||||
|
}
|
||||||
|
|
||||||
|
val radial := at.local == "radialGradient";
|
||||||
|
val user_space := attribute_of(&chain, "gradientUnits") is some(units) && units == "userSpaceOnUse";
|
||||||
|
var made := painter { by = radial ? paint_by::radial : paint_by::linear };
|
||||||
|
val spread_written := attribute_of(&chain, "spreadMethod") else "pad";
|
||||||
|
made.spread = spread_written == "reflect" ? spread::reflect : (spread_written == "repeat" ? spread::repeat : spread::pad);
|
||||||
|
|
||||||
|
# Coordinates: fractions of the bounds, or lengths in user space.
|
||||||
|
if radial {
|
||||||
|
made.x1 = this.gradient_length(&chain, "cx", user_space, axis::x, 0.5);
|
||||||
|
made.y1 = this.gradient_length(&chain, "cy", user_space, axis::y, 0.5);
|
||||||
|
made.r = this.gradient_length(&chain, "r", user_space, axis::diagonal, 0.5);
|
||||||
|
# The focus is the center, where it's not given.
|
||||||
|
made.x2 = attribute_of(&chain, "fx") is some(_) ? this.gradient_length(&chain, "fx", user_space, axis::x, 0.5) : made.x1;
|
||||||
|
made.y2 = attribute_of(&chain, "fy") is some(_) ? this.gradient_length(&chain, "fy", user_space, axis::y, 0.5) : made.y1;
|
||||||
|
# A focus outside the circle is moved onto it, as SVG 1.1 says.
|
||||||
|
val dx := made.x2 - made.x1;
|
||||||
|
val dy := made.y2 - made.y1;
|
||||||
|
val distance := math::hypot(dx, dy);
|
||||||
|
if distance > made.r * 0.999 && distance > 0 {
|
||||||
|
made.x2 = made.x1 + dx * made.r * 0.999 / distance;
|
||||||
|
made.y2 = made.y1 + dy * made.r * 0.999 / distance;
|
||||||
|
}
|
||||||
|
if made.r <= 0 {
|
||||||
|
return nothing {};
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
made.x1 = this.gradient_length(&chain, "x1", user_space, axis::x, 0);
|
||||||
|
made.y1 = this.gradient_length(&chain, "y1", user_space, axis::y, 0);
|
||||||
|
made.x2 = this.gradient_length(&chain, "x2", user_space, axis::x, 1);
|
||||||
|
made.y2 = this.gradient_length(&chain, "y2", user_space, axis::y, 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
# The space it's in, then the canvas.
|
||||||
|
var space := matrix {};
|
||||||
|
if attribute_of(&chain, "gradientTransform") is some(written) {
|
||||||
|
space = parse_transform(written) else matrix {};
|
||||||
|
}
|
||||||
|
if !user_space {
|
||||||
|
val width := bounds[1].x - bounds[0].x;
|
||||||
|
val height := bounds[1].y - bounds[0].y;
|
||||||
|
if width <= 0 || height <= 0 {
|
||||||
|
return nothing {};
|
||||||
|
}
|
||||||
|
space = space.then(&matrix { a = width, d = height, e = bounds[0].x, f = bounds[0].y });
|
||||||
|
}
|
||||||
|
made.inverse = space.then(placed).inverse() else { return nothing {}; };
|
||||||
|
|
||||||
|
# The stops, of the nearest gradient that has any, each offset no less than
|
||||||
|
# the one before.
|
||||||
|
var offsets := vector::<f64>::new();
|
||||||
|
var colors := vector::<f32>::new();
|
||||||
|
for linked in chain {
|
||||||
|
for stop in linked.elements() {
|
||||||
|
if stop.local != "stop" || !is_svg(&stop) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
val stop_style := this.style_of(&stop, &style {});
|
||||||
|
var offset := parse_fraction(stop.attribute("offset") else "0") else 0.0;
|
||||||
|
offset = math::clamp(offset, 0.0, 1.0);
|
||||||
|
if !offsets.empty && offset < offsets.last {
|
||||||
|
offset = offsets.last;
|
||||||
|
}
|
||||||
|
offsets.append(offset);
|
||||||
|
colors.append(stop_style.stop_color.r as f32);
|
||||||
|
colors.append(stop_style.stop_color.g as f32);
|
||||||
|
colors.append(stop_style.stop_color.b as f32);
|
||||||
|
colors.append((stop_style.stop_color.a * stop_style.stop_opacity * opacity) as f32);
|
||||||
|
}
|
||||||
|
if !offsets.empty {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if offsets.empty {
|
||||||
|
return nothing {};
|
||||||
|
}
|
||||||
|
|
||||||
|
# The table: each stop's color up to the next, blended between them before
|
||||||
|
# they're premultiplied, as browsers blend them.
|
||||||
|
var stop: u64 = 0;
|
||||||
|
for slot in 0u..256u {
|
||||||
|
val t := slot as f64 / 255;
|
||||||
|
while stop + 1 < offsets.length && offsets[stop + 1] <= t {
|
||||||
|
stop++;
|
||||||
|
}
|
||||||
|
var mix: f64 = 0;
|
||||||
|
var next := stop;
|
||||||
|
if t > offsets[stop] && stop + 1 < offsets.length {
|
||||||
|
next = stop + 1;
|
||||||
|
val gap := offsets[next] - offsets[stop];
|
||||||
|
mix = gap <= 0 ? 1.0 : (t - offsets[stop]) / gap;
|
||||||
|
}
|
||||||
|
if t < offsets[0] {
|
||||||
|
mix = 0;
|
||||||
|
next = 0;
|
||||||
|
}
|
||||||
|
var blended: f64[4];
|
||||||
|
for channel in 0u..4u {
|
||||||
|
val from := colors[stop * 4 + channel] as f64;
|
||||||
|
val to := colors[next * 4 + channel] as f64;
|
||||||
|
blended[channel] = from + (to - from) * mix;
|
||||||
|
}
|
||||||
|
for channel in 0u..3u {
|
||||||
|
made.table[slot * 4 + channel] = (blended[channel] * blended[3]) as f32;
|
||||||
|
}
|
||||||
|
made.table[slot * 4 + 3] = blended[3] as f32;
|
||||||
|
}
|
||||||
|
return made;
|
||||||
|
}
|
||||||
|
|
||||||
|
# A gradient's coordinate: a fraction of the bounds, or a length in user space,
|
||||||
|
# where what it is when left out is a fraction of the bounds or the viewport.
|
||||||
|
def renderer::gradient_length(&this, chain: &vector<xml::element>, name: strview, user_space: bool, along: axis, fallback: f64): f64 {
|
||||||
|
val written := attribute_of(chain, name) else { return user_space && fallback != 0 ? this.percent(fallback, along) : fallback; };
|
||||||
|
if user_space {
|
||||||
|
return parse_length(written, &this.view, along) else fallback;
|
||||||
|
}
|
||||||
|
return parse_fraction(written) else fallback;
|
||||||
|
}
|
||||||
|
|
||||||
|
# A fraction of the viewport along an axis, as a percentage of it is.
|
||||||
|
def renderer::percent(&this, fraction: f64, along: axis): f64 {
|
||||||
|
return fraction * (along == axis::x ? this.view.width : (along == axis::y ? this.view.height : this.view.diagonal()));
|
||||||
|
}
|
||||||
|
|
||||||
|
# The first of a chain of gradients to give an attribute.
|
||||||
|
def attribute_of(chain: &vector<xml::element>, name: strview): maybe<strview> {
|
||||||
|
for linked in chain {
|
||||||
|
if linked.attribute(name) is some(value) {
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nothing {};
|
||||||
|
}
|
||||||
@@ -0,0 +1,60 @@
|
|||||||
|
#! Contains lengths, in user units: numbers, with a unit or as a percentage of
|
||||||
|
#! the viewport, and fractions, as offsets and opacities are written.
|
||||||
|
|
||||||
|
import std::math;
|
||||||
|
module malunal::image::svg;
|
||||||
|
|
||||||
|
|
||||||
|
# The size percentages are of, and that of the viewport's diagonal, as the user
|
||||||
|
# space being drawn in measures them.
|
||||||
|
struct viewport {
|
||||||
|
var width: f64;
|
||||||
|
var height: f64;
|
||||||
|
}
|
||||||
|
|
||||||
|
def viewport::diagonal(&this): f64 {
|
||||||
|
return math::sqrt((this.width * this.width + this.height * this.height) / 2);
|
||||||
|
}
|
||||||
|
|
||||||
|
# Which length a percentage is of.
|
||||||
|
enum axis: u8 {
|
||||||
|
x,
|
||||||
|
y,
|
||||||
|
diagonal,
|
||||||
|
}
|
||||||
|
|
||||||
|
# Reads a length, in user units: a number, with a unit or a percentage of the
|
||||||
|
# viewport.
|
||||||
|
def parse_length(text: strview, view: &viewport, along: axis): maybe<f64> {
|
||||||
|
val trimmed := text.trim();
|
||||||
|
val read := number_at(trimmed, 0) else { return nothing {}; };
|
||||||
|
val unit := trimmed.substr(read.end, trimmed.length - read.end).trim();
|
||||||
|
val scale: f64 = match unit {
|
||||||
|
"" => 1.0,
|
||||||
|
"px" => 1.0,
|
||||||
|
"pt" => 4.0 / 3.0,
|
||||||
|
"pc" => 16.0,
|
||||||
|
"mm" => 96.0 / 25.4,
|
||||||
|
"cm" => 96.0 / 2.54,
|
||||||
|
"in" => 96.0,
|
||||||
|
"em" => 16.0,
|
||||||
|
"ex" => 8.0,
|
||||||
|
"%" => (along == axis::x ? view.width : (along == axis::y ? view.height : view.diagonal())) / 100,
|
||||||
|
else => -1.0,
|
||||||
|
};
|
||||||
|
if scale < 0 {
|
||||||
|
return nothing {};
|
||||||
|
}
|
||||||
|
return read.value * scale;
|
||||||
|
}
|
||||||
|
|
||||||
|
# Reads a number, or a percentage of 1, as offsets and opacities are written.
|
||||||
|
def parse_fraction(text: strview): maybe<f64> {
|
||||||
|
val trimmed := text.trim();
|
||||||
|
val read := number_at(trimmed, 0) else { return nothing {}; };
|
||||||
|
val rest := trimmed.substr(read.end, trimmed.length - read.end).trim();
|
||||||
|
if rest == "%" {
|
||||||
|
return read.value / 100;
|
||||||
|
}
|
||||||
|
return rest.length == 0 ? read.value : nothing {};
|
||||||
|
}
|
||||||
@@ -0,0 +1,56 @@
|
|||||||
|
#! Contains clips and masks: the coverage a `clipPath`'s shapes give, each solid,
|
||||||
|
#! and the luminance a `mask`'s content gives, each drawn as a layer of its own.
|
||||||
|
|
||||||
|
import std::xml;
|
||||||
|
module malunal::image::svg;
|
||||||
|
|
||||||
|
|
||||||
|
# A clip path's coverage, drawn as a layer of its shapes, each solid.
|
||||||
|
def renderer::clip_mask(&mut this, clip: &xml::element, placed: &matrix, bounds: maybe<point[2]>): vector<u8> {
|
||||||
|
var space := copy(placed);
|
||||||
|
if clip.attribute("clipPathUnits") is some(units) && units == "objectBoundingBox" {
|
||||||
|
val box := bounds else {
|
||||||
|
var empty := vector::<u8>::new();
|
||||||
|
empty.resize(this.canvas.width * this.canvas.height * 4);
|
||||||
|
return empty;
|
||||||
|
};
|
||||||
|
space = matrix { a = box[1].x - box[0].x, d = box[1].y - box[0].y, e = box[0].x, f = box[0].y }.then(placed);
|
||||||
|
}
|
||||||
|
if clip.attribute("transform") is some(written) {
|
||||||
|
if parse_transform(written) is some(own_transform) {
|
||||||
|
space = own_transform.then(&space);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
val clip_style := this.style_of(clip, &style {});
|
||||||
|
this.canvas.push();
|
||||||
|
val saved := this.clipping;
|
||||||
|
this.clipping = true;
|
||||||
|
for child in clip.elements() {
|
||||||
|
if is_shape(child.local) || child.local == "use" {
|
||||||
|
this.draw(&child, &clip_style, &space);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
this.clipping = saved;
|
||||||
|
return this.canvas.pop();
|
||||||
|
}
|
||||||
|
|
||||||
|
# A mask's coverage: its content drawn as a layer, its luminance taken as alpha.
|
||||||
|
def renderer::luminance_mask(&mut this, mask: &xml::element, placed: &matrix, bounds: maybe<point[2]>): vector<u8> {
|
||||||
|
var space := copy(placed);
|
||||||
|
if mask.attribute("maskContentUnits") is some(units) && units == "objectBoundingBox" {
|
||||||
|
if bounds is some(box) {
|
||||||
|
space = matrix { a = box[1].x - box[0].x, d = box[1].y - box[0].y, e = box[0].x, f = box[0].y }.then(placed);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
val mask_style := this.style_of(mask, &style {});
|
||||||
|
this.canvas.push();
|
||||||
|
this.children(mask, &mask_style, &space);
|
||||||
|
var made := this.canvas.pop();
|
||||||
|
var at: u64 = 0;
|
||||||
|
while at < made.length {
|
||||||
|
val luminance := made[at] as f32 * 0.2125 + made[at + 1] as f32 * 0.7154 + made[at + 2] as f32 * 0.0721;
|
||||||
|
made[at + 3] = (luminance + 0.5) as u8;
|
||||||
|
at += 4;
|
||||||
|
}
|
||||||
|
return made;
|
||||||
|
}
|
||||||
@@ -0,0 +1,138 @@
|
|||||||
|
#! Contains points and the affine transforms between SVG's spaces, and the
|
||||||
|
#! lists of transforms an element's `transform` gives.
|
||||||
|
|
||||||
|
import std::math;
|
||||||
|
module malunal::image::svg;
|
||||||
|
|
||||||
|
|
||||||
|
# A point, in whatever space it's in.
|
||||||
|
struct point {
|
||||||
|
var x: f64;
|
||||||
|
var y: f64;
|
||||||
|
}
|
||||||
|
|
||||||
|
# An affine transform, mapping (x, y) to (a x + c y + e, b x + d y + f), as SVG's
|
||||||
|
# `matrix(a b c d e f)` does.
|
||||||
|
struct matrix {
|
||||||
|
var a: f64 = 1;
|
||||||
|
var b: f64 = 0;
|
||||||
|
var c: f64 = 0;
|
||||||
|
var d: f64 = 1;
|
||||||
|
var e: f64 = 0;
|
||||||
|
var f: f64 = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
# The transform that applies this one, then another.
|
||||||
|
def matrix::then(&this, outer: &matrix): matrix {
|
||||||
|
return matrix {
|
||||||
|
a = outer.a * this.a + outer.c * this.b,
|
||||||
|
b = outer.b * this.a + outer.d * this.b,
|
||||||
|
c = outer.a * this.c + outer.c * this.d,
|
||||||
|
d = outer.b * this.c + outer.d * this.d,
|
||||||
|
e = outer.a * this.e + outer.c * this.f + outer.e,
|
||||||
|
f = outer.b * this.e + outer.d * this.f + outer.f
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
def matrix::apply(&this, at: point): point {
|
||||||
|
return point { x = this.a * at.x + this.c * at.y + this.e, y = this.b * at.x + this.d * at.y + this.f };
|
||||||
|
}
|
||||||
|
|
||||||
|
# The transform undoing this one, or `nothing` where it flattens everything.
|
||||||
|
def matrix::inverse(&this): maybe<matrix> {
|
||||||
|
val det := this.a * this.d - this.b * this.c;
|
||||||
|
if math::abs(det) < 1e-12 {
|
||||||
|
return nothing {};
|
||||||
|
}
|
||||||
|
return matrix {
|
||||||
|
a = this.d / det,
|
||||||
|
b = -this.b / det,
|
||||||
|
c = -this.c / det,
|
||||||
|
d = this.a / det,
|
||||||
|
e = (this.c * this.f - this.d * this.e) / det,
|
||||||
|
f = (this.b * this.e - this.a * this.f) / det
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
# How much the transform stretches lengths at most, which tolerances in user
|
||||||
|
# space are divided by.
|
||||||
|
def matrix::stretch(&this): f64 {
|
||||||
|
val across := math::sqrt(this.a * this.a + this.b * this.b);
|
||||||
|
val down := math::sqrt(this.c * this.c + this.d * this.d);
|
||||||
|
return across > down ? across : down;
|
||||||
|
}
|
||||||
|
|
||||||
|
def translation(x: f64, y: f64): matrix {
|
||||||
|
return matrix { e = x, f = y };
|
||||||
|
}
|
||||||
|
|
||||||
|
def scaling(x: f64, y: f64): matrix {
|
||||||
|
return matrix { a = x, d = y };
|
||||||
|
}
|
||||||
|
|
||||||
|
def rotation(degrees: f64): matrix {
|
||||||
|
val angle := degrees * math::pi / 180;
|
||||||
|
val cos := math::cos(angle);
|
||||||
|
val sin := math::sin(angle);
|
||||||
|
return matrix { a = cos, b = sin, c = -sin, d = cos };
|
||||||
|
}
|
||||||
|
|
||||||
|
# Reads SVG's list of transforms, each applied after those after it, as an
|
||||||
|
# element's `transform` gives them.
|
||||||
|
# @returns The transform, or `nothing` where the list is broken, which SVG takes
|
||||||
|
# as none at all.
|
||||||
|
def parse_transform(text: strview): maybe<matrix> {
|
||||||
|
var made := matrix {};
|
||||||
|
var at: u64 = 0;
|
||||||
|
while true {
|
||||||
|
while at < text.length && (text[at].is_space || text[at] == ',') {
|
||||||
|
at++;
|
||||||
|
}
|
||||||
|
if at >= text.length {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
var name_end := at;
|
||||||
|
while name_end < text.length && text[name_end].is_alpha {
|
||||||
|
name_end++;
|
||||||
|
}
|
||||||
|
val name := text.substr(at, name_end - at);
|
||||||
|
val open := text.substr(name_end, text.length - name_end).find("(") else { return nothing {}; };
|
||||||
|
val close := text.substr(name_end, text.length - name_end).find(")") else { return nothing {}; };
|
||||||
|
if close < open {
|
||||||
|
return nothing {};
|
||||||
|
}
|
||||||
|
var values: f64[6];
|
||||||
|
var count: u64 = 0;
|
||||||
|
var read := numbers::of(text.substr(name_end + open + 1, close - open - 1));
|
||||||
|
while !read.at_end() {
|
||||||
|
val value := read.next() else { return nothing {}; };
|
||||||
|
if count >= 6 {
|
||||||
|
return nothing {};
|
||||||
|
}
|
||||||
|
values[count] = value;
|
||||||
|
count++;
|
||||||
|
}
|
||||||
|
at = name_end + close + 1;
|
||||||
|
|
||||||
|
var step := matrix {};
|
||||||
|
if name == "matrix" && count == 6 {
|
||||||
|
step = matrix { a = values[0], b = values[1], c = values[2], d = values[3], e = values[4], f = values[5] };
|
||||||
|
} else if name == "translate" && (count == 1 || count == 2) {
|
||||||
|
step = translation(values[0], count == 2 ? values[1] : 0);
|
||||||
|
} else if name == "scale" && (count == 1 || count == 2) {
|
||||||
|
step = scaling(values[0], count == 2 ? values[1] : values[0]);
|
||||||
|
} else if name == "rotate" && count == 1 {
|
||||||
|
step = rotation(values[0]);
|
||||||
|
} else if name == "rotate" && count == 3 {
|
||||||
|
step = translation(-values[1], -values[2]).then(&rotation(values[0])).then(&translation(values[1], values[2]));
|
||||||
|
} else if name == "skewX" && count == 1 {
|
||||||
|
step = matrix { c = math::tan(values[0] * math::pi / 180) };
|
||||||
|
} else if name == "skewY" && count == 1 {
|
||||||
|
step = matrix { b = math::tan(values[0] * math::pi / 180) };
|
||||||
|
} else {
|
||||||
|
return nothing {};
|
||||||
|
}
|
||||||
|
made = step.then(&made);
|
||||||
|
}
|
||||||
|
return made;
|
||||||
|
}
|
||||||
@@ -0,0 +1,87 @@
|
|||||||
|
#! Contains the colors CSS names, and the RGB of each.
|
||||||
|
|
||||||
|
module malunal::image::svg;
|
||||||
|
|
||||||
|
|
||||||
|
# A color CSS names, and its RGB.
|
||||||
|
struct named_color {
|
||||||
|
var name: strview;
|
||||||
|
var rgb: u32;
|
||||||
|
}
|
||||||
|
|
||||||
|
const named_colors: named_color[147] = [
|
||||||
|
named_color { name = "aliceblue", rgb = 0xF0F8FF }, named_color { name = "antiquewhite", rgb = 0xFAEBD7 },
|
||||||
|
named_color { name = "aqua", rgb = 0x00FFFF }, named_color { name = "aquamarine", rgb = 0x7FFFD4 },
|
||||||
|
named_color { name = "azure", rgb = 0xF0FFFF }, named_color { name = "beige", rgb = 0xF5F5DC },
|
||||||
|
named_color { name = "bisque", rgb = 0xFFE4C4 }, named_color { name = "black", rgb = 0x000000 },
|
||||||
|
named_color { name = "blanchedalmond", rgb = 0xFFEBCD }, named_color { name = "blue", rgb = 0x0000FF },
|
||||||
|
named_color { name = "blueviolet", rgb = 0x8A2BE2 }, named_color { name = "brown", rgb = 0xA52A2A },
|
||||||
|
named_color { name = "burlywood", rgb = 0xDEB887 }, named_color { name = "cadetblue", rgb = 0x5F9EA0 },
|
||||||
|
named_color { name = "chartreuse", rgb = 0x7FFF00 }, named_color { name = "chocolate", rgb = 0xD2691E },
|
||||||
|
named_color { name = "coral", rgb = 0xFF7F50 }, named_color { name = "cornflowerblue", rgb = 0x6495ED },
|
||||||
|
named_color { name = "cornsilk", rgb = 0xFFF8DC }, named_color { name = "crimson", rgb = 0xDC143C },
|
||||||
|
named_color { name = "cyan", rgb = 0x00FFFF }, named_color { name = "darkblue", rgb = 0x00008B },
|
||||||
|
named_color { name = "darkcyan", rgb = 0x008B8B }, named_color { name = "darkgoldenrod", rgb = 0xB8860B },
|
||||||
|
named_color { name = "darkgray", rgb = 0xA9A9A9 }, named_color { name = "darkgreen", rgb = 0x006400 },
|
||||||
|
named_color { name = "darkgrey", rgb = 0xA9A9A9 }, named_color { name = "darkkhaki", rgb = 0xBDB76B },
|
||||||
|
named_color { name = "darkmagenta", rgb = 0x8B008B }, named_color { name = "darkolivegreen", rgb = 0x556B2F },
|
||||||
|
named_color { name = "darkorange", rgb = 0xFF8C00 }, named_color { name = "darkorchid", rgb = 0x9932CC },
|
||||||
|
named_color { name = "darkred", rgb = 0x8B0000 }, named_color { name = "darksalmon", rgb = 0xE9967A },
|
||||||
|
named_color { name = "darkseagreen", rgb = 0x8FBC8F }, named_color { name = "darkslateblue", rgb = 0x483D8B },
|
||||||
|
named_color { name = "darkslategray", rgb = 0x2F4F4F }, named_color { name = "darkslategrey", rgb = 0x2F4F4F },
|
||||||
|
named_color { name = "darkturquoise", rgb = 0x00CED1 }, named_color { name = "darkviolet", rgb = 0x9400D3 },
|
||||||
|
named_color { name = "deeppink", rgb = 0xFF1493 }, named_color { name = "deepskyblue", rgb = 0x00BFFF },
|
||||||
|
named_color { name = "dimgray", rgb = 0x696969 }, named_color { name = "dimgrey", rgb = 0x696969 },
|
||||||
|
named_color { name = "dodgerblue", rgb = 0x1E90FF }, named_color { name = "firebrick", rgb = 0xB22222 },
|
||||||
|
named_color { name = "floralwhite", rgb = 0xFFFAF0 }, named_color { name = "forestgreen", rgb = 0x228B22 },
|
||||||
|
named_color { name = "fuchsia", rgb = 0xFF00FF }, named_color { name = "gainsboro", rgb = 0xDCDCDC },
|
||||||
|
named_color { name = "ghostwhite", rgb = 0xF8F8FF }, named_color { name = "gold", rgb = 0xFFD700 },
|
||||||
|
named_color { name = "goldenrod", rgb = 0xDAA520 }, named_color { name = "gray", rgb = 0x808080 },
|
||||||
|
named_color { name = "grey", rgb = 0x808080 }, named_color { name = "green", rgb = 0x008000 },
|
||||||
|
named_color { name = "greenyellow", rgb = 0xADFF2F }, named_color { name = "honeydew", rgb = 0xF0FFF0 },
|
||||||
|
named_color { name = "hotpink", rgb = 0xFF69B4 }, named_color { name = "indianred", rgb = 0xCD5C5C },
|
||||||
|
named_color { name = "indigo", rgb = 0x4B0082 }, named_color { name = "ivory", rgb = 0xFFFFF0 },
|
||||||
|
named_color { name = "khaki", rgb = 0xF0E68C }, named_color { name = "lavender", rgb = 0xE6E6FA },
|
||||||
|
named_color { name = "lavenderblush", rgb = 0xFFF0F5 }, named_color { name = "lawngreen", rgb = 0x7CFC00 },
|
||||||
|
named_color { name = "lemonchiffon", rgb = 0xFFFACD }, named_color { name = "lightblue", rgb = 0xADD8E6 },
|
||||||
|
named_color { name = "lightcoral", rgb = 0xF08080 }, named_color { name = "lightcyan", rgb = 0xE0FFFF },
|
||||||
|
named_color { name = "lightgoldenrodyellow", rgb = 0xFAFAD2 }, named_color { name = "lightgray", rgb = 0xD3D3D3 },
|
||||||
|
named_color { name = "lightgreen", rgb = 0x90EE90 }, named_color { name = "lightgrey", rgb = 0xD3D3D3 },
|
||||||
|
named_color { name = "lightpink", rgb = 0xFFB6C1 }, named_color { name = "lightsalmon", rgb = 0xFFA07A },
|
||||||
|
named_color { name = "lightseagreen", rgb = 0x20B2AA }, named_color { name = "lightskyblue", rgb = 0x87CEFA },
|
||||||
|
named_color { name = "lightslategray", rgb = 0x778899 }, named_color { name = "lightslategrey", rgb = 0x778899 },
|
||||||
|
named_color { name = "lightsteelblue", rgb = 0xB0C4DE }, named_color { name = "lightyellow", rgb = 0xFFFFE0 },
|
||||||
|
named_color { name = "lime", rgb = 0x00FF00 }, named_color { name = "limegreen", rgb = 0x32CD32 },
|
||||||
|
named_color { name = "linen", rgb = 0xFAF0E6 }, named_color { name = "magenta", rgb = 0xFF00FF },
|
||||||
|
named_color { name = "maroon", rgb = 0x800000 }, named_color { name = "mediumaquamarine", rgb = 0x66CDAA },
|
||||||
|
named_color { name = "mediumblue", rgb = 0x0000CD }, named_color { name = "mediumorchid", rgb = 0xBA55D3 },
|
||||||
|
named_color { name = "mediumpurple", rgb = 0x9370DB }, named_color { name = "mediumseagreen", rgb = 0x3CB371 },
|
||||||
|
named_color { name = "mediumslateblue", rgb = 0x7B68EE }, named_color { name = "mediumspringgreen", rgb = 0x00FA9A },
|
||||||
|
named_color { name = "mediumturquoise", rgb = 0x48D1CC }, named_color { name = "mediumvioletred", rgb = 0xC71585 },
|
||||||
|
named_color { name = "midnightblue", rgb = 0x191970 }, named_color { name = "mintcream", rgb = 0xF5FFFA },
|
||||||
|
named_color { name = "mistyrose", rgb = 0xFFE4E1 }, named_color { name = "moccasin", rgb = 0xFFE4B5 },
|
||||||
|
named_color { name = "navajowhite", rgb = 0xFFDEAD }, named_color { name = "navy", rgb = 0x000080 },
|
||||||
|
named_color { name = "oldlace", rgb = 0xFDF5E6 }, named_color { name = "olive", rgb = 0x808000 },
|
||||||
|
named_color { name = "olivedrab", rgb = 0x6B8E23 }, named_color { name = "orange", rgb = 0xFFA500 },
|
||||||
|
named_color { name = "orangered", rgb = 0xFF4500 }, named_color { name = "orchid", rgb = 0xDA70D6 },
|
||||||
|
named_color { name = "palegoldenrod", rgb = 0xEEE8AA }, named_color { name = "palegreen", rgb = 0x98FB98 },
|
||||||
|
named_color { name = "paleturquoise", rgb = 0xAFEEEE }, named_color { name = "palevioletred", rgb = 0xDB7093 },
|
||||||
|
named_color { name = "papayawhip", rgb = 0xFFEFD5 }, named_color { name = "peachpuff", rgb = 0xFFDAB9 },
|
||||||
|
named_color { name = "peru", rgb = 0xCD853F }, named_color { name = "pink", rgb = 0xFFC0CB },
|
||||||
|
named_color { name = "plum", rgb = 0xDDA0DD }, named_color { name = "powderblue", rgb = 0xB0E0E6 },
|
||||||
|
named_color { name = "purple", rgb = 0x800080 }, named_color { name = "red", rgb = 0xFF0000 },
|
||||||
|
named_color { name = "rosybrown", rgb = 0xBC8F8F }, named_color { name = "royalblue", rgb = 0x4169E1 },
|
||||||
|
named_color { name = "saddlebrown", rgb = 0x8B4513 }, named_color { name = "salmon", rgb = 0xFA8072 },
|
||||||
|
named_color { name = "sandybrown", rgb = 0xF4A460 }, named_color { name = "seagreen", rgb = 0x2E8B57 },
|
||||||
|
named_color { name = "seashell", rgb = 0xFFF5EE }, named_color { name = "sienna", rgb = 0xA0522D },
|
||||||
|
named_color { name = "silver", rgb = 0xC0C0C0 }, named_color { name = "skyblue", rgb = 0x87CEEB },
|
||||||
|
named_color { name = "slateblue", rgb = 0x6A5ACD }, named_color { name = "slategray", rgb = 0x708090 },
|
||||||
|
named_color { name = "slategrey", rgb = 0x708090 }, named_color { name = "snow", rgb = 0xFFFAFA },
|
||||||
|
named_color { name = "springgreen", rgb = 0x00FF7F }, named_color { name = "steelblue", rgb = 0x4682B4 },
|
||||||
|
named_color { name = "tan", rgb = 0xD2B48C }, named_color { name = "teal", rgb = 0x008080 },
|
||||||
|
named_color { name = "thistle", rgb = 0xD8BFD8 }, named_color { name = "tomato", rgb = 0xFF6347 },
|
||||||
|
named_color { name = "turquoise", rgb = 0x40E0D0 }, named_color { name = "violet", rgb = 0xEE82EE },
|
||||||
|
named_color { name = "wheat", rgb = 0xF5DEB3 }, named_color { name = "white", rgb = 0xFFFFFF },
|
||||||
|
named_color { name = "whitesmoke", rgb = 0xF5F5F5 }, named_color { name = "yellow", rgb = 0xFFFF00 },
|
||||||
|
named_color { name = "yellowgreen", rgb = 0x9ACD32 },
|
||||||
|
];
|
||||||
@@ -0,0 +1,127 @@
|
|||||||
|
#! Contains the numbers of attributes' text, as CSS and SVG write them, and the
|
||||||
|
#! separators between them.
|
||||||
|
|
||||||
|
import std::math;
|
||||||
|
module malunal::image::svg;
|
||||||
|
|
||||||
|
|
||||||
|
# Reads numbers, and the separators between them, from attributes' text.
|
||||||
|
struct numbers {
|
||||||
|
var text: strview;
|
||||||
|
var at: u64;
|
||||||
|
}
|
||||||
|
|
||||||
|
def numbers::of(text: strview): numbers {
|
||||||
|
return numbers { text = text };
|
||||||
|
}
|
||||||
|
|
||||||
|
# Moves past whitespace, and a comma among it.
|
||||||
|
def numbers::skip(&mut this): void {
|
||||||
|
var comma := false;
|
||||||
|
while this.at < this.text.length {
|
||||||
|
val byte := this.text[this.at];
|
||||||
|
if byte == ',' && !comma {
|
||||||
|
comma = true;
|
||||||
|
} else if !byte.is_space {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
this.at++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
def numbers::at_end(&mut this): bool {
|
||||||
|
this.skip();
|
||||||
|
return this.at >= this.text.length;
|
||||||
|
}
|
||||||
|
|
||||||
|
# Reads a number, as CSS and SVG write them: a sign, digits with or without a
|
||||||
|
# point, and an exponent, so `1.5.5` is two, and `-1-2` too.
|
||||||
|
def numbers::next(&mut this): maybe<f64> {
|
||||||
|
this.skip();
|
||||||
|
val read := number_at(this.text, this.at) else { return nothing {}; };
|
||||||
|
this.at = read.end;
|
||||||
|
return read.value;
|
||||||
|
}
|
||||||
|
|
||||||
|
# Reads a flag of an arc, `0` or `1`, which needs nothing after it.
|
||||||
|
def numbers::flag(&mut this): maybe<bool> {
|
||||||
|
this.skip();
|
||||||
|
if this.at >= this.text.length {
|
||||||
|
return nothing {};
|
||||||
|
}
|
||||||
|
val byte := this.text[this.at];
|
||||||
|
if byte != '0' && byte != '1' {
|
||||||
|
return nothing {};
|
||||||
|
}
|
||||||
|
this.at++;
|
||||||
|
return byte == '1';
|
||||||
|
}
|
||||||
|
|
||||||
|
def numbers::point(&mut this): maybe<point> {
|
||||||
|
val x := this.next() else { return nothing {}; };
|
||||||
|
val y := this.next() else { return nothing {}; };
|
||||||
|
return point { x = x, y = y };
|
||||||
|
}
|
||||||
|
|
||||||
|
# A number read, and where it ends.
|
||||||
|
struct read_number {
|
||||||
|
var value: f64;
|
||||||
|
var end: u64;
|
||||||
|
}
|
||||||
|
|
||||||
|
# Reads a number beginning at a byte.
|
||||||
|
def number_at(text: strview, from: u64): maybe<read_number> {
|
||||||
|
var at := from;
|
||||||
|
var negative := false;
|
||||||
|
if at < text.length && (text[at] == '+' || text[at] == '-') {
|
||||||
|
negative = text[at] == '-';
|
||||||
|
at++;
|
||||||
|
}
|
||||||
|
var mantissa: f64 = 0;
|
||||||
|
var digits := 0u;
|
||||||
|
var scale: i64 = 0;
|
||||||
|
while at < text.length && text[at].is_digit {
|
||||||
|
mantissa = mantissa * 10 + (text[at] - '0') as f64;
|
||||||
|
digits++;
|
||||||
|
at++;
|
||||||
|
}
|
||||||
|
if at < text.length && text[at] == '.' {
|
||||||
|
var fraction := at + 1;
|
||||||
|
while fraction < text.length && text[fraction].is_digit {
|
||||||
|
mantissa = mantissa * 10 + (text[fraction] - '0') as f64;
|
||||||
|
scale--;
|
||||||
|
digits++;
|
||||||
|
fraction++;
|
||||||
|
}
|
||||||
|
if fraction > at + 1 || digits > 0 {
|
||||||
|
at = fraction;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if digits == 0 {
|
||||||
|
return nothing {};
|
||||||
|
}
|
||||||
|
if at < text.length && (text[at] == 'e' || text[at] == 'E') {
|
||||||
|
var exponent_at := at + 1;
|
||||||
|
var exponent_negative := false;
|
||||||
|
if exponent_at < text.length && (text[exponent_at] == '+' || text[exponent_at] == '-') {
|
||||||
|
exponent_negative = text[exponent_at] == '-';
|
||||||
|
exponent_at++;
|
||||||
|
}
|
||||||
|
if exponent_at < text.length && text[exponent_at].is_digit {
|
||||||
|
var exponent: i64 = 0;
|
||||||
|
while exponent_at < text.length && text[exponent_at].is_digit {
|
||||||
|
if exponent < 10000 {
|
||||||
|
exponent = exponent * 10 + (text[exponent_at] - '0') as i64;
|
||||||
|
}
|
||||||
|
exponent_at++;
|
||||||
|
}
|
||||||
|
scale += exponent_negative ? -exponent : exponent;
|
||||||
|
at = exponent_at;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
var value := mantissa;
|
||||||
|
if scale != 0 {
|
||||||
|
value = mantissa * math::pow(10.0, scale as f64);
|
||||||
|
}
|
||||||
|
return read_number { value = negative ? -value : value, end = at };
|
||||||
|
}
|
||||||
@@ -0,0 +1,155 @@
|
|||||||
|
#! Contains outlines: the polygons and polylines paths are flattened to, and
|
||||||
|
#! strokes made, before they're filled.
|
||||||
|
|
||||||
|
import std::math;
|
||||||
|
module malunal::image::svg;
|
||||||
|
|
||||||
|
|
||||||
|
# How far, in pixels, a flattened curve may stray from the curve.
|
||||||
|
const tolerance: f64 = 0.2;
|
||||||
|
|
||||||
|
# A polygon or polyline of an outline, by its points in the outline's.
|
||||||
|
struct contour {
|
||||||
|
var start: u64;
|
||||||
|
var count: u64;
|
||||||
|
var closed: bool;
|
||||||
|
}
|
||||||
|
|
||||||
|
# Polygons and polylines, as paths are flattened to, and strokes made.
|
||||||
|
struct outline {
|
||||||
|
var points: vector<point>;
|
||||||
|
var contours: vector<contour>;
|
||||||
|
var begun: u64; #! Where the contour being added began.
|
||||||
|
}
|
||||||
|
|
||||||
|
def outline::new(): outline {
|
||||||
|
return outline { points = vector::<point>::new(), contours = vector::<contour>::new() };
|
||||||
|
}
|
||||||
|
|
||||||
|
def outline::begin(&mut this): void {
|
||||||
|
this.begun = this.points.length;
|
||||||
|
}
|
||||||
|
|
||||||
|
def outline::add(&mut this, at: point): void {
|
||||||
|
this.points.append(at);
|
||||||
|
}
|
||||||
|
|
||||||
|
# Ends the contour being added, keeping it where it has a point.
|
||||||
|
def outline::finish(&mut this, closed: bool): void {
|
||||||
|
if this.points.length > this.begun {
|
||||||
|
this.contours.append(contour { start = this.begun, count = this.points.length - this.begun, closed = closed });
|
||||||
|
}
|
||||||
|
this.begun = this.points.length;
|
||||||
|
}
|
||||||
|
|
||||||
|
# Adds a closed polygon, its points turning the same way as every other the
|
||||||
|
# stroker adds, so filling them all by the nonzero rule fills where any is.
|
||||||
|
def outline::polygon(&mut this, corners: span<point>): void {
|
||||||
|
var area: f64 = 0;
|
||||||
|
for index in 0..corners.length {
|
||||||
|
val a := corners[index];
|
||||||
|
val b := corners[(index + 1) % corners.length];
|
||||||
|
area += a.x * b.y - b.x * a.y;
|
||||||
|
}
|
||||||
|
this.begin();
|
||||||
|
if area >= 0 {
|
||||||
|
for corner in corners {
|
||||||
|
this.add(corner);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
var index := corners.length;
|
||||||
|
while index > 0 {
|
||||||
|
index--;
|
||||||
|
this.add(corners[index]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
this.finish(true);
|
||||||
|
}
|
||||||
|
|
||||||
|
# The outline with each point transformed.
|
||||||
|
def outline::transformed(&this, by: &matrix): outline {
|
||||||
|
var made := outline::new();
|
||||||
|
for at in this.points {
|
||||||
|
made.points.append(by.apply(at));
|
||||||
|
}
|
||||||
|
for held in this.contours {
|
||||||
|
made.contours.append(held);
|
||||||
|
}
|
||||||
|
return made;
|
||||||
|
}
|
||||||
|
|
||||||
|
# The smallest rectangle holding every point, as its least and greatest corners.
|
||||||
|
def outline::bounds(&this): point[2] {
|
||||||
|
if this.points.empty {
|
||||||
|
return [point {}, point {}];
|
||||||
|
}
|
||||||
|
var low := this.points[0];
|
||||||
|
var high := low;
|
||||||
|
for at in this.points {
|
||||||
|
low.x = at.x < low.x ? at.x : low.x;
|
||||||
|
low.y = at.y < low.y ? at.y : low.y;
|
||||||
|
high.x = at.x > high.x ? at.x : high.x;
|
||||||
|
high.y = at.y > high.y ? at.y : high.y;
|
||||||
|
}
|
||||||
|
return [low, high];
|
||||||
|
}
|
||||||
|
|
||||||
|
# Flattens a path, transformed, into polylines: each curve into as many lines
|
||||||
|
# as keep it within a distance, by Wang's formula.
|
||||||
|
def flatten(shape: &path, by: &matrix, within: f64): outline {
|
||||||
|
var made := outline::new();
|
||||||
|
var open := false;
|
||||||
|
var at: u64 = 0;
|
||||||
|
var last := point {};
|
||||||
|
for each in shape.verbs {
|
||||||
|
match each {
|
||||||
|
move => {
|
||||||
|
if open {
|
||||||
|
made.finish(false);
|
||||||
|
}
|
||||||
|
made.begin();
|
||||||
|
last = by.apply(shape.points[at]);
|
||||||
|
made.add(last);
|
||||||
|
at++;
|
||||||
|
open = true;
|
||||||
|
}
|
||||||
|
line => {
|
||||||
|
last = by.apply(shape.points[at]);
|
||||||
|
made.add(last);
|
||||||
|
at++;
|
||||||
|
}
|
||||||
|
cubic => {
|
||||||
|
val p0 := last;
|
||||||
|
val p1 := by.apply(shape.points[at]);
|
||||||
|
val p2 := by.apply(shape.points[at + 1]);
|
||||||
|
val p3 := by.apply(shape.points[at + 2]);
|
||||||
|
at += 3;
|
||||||
|
val bend1 := math::hypot(p0.x - 2 * p1.x + p2.x, p0.y - 2 * p1.y + p2.y);
|
||||||
|
val bend2 := math::hypot(p1.x - 2 * p2.x + p3.x, p1.y - 2 * p2.y + p3.y);
|
||||||
|
val bend := bend1 > bend2 ? bend1 : bend2;
|
||||||
|
var pieces := math::ceil(math::sqrt(bend * 0.75 / within));
|
||||||
|
pieces = pieces < 1 ? 1 : (pieces > 1000 ? 1000 : pieces);
|
||||||
|
val count := pieces as u64;
|
||||||
|
for step in 1..count {
|
||||||
|
val t := step as f64 / pieces;
|
||||||
|
val u := 1 - t;
|
||||||
|
val a := u * u * u;
|
||||||
|
val b := 3 * u * u * t;
|
||||||
|
val c := 3 * u * t * t;
|
||||||
|
val d := t * t * t;
|
||||||
|
made.add(point { x = a * p0.x + b * p1.x + c * p2.x + d * p3.x, y = a * p0.y + b * p1.y + c * p2.y + d * p3.y });
|
||||||
|
}
|
||||||
|
made.add(p3);
|
||||||
|
last = p3;
|
||||||
|
}
|
||||||
|
close => {
|
||||||
|
made.finish(true);
|
||||||
|
open = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if open {
|
||||||
|
made.finish(false);
|
||||||
|
}
|
||||||
|
return made;
|
||||||
|
}
|
||||||
@@ -0,0 +1,72 @@
|
|||||||
|
#! Contains paints, as a fill or stroke gives one: none, the element's own
|
||||||
|
#! color, a color, or a gradient by its ID, with what paints where it can't be
|
||||||
|
#! found.
|
||||||
|
|
||||||
|
module malunal::image::svg;
|
||||||
|
|
||||||
|
|
||||||
|
# What paints a fill or stroke.
|
||||||
|
enum paint_kind: u8 {
|
||||||
|
none,
|
||||||
|
color,
|
||||||
|
current, #! The element's `color`.
|
||||||
|
url, #! A gradient, by its ID, or the fallback after it.
|
||||||
|
}
|
||||||
|
|
||||||
|
struct paint {
|
||||||
|
var kind: paint_kind;
|
||||||
|
var color: color;
|
||||||
|
var url: strview;
|
||||||
|
var fallback: paint_kind = paint_kind::none; #! What paints where the gradient can't: none, a color, or `currentColor`.
|
||||||
|
}
|
||||||
|
|
||||||
|
# Reads a paint: `none`, `currentColor`, a color, or `url(#id)` and what paints
|
||||||
|
# where it can't.
|
||||||
|
def parse_paint(text: strview): maybe<paint> {
|
||||||
|
val trimmed := text.trim();
|
||||||
|
if trimmed == "none" {
|
||||||
|
return paint { kind = paint_kind::none };
|
||||||
|
}
|
||||||
|
if same_letters(trimmed, "currentColor") {
|
||||||
|
return paint { kind = paint_kind::current };
|
||||||
|
}
|
||||||
|
if trimmed.starts_with("url(") {
|
||||||
|
val close := trimmed.find(")") else { return nothing {}; };
|
||||||
|
var target := trimmed.substr(4, close - 4).trim();
|
||||||
|
if target.length >= 2 && (target[0] == '"' || target[0] == '\'') {
|
||||||
|
target = target.substr(1, target.length - 2);
|
||||||
|
}
|
||||||
|
if !target.starts_with("#") {
|
||||||
|
return nothing {};
|
||||||
|
}
|
||||||
|
var made := paint { kind = paint_kind::url, url = target.substr(1, target.length - 1) };
|
||||||
|
val rest := trimmed.substr(close + 1, trimmed.length - close - 1).trim();
|
||||||
|
if rest.length != 0 {
|
||||||
|
val fallback := parse_paint(rest) else { return nothing {}; };
|
||||||
|
made.fallback = fallback.kind;
|
||||||
|
made.color = fallback.color;
|
||||||
|
}
|
||||||
|
return made;
|
||||||
|
}
|
||||||
|
val found := parse_color(trimmed) else { return nothing {}; };
|
||||||
|
return paint { kind = paint_kind::color, color = found };
|
||||||
|
}
|
||||||
|
|
||||||
|
# The ID `url(#id)` names, or empty for `none` or what isn't one.
|
||||||
|
def url_of(text: strview): strview {
|
||||||
|
val read := parse_paint(text) else { return ""; };
|
||||||
|
return read.kind == paint_kind::url ? read.url : "";
|
||||||
|
}
|
||||||
|
|
||||||
|
# Whether two words are the same but for the case of their letters.
|
||||||
|
def same_letters(a: strview, b: strview): bool {
|
||||||
|
if a.length != b.length {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
for index in 0..a.length {
|
||||||
|
if a[index].to_lower != b[index].to_lower {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
@@ -0,0 +1,79 @@
|
|||||||
|
#! Contains painters, which give the color each pixel is painted: a color, or a
|
||||||
|
#! gradient's, from a table of 256 of them, premultiplied, along it, as far
|
||||||
|
#! along it as the pixel is, spread past its ends.
|
||||||
|
|
||||||
|
import std::math;
|
||||||
|
module malunal::image::svg;
|
||||||
|
|
||||||
|
|
||||||
|
# What paints: a color, or a gradient, whose colors a table of 256 holds,
|
||||||
|
# premultiplied, along it.
|
||||||
|
enum paint_by: u8 {
|
||||||
|
color,
|
||||||
|
linear,
|
||||||
|
radial,
|
||||||
|
}
|
||||||
|
|
||||||
|
enum spread: u8 {
|
||||||
|
pad,
|
||||||
|
reflect,
|
||||||
|
repeat,
|
||||||
|
}
|
||||||
|
|
||||||
|
struct painter {
|
||||||
|
var by: paint_by;
|
||||||
|
var color: f32[4]; #! Premultiplied, already scaled by the opacity.
|
||||||
|
var table: f32[1024]; #! A gradient's colors, premultiplied, already scaled by the opacity.
|
||||||
|
var inverse: matrix; #! From the canvas to the gradient's own space.
|
||||||
|
var spread: spread;
|
||||||
|
var x1: f64; #! A linear gradient's ends, or a radial one's center and focus.
|
||||||
|
var y1: f64;
|
||||||
|
var x2: f64;
|
||||||
|
var y2: f64;
|
||||||
|
var r: f64;
|
||||||
|
}
|
||||||
|
|
||||||
|
def painter::solid(paint: &color, opacity: f64): painter {
|
||||||
|
val alpha := (paint.a * opacity) as f32;
|
||||||
|
return painter { color = [paint.r as f32 * alpha, paint.g as f32 * alpha, paint.b as f32 * alpha, alpha] };
|
||||||
|
}
|
||||||
|
|
||||||
|
# The premultiplied color at the center of a pixel.
|
||||||
|
def painter::at(&this, x: u64, y: u64): f32[4] {
|
||||||
|
if this.by == paint_by::color {
|
||||||
|
return this.color;
|
||||||
|
}
|
||||||
|
val here := this.inverse.apply(point { x = x as f64 + 0.5, y = y as f64 + 0.5 });
|
||||||
|
var t: f64 = 0;
|
||||||
|
if this.by == paint_by::linear {
|
||||||
|
val dx := this.x2 - this.x1;
|
||||||
|
val dy := this.y2 - this.y1;
|
||||||
|
val length := dx * dx + dy * dy;
|
||||||
|
t = length == 0 ? 1 : ((here.x - this.x1) * dx + (here.y - this.y1) * dy) / length;
|
||||||
|
} else {
|
||||||
|
# Along the line from the focus through the pixel, as far as the circle is.
|
||||||
|
val dx := here.x - this.x2;
|
||||||
|
val dy := here.y - this.y2;
|
||||||
|
val ex := this.x2 - this.x1;
|
||||||
|
val ey := this.y2 - this.y1;
|
||||||
|
val a := dx * dx + dy * dy;
|
||||||
|
if a == 0 {
|
||||||
|
t = 0;
|
||||||
|
} else {
|
||||||
|
val b := ex * dx + ey * dy;
|
||||||
|
val c := ex * ex + ey * ey - this.r * this.r;
|
||||||
|
val reach := (-b + math::sqrt(math::max(0.0, b * b - a * c))) / a;
|
||||||
|
t = reach <= 0 ? 1 : 1 / reach;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if this.spread == spread::repeat {
|
||||||
|
t = t - math::floor(t);
|
||||||
|
} else if this.spread == spread::reflect {
|
||||||
|
t = t % 2;
|
||||||
|
t = t < 0 ? t + 2 : t;
|
||||||
|
t = t > 1 ? 2 - t : t;
|
||||||
|
}
|
||||||
|
t = t < 0 ? 0 : (t > 1 ? 1 : t);
|
||||||
|
val slot := (t * 255 + 0.5) as u64 * 4;
|
||||||
|
return [this.table[slot], this.table[slot + 1], this.table[slot + 2], this.table[slot + 3]];
|
||||||
|
}
|
||||||
@@ -0,0 +1,199 @@
|
|||||||
|
#! Contains paths: subpaths of lines and cubic curves, quadratics and arcs made
|
||||||
|
#! cubics, and the rectangles and ellipses SVG's shapes are made of.
|
||||||
|
|
||||||
|
import std::math;
|
||||||
|
module malunal::image::svg;
|
||||||
|
|
||||||
|
|
||||||
|
# What a path is made of: moves to begin each subpath, lines, cubic curves, each
|
||||||
|
# with its points after it, and closes.
|
||||||
|
enum verb: u8 {
|
||||||
|
move,
|
||||||
|
line,
|
||||||
|
cubic,
|
||||||
|
close,
|
||||||
|
}
|
||||||
|
|
||||||
|
# A path: subpaths of lines and cubic curves, quadratics and arcs made cubics.
|
||||||
|
struct path {
|
||||||
|
var verbs: vector<verb>;
|
||||||
|
var points: vector<point>;
|
||||||
|
var start: point; #! Where the subpath being made began.
|
||||||
|
var last: point; #! Where the path is.
|
||||||
|
var open: bool; #! Whether a subpath has begun, which a line or curve needs.
|
||||||
|
}
|
||||||
|
|
||||||
|
def path::new(): path {
|
||||||
|
return path { verbs = vector::<verb>::new(), points = vector::<point>::new() };
|
||||||
|
}
|
||||||
|
|
||||||
|
def path::move_to(&mut this, to: point): void {
|
||||||
|
this.verbs.append(verb::move);
|
||||||
|
this.points.append(to);
|
||||||
|
this.start = to;
|
||||||
|
this.last = to;
|
||||||
|
this.open = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
def path::line_to(&mut this, to: point): void {
|
||||||
|
this.begin();
|
||||||
|
this.verbs.append(verb::line);
|
||||||
|
this.points.append(to);
|
||||||
|
this.last = to;
|
||||||
|
}
|
||||||
|
|
||||||
|
def path::cubic_to(&mut this, first: point, second: point, to: point): void {
|
||||||
|
this.begin();
|
||||||
|
this.verbs.append(verb::cubic);
|
||||||
|
this.points.append(first);
|
||||||
|
this.points.append(second);
|
||||||
|
this.points.append(to);
|
||||||
|
this.last = to;
|
||||||
|
}
|
||||||
|
|
||||||
|
def path::quad_to(&mut this, control: point, to: point): void {
|
||||||
|
val from := this.last;
|
||||||
|
this.cubic_to(
|
||||||
|
point { x = from.x + (control.x - from.x) * 2 / 3, y = from.y + (control.y - from.y) * 2 / 3 },
|
||||||
|
point { x = to.x + (control.x - to.x) * 2 / 3, y = to.y + (control.y - to.y) * 2 / 3 },
|
||||||
|
to
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
def path::close(&mut this): void {
|
||||||
|
if this.open {
|
||||||
|
this.verbs.append(verb::close);
|
||||||
|
this.last = this.start;
|
||||||
|
this.open = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
# Begins a subpath where the path is, after a close, which a line or curve needs.
|
||||||
|
def path::begin(&mut this): void {
|
||||||
|
if !this.open {
|
||||||
|
this.move_to(this.last);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
def path::is_empty(&this): bool {
|
||||||
|
return this.verbs.empty;
|
||||||
|
}
|
||||||
|
|
||||||
|
# Appends an elliptical arc to a point, as SVG's `A` gives it: radii, the
|
||||||
|
# ellipse's rotation, and which of the four arcs, made cubics of at most a
|
||||||
|
# quarter turn each, as SVG's implementation notes say.
|
||||||
|
def path::arc_to(&mut this, radius_x: f64, radius_y: f64, degrees: f64, large: bool, sweep: bool, to: point): void {
|
||||||
|
val from := this.last;
|
||||||
|
if from.x == to.x && from.y == to.y {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
var rx := math::abs(radius_x);
|
||||||
|
var ry := math::abs(radius_y);
|
||||||
|
if rx == 0 || ry == 0 {
|
||||||
|
this.line_to(to);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
val angle := degrees * math::pi / 180;
|
||||||
|
val cos := math::cos(angle);
|
||||||
|
val sin := math::sin(angle);
|
||||||
|
val half_x := (from.x - to.x) / 2;
|
||||||
|
val half_y := (from.y - to.y) / 2;
|
||||||
|
val x1 := cos * half_x + sin * half_y;
|
||||||
|
val y1 := -sin * half_x + cos * half_y;
|
||||||
|
|
||||||
|
# Radii too small to reach are made just large enough.
|
||||||
|
val reach := (x1 * x1) / (rx * rx) + (y1 * y1) / (ry * ry);
|
||||||
|
if reach > 1 {
|
||||||
|
rx *= math::sqrt(reach);
|
||||||
|
ry *= math::sqrt(reach);
|
||||||
|
}
|
||||||
|
val numerator := rx * rx * ry * ry - rx * rx * y1 * y1 - ry * ry * x1 * x1;
|
||||||
|
val denominator := rx * rx * y1 * y1 + ry * ry * x1 * x1;
|
||||||
|
var scale := denominator == 0 ? 0.0 : math::sqrt(math::max(0.0, numerator / denominator));
|
||||||
|
if large == sweep {
|
||||||
|
scale = -scale;
|
||||||
|
}
|
||||||
|
val center_x1 := scale * rx * y1 / ry;
|
||||||
|
val center_y1 := -scale * ry * x1 / rx;
|
||||||
|
val center := point {
|
||||||
|
x = cos * center_x1 - sin * center_y1 + (from.x + to.x) / 2,
|
||||||
|
y = sin * center_x1 + cos * center_y1 + (from.y + to.y) / 2
|
||||||
|
};
|
||||||
|
|
||||||
|
val begin := math::atan2((y1 - center_y1) / ry, (x1 - center_x1) / rx);
|
||||||
|
var turn := math::atan2((-y1 - center_y1) / ry, (-x1 - center_x1) / rx) - begin;
|
||||||
|
if sweep && turn < 0 {
|
||||||
|
turn += 2 * math::pi;
|
||||||
|
} else if !sweep && turn > 0 {
|
||||||
|
turn -= 2 * math::pi;
|
||||||
|
}
|
||||||
|
|
||||||
|
val pieces := math::ceil(math::abs(turn) / (math::pi / 2) - 1e-9);
|
||||||
|
val count := pieces < 1 ? 1u : pieces as u64;
|
||||||
|
val step := turn / count as f64;
|
||||||
|
val handle := 4.0 / 3.0 * math::tan(step / 4);
|
||||||
|
for index in 0..count {
|
||||||
|
val t1 := begin + step * index as f64;
|
||||||
|
val t2 := t1 + step;
|
||||||
|
val c1 := math::cos(t1);
|
||||||
|
val s1 := math::sin(t1);
|
||||||
|
val c2 := math::cos(t2);
|
||||||
|
val s2 := math::sin(t2);
|
||||||
|
var end := on_ellipse(¢er, rx, ry, cos, sin, c2, s2);
|
||||||
|
if index == count - 1 {
|
||||||
|
end = to;
|
||||||
|
}
|
||||||
|
this.cubic_to(
|
||||||
|
on_ellipse(¢er, rx, ry, cos, sin, c1 - handle * s1, s1 + handle * c1),
|
||||||
|
on_ellipse(¢er, rx, ry, cos, sin, c2 + handle * s2, s2 - handle * c2),
|
||||||
|
end
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
# A point of the unit circle's plane, put on a rotated ellipse.
|
||||||
|
def on_ellipse(center: &point, rx: f64, ry: f64, cos: f64, sin: f64, x: f64, y: f64): point {
|
||||||
|
return point { x = center.x + rx * cos * x - ry * sin * y, y = center.y + rx * sin * x + ry * cos * y };
|
||||||
|
}
|
||||||
|
|
||||||
|
# The handles of a cubic making a quarter of a circle, for a radius of 1.
|
||||||
|
const kappa: f64 = 0.5522847498307936;
|
||||||
|
|
||||||
|
# Appends an ellipse, clockwise from its right.
|
||||||
|
def path::ellipse(&mut this, cx: f64, cy: f64, rx: f64, ry: f64): void {
|
||||||
|
val kx := rx * kappa;
|
||||||
|
val ky := ry * kappa;
|
||||||
|
this.move_to(point { x = cx + rx, y = cy });
|
||||||
|
this.cubic_to(point { x = cx + rx, y = cy + ky }, point { x = cx + kx, y = cy + ry }, point { x = cx, y = cy + ry });
|
||||||
|
this.cubic_to(point { x = cx - kx, y = cy + ry }, point { x = cx - rx, y = cy + ky }, point { x = cx - rx, y = cy });
|
||||||
|
this.cubic_to(point { x = cx - rx, y = cy - ky }, point { x = cx - kx, y = cy - ry }, point { x = cx, y = cy - ry });
|
||||||
|
this.cubic_to(point { x = cx + kx, y = cy - ry }, point { x = cx + rx, y = cy - ky }, point { x = cx + rx, y = cy });
|
||||||
|
this.close();
|
||||||
|
}
|
||||||
|
|
||||||
|
# Appends a rectangle, its corners rounded by radii, as SVG's `rect` is.
|
||||||
|
def path::rectangle(&mut this, x: f64, y: f64, width: f64, height: f64, rx: f64, ry: f64): void {
|
||||||
|
if rx <= 0 || ry <= 0 {
|
||||||
|
this.move_to(point { x = x, y = y });
|
||||||
|
this.line_to(point { x = x + width, y = y });
|
||||||
|
this.line_to(point { x = x + width, y = y + height });
|
||||||
|
this.line_to(point { x = x, y = y + height });
|
||||||
|
this.close();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
val kx := rx * kappa;
|
||||||
|
val ky := ry * kappa;
|
||||||
|
val right := x + width;
|
||||||
|
val bottom := y + height;
|
||||||
|
this.move_to(point { x = x + rx, y = y });
|
||||||
|
this.line_to(point { x = right - rx, y = y });
|
||||||
|
this.cubic_to(point { x = right - rx + kx, y = y }, point { x = right, y = y + ry - ky }, point { x = right, y = y + ry });
|
||||||
|
this.line_to(point { x = right, y = bottom - ry });
|
||||||
|
this.cubic_to(point { x = right, y = bottom - ry + ky }, point { x = right - rx + kx, y = bottom }, point { x = right - rx, y = bottom });
|
||||||
|
this.line_to(point { x = x + rx, y = bottom });
|
||||||
|
this.cubic_to(point { x = x + rx - kx, y = bottom }, point { x = x, y = bottom - ry + ky }, point { x = x, y = bottom - ry });
|
||||||
|
this.line_to(point { x = x, y = y + ry });
|
||||||
|
this.cubic_to(point { x = x, y = y + ry - ky }, point { x = x + rx - kx, y = y }, point { x = x + rx, y = y });
|
||||||
|
this.close();
|
||||||
|
}
|
||||||
@@ -0,0 +1,90 @@
|
|||||||
|
#! Contains SVG's path data, as a `path` element's `d` writes it, read into a
|
||||||
|
#! path.
|
||||||
|
|
||||||
|
module malunal::image::svg;
|
||||||
|
|
||||||
|
|
||||||
|
# Reads SVG's path data into a path, as far as it's written correctly, as SVG
|
||||||
|
# says to draw a path broken partway.
|
||||||
|
def parse_path(text: strview): path {
|
||||||
|
var made := path::new();
|
||||||
|
var read := numbers::of(text);
|
||||||
|
var command: u8 = 0;
|
||||||
|
var control := point {}; # The last curve's second control point, which `S` and `T` reflect.
|
||||||
|
var curved: u8 = 0; # Whether the last command was a cubic, `C`, or a quadratic, `Q`.
|
||||||
|
while !read.at_end() {
|
||||||
|
val byte := read.text[read.at];
|
||||||
|
if byte.is_alpha {
|
||||||
|
command = byte;
|
||||||
|
read.at++;
|
||||||
|
if command == 'Z' || command == 'z' {
|
||||||
|
made.close();
|
||||||
|
curved = 0;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
} else if command == 0 {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
val relative := command >= 'a';
|
||||||
|
val origin := relative ? made.last : point {};
|
||||||
|
val upper := command.to_upper;
|
||||||
|
var next_curved: u8 = 0;
|
||||||
|
if upper == 'M' {
|
||||||
|
val to := read.point() else { break; };
|
||||||
|
made.move_to(offset(to, &origin));
|
||||||
|
# Pairs after a move's first are lines.
|
||||||
|
command = relative ? 'l' : 'L';
|
||||||
|
} else if upper == 'L' {
|
||||||
|
val to := read.point() else { break; };
|
||||||
|
made.line_to(offset(to, &origin));
|
||||||
|
} else if upper == 'H' {
|
||||||
|
val x := read.next() else { break; };
|
||||||
|
made.line_to(point { x = relative ? made.last.x + x : x, y = made.last.y });
|
||||||
|
} else if upper == 'V' {
|
||||||
|
val y := read.next() else { break; };
|
||||||
|
made.line_to(point { x = made.last.x, y = relative ? made.last.y + y : y });
|
||||||
|
} else if upper == 'C' || upper == 'S' {
|
||||||
|
var first := made.last;
|
||||||
|
if upper == 'C' {
|
||||||
|
val given := read.point() else { break; };
|
||||||
|
first = offset(given, &origin);
|
||||||
|
} else if curved == 'C' {
|
||||||
|
first = point { x = 2 * made.last.x - control.x, y = 2 * made.last.y - control.y };
|
||||||
|
}
|
||||||
|
val second := read.point() else { break; };
|
||||||
|
val to := read.point() else { break; };
|
||||||
|
control = offset(second, &origin);
|
||||||
|
made.cubic_to(first, control, offset(to, &origin));
|
||||||
|
next_curved = 'C';
|
||||||
|
} else if upper == 'Q' || upper == 'T' {
|
||||||
|
var middle := made.last;
|
||||||
|
if upper == 'Q' {
|
||||||
|
val given := read.point() else { break; };
|
||||||
|
middle = offset(given, &origin);
|
||||||
|
} else if curved == 'Q' {
|
||||||
|
middle = point { x = 2 * made.last.x - control.x, y = 2 * made.last.y - control.y };
|
||||||
|
}
|
||||||
|
val to := read.point() else { break; };
|
||||||
|
control = middle;
|
||||||
|
made.quad_to(middle, offset(to, &origin));
|
||||||
|
next_curved = 'Q';
|
||||||
|
} else if upper == 'A' {
|
||||||
|
val rx := read.next() else { break; };
|
||||||
|
val ry := read.next() else { break; };
|
||||||
|
val degrees := read.next() else { break; };
|
||||||
|
val large := read.flag() else { break; };
|
||||||
|
val sweep := read.flag() else { break; };
|
||||||
|
val to := read.point() else { break; };
|
||||||
|
made.arc_to(rx, ry, degrees, large, sweep, offset(to, &origin));
|
||||||
|
} else {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
curved = next_curved;
|
||||||
|
}
|
||||||
|
return made;
|
||||||
|
}
|
||||||
|
|
||||||
|
def offset(at: point, by: &point): point {
|
||||||
|
return point { x = at.x + by.x, y = at.y + by.y };
|
||||||
|
}
|
||||||
@@ -0,0 +1,200 @@
|
|||||||
|
#! Contains the rasterizer, which fills polygons, by either rule, with sixteen
|
||||||
|
#! rows of samples down each pixel and each span's coverage across it worked
|
||||||
|
#! out exactly, painting each pixel by how much it's covered.
|
||||||
|
|
||||||
|
import std::math;
|
||||||
|
module malunal::image::svg;
|
||||||
|
|
||||||
|
|
||||||
|
# How many rows of samples each row of pixels is covered by.
|
||||||
|
const samples: u64 = 16;
|
||||||
|
|
||||||
|
# An edge of a polygon, from its top to its bottom, and which way it went.
|
||||||
|
struct edge {
|
||||||
|
var x0: f64;
|
||||||
|
var y0: f64;
|
||||||
|
var y1: f64;
|
||||||
|
var slope: f64; #! How far across it goes each row down.
|
||||||
|
var winding: i32;
|
||||||
|
}
|
||||||
|
|
||||||
|
struct crossing {
|
||||||
|
var x: f64;
|
||||||
|
var winding: i32;
|
||||||
|
}
|
||||||
|
|
||||||
|
# What the rasterizer keeps between polygons, so it allocates little.
|
||||||
|
struct raster {
|
||||||
|
var width: u64;
|
||||||
|
var height: u64;
|
||||||
|
var edges: vector<edge>;
|
||||||
|
var active: vector<u64>;
|
||||||
|
var crossings: vector<crossing>;
|
||||||
|
var cover: vector<f32>; #! How much more each pixel is covered than the one before, by spans across it.
|
||||||
|
var area: vector<f32>; #! How much of each pixel spans end within.
|
||||||
|
}
|
||||||
|
|
||||||
|
def raster::new(width: u64, height: u64): raster {
|
||||||
|
var made := raster {
|
||||||
|
width = width, height = height,
|
||||||
|
edges = vector::<edge>::new(), active = vector::<u64>::new(), crossings = vector::<crossing>::new(),
|
||||||
|
cover = vector::<f32>::new(), area = vector::<f32>::new()
|
||||||
|
};
|
||||||
|
made.cover.resize(width + 2);
|
||||||
|
made.area.resize(width + 2);
|
||||||
|
return made;
|
||||||
|
}
|
||||||
|
|
||||||
|
# Fills the polygons of an outline, each contour closed, by the nonzero rule or
|
||||||
|
# the even-odd one, painting each pixel by how much it covers.
|
||||||
|
def raster::fill(&mut this, shape: &outline, even_odd: bool, paint: &painter, target: slice<u8>): void {
|
||||||
|
this.edges.clear();
|
||||||
|
var top := math::infinity::<f64>();
|
||||||
|
var bottom := -math::infinity::<f64>();
|
||||||
|
for held in shape.contours {
|
||||||
|
if held.count < 2 {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
for index in 0..held.count {
|
||||||
|
val a := shape.points[held.start + index];
|
||||||
|
val b := shape.points[held.start + (index + 1) % held.count];
|
||||||
|
if a.y == b.y || !math::is_finite(a.x) || !math::is_finite(a.y) || !math::is_finite(b.x) || !math::is_finite(b.y) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
val down := a.y < b.y;
|
||||||
|
val upper := down ? a : b;
|
||||||
|
val lower := down ? b : a;
|
||||||
|
this.edges.append(edge {
|
||||||
|
x0 = upper.x, y0 = upper.y, y1 = lower.y,
|
||||||
|
slope = (lower.x - upper.x) / (lower.y - upper.y),
|
||||||
|
winding = down ? 1 : -1
|
||||||
|
});
|
||||||
|
top = upper.y < top ? upper.y : top;
|
||||||
|
bottom = lower.y > bottom ? lower.y : bottom;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if this.edges.empty || bottom <= 0 || top >= this.height as f64 {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
this.edges.sort_by(def(a: &edge, b: &edge): bool => a.y0 < b.y0);
|
||||||
|
|
||||||
|
val first_row: u64 = top <= 0 ? 0 : math::floor(top) as u64;
|
||||||
|
val end_row: u64 = bottom >= this.height as f64 ? this.height : math::ceil(bottom) as u64;
|
||||||
|
val weight: f32 = 1.0 / samples as f32;
|
||||||
|
var next: u64 = 0;
|
||||||
|
this.active.clear();
|
||||||
|
for row in first_row..end_row {
|
||||||
|
# Edges begin above the row's bottom, and end below its top.
|
||||||
|
while next < this.edges.length && this.edges[next].y0 < (row + 1) as f64 {
|
||||||
|
this.active.append(next);
|
||||||
|
next++;
|
||||||
|
}
|
||||||
|
var kept: u64 = 0;
|
||||||
|
for index in 0..this.active.length {
|
||||||
|
val which := this.active[index];
|
||||||
|
if this.edges[which].y1 > row as f64 {
|
||||||
|
this.active[kept] = which;
|
||||||
|
kept++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
this.active.resize(kept);
|
||||||
|
|
||||||
|
var left := this.width;
|
||||||
|
var right: u64 = 0;
|
||||||
|
for sample in 0..samples {
|
||||||
|
val y := row as f64 + (sample as f64 + 0.5) / samples as f64;
|
||||||
|
this.crossings.clear();
|
||||||
|
for index in 0..this.active.length {
|
||||||
|
val held := &this.edges[this.active[index]];
|
||||||
|
if held.y0 <= y && y < held.y1 {
|
||||||
|
this.crossings.append(crossing { x = held.x0 + (y - held.y0) * held.slope, winding = held.winding });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if this.crossings.length < 2 {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
# Few cross a row, so they're ordered by insertion.
|
||||||
|
for index in 1..this.crossings.length {
|
||||||
|
var back := index;
|
||||||
|
while back > 0 && this.crossings[back].x < this.crossings[back - 1].x {
|
||||||
|
val swap := this.crossings[back];
|
||||||
|
this.crossings[back] = this.crossings[back - 1];
|
||||||
|
this.crossings[back - 1] = swap;
|
||||||
|
back--;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
var winding: i32 = 0;
|
||||||
|
for index in 0..this.crossings.length - 1 {
|
||||||
|
winding += this.crossings[index].winding;
|
||||||
|
val inside := even_odd ? (winding & 1) != 0 : winding != 0;
|
||||||
|
if inside {
|
||||||
|
val span := this.span(this.crossings[index].x, this.crossings[index + 1].x, weight);
|
||||||
|
left = span[0] < left ? span[0] : left;
|
||||||
|
right = span[1] > right ? span[1] : right;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if left <= right && left < this.width {
|
||||||
|
this.paint_row(row, left, right, paint, target);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
# Covers a span of a row of samples, from one place across it to another.
|
||||||
|
# @returns The first and last pixels it touches.
|
||||||
|
def raster::span(&mut this, from: f64, to: f64, weight: f32): u64[2] {
|
||||||
|
val width := this.width as f64;
|
||||||
|
val start := from < 0 ? 0.0 : from;
|
||||||
|
val end := to > width ? width : to;
|
||||||
|
if end <= start {
|
||||||
|
return [this.width, 0];
|
||||||
|
}
|
||||||
|
val first := start as u64;
|
||||||
|
val last := end as u64;
|
||||||
|
if first == last {
|
||||||
|
this.area[first] += (end - start) as f32 * weight;
|
||||||
|
return [first, last];
|
||||||
|
}
|
||||||
|
this.area[first] += (first as f64 + 1 - start) as f32 * weight;
|
||||||
|
this.cover[first + 1] += weight;
|
||||||
|
this.cover[last] -= weight;
|
||||||
|
if last < this.width {
|
||||||
|
this.area[last] += (end - last as f64) as f32 * weight;
|
||||||
|
}
|
||||||
|
return [first, last];
|
||||||
|
}
|
||||||
|
|
||||||
|
# Paints a row's pixels by how much they're covered, and clears its coverage.
|
||||||
|
def raster::paint_row(&mut this, row: u64, left: u64, right: u64, paint: &painter, target: slice<u8>): void {
|
||||||
|
var running: f32 = 0;
|
||||||
|
val last := right < this.width ? right : this.width - 1;
|
||||||
|
for x in left..=last {
|
||||||
|
running += this.cover[x];
|
||||||
|
var covered := running + this.area[x];
|
||||||
|
this.cover[x] = 0;
|
||||||
|
this.area[x] = 0;
|
||||||
|
if covered > 0.001 {
|
||||||
|
covered = covered > 1 ? 1 : covered;
|
||||||
|
blend(target, (row * this.width + x) * 4, paint.at(x, row), covered);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for x in (last + 1)..(right + 2) {
|
||||||
|
if x < this.cover.length {
|
||||||
|
this.cover[x] = 0;
|
||||||
|
this.area[x] = 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
# Draws a premultiplied color over a pixel, as much as covers it.
|
||||||
|
def blend(target: slice<u8>, at: u64, color: f32[4], covered: f32): void {
|
||||||
|
val alpha := color[3] * covered;
|
||||||
|
if alpha <= 0 {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
val keep := 1 - alpha;
|
||||||
|
for channel in 0u..4u {
|
||||||
|
val value := color[channel] * covered * 255 + target[at + channel] as f32 * keep;
|
||||||
|
target[at + channel] = (value + 0.5) as u8;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,115 @@
|
|||||||
|
#! Contains SVG's shapes: the path of each kind of shape element, and a shape
|
||||||
|
#! drawn, filled and then stroked.
|
||||||
|
|
||||||
|
import std::math;
|
||||||
|
import std::xml;
|
||||||
|
module malunal::image::svg;
|
||||||
|
|
||||||
|
|
||||||
|
# Draws a shape: its fill, then its stroke.
|
||||||
|
# @returns Its bounds in its user space, which gradients, clips, and masks may
|
||||||
|
# be measured by.
|
||||||
|
def renderer::shape(&mut this, at: &xml::element, own: &style, placed: &matrix, opacity: f64): maybe<point[2]> {
|
||||||
|
val geometry := this.geometry_of(at);
|
||||||
|
if geometry.is_empty() {
|
||||||
|
return nothing {};
|
||||||
|
}
|
||||||
|
val stretch := placed.stretch();
|
||||||
|
if stretch <= 0 || !math::is_finite(stretch) {
|
||||||
|
return nothing {};
|
||||||
|
}
|
||||||
|
val user := flatten(&geometry, &matrix {}, tolerance / stretch);
|
||||||
|
val bounds := user.bounds();
|
||||||
|
if !own.visible {
|
||||||
|
return bounds;
|
||||||
|
}
|
||||||
|
|
||||||
|
if this.clipping {
|
||||||
|
this.canvas.fill(&user.transformed(placed), own.clip_even_odd, &painter::solid(&color { r = 1, g = 1, b = 1 }, 1));
|
||||||
|
return bounds;
|
||||||
|
}
|
||||||
|
if this.painter_for(&own.fill, own, own.fill_opacity * opacity, &bounds, placed) is some(fill) {
|
||||||
|
this.canvas.fill(&user.transformed(placed), own.even_odd, &fill);
|
||||||
|
}
|
||||||
|
if own.stroke_width > 0 {
|
||||||
|
if this.painter_for(&own.stroke, own, own.stroke_opacity * opacity, &bounds, placed) is some(stroke_paint) {
|
||||||
|
val with := pen {
|
||||||
|
half = own.stroke_width / 2,
|
||||||
|
cap = own.cap,
|
||||||
|
join = own.join,
|
||||||
|
miter_limit = own.miter_limit,
|
||||||
|
dashes = own.dashes,
|
||||||
|
dash_count = own.dash_count,
|
||||||
|
dash_offset = own.dash_offset,
|
||||||
|
within = tolerance / stretch
|
||||||
|
};
|
||||||
|
val outlined := stroke(&user, &with);
|
||||||
|
this.canvas.fill(&outlined.transformed(placed), false, &stroke_paint);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return bounds;
|
||||||
|
}
|
||||||
|
|
||||||
|
# The path of a shape element, in its user space, or an empty one where it has
|
||||||
|
# no area or length, as a rectangle of no width hasn't.
|
||||||
|
def renderer::geometry_of(&this, at: &xml::element): path {
|
||||||
|
var made := path::new();
|
||||||
|
val name := at.local;
|
||||||
|
if name == "path" {
|
||||||
|
val data := at.attribute("d") else { return made; };
|
||||||
|
return parse_path(data);
|
||||||
|
}
|
||||||
|
if name == "rect" {
|
||||||
|
val x := this.length_of(at, "x", axis::x, 0);
|
||||||
|
val y := this.length_of(at, "y", axis::y, 0);
|
||||||
|
val width := this.length_of(at, "width", axis::x, 0);
|
||||||
|
val height := this.length_of(at, "height", axis::y, 0);
|
||||||
|
if width <= 0 || height <= 0 {
|
||||||
|
return made;
|
||||||
|
}
|
||||||
|
var rx := this.length_of(at, "rx", axis::x, -1);
|
||||||
|
var ry := this.length_of(at, "ry", axis::y, -1);
|
||||||
|
if rx < 0 {
|
||||||
|
rx = ry;
|
||||||
|
}
|
||||||
|
if ry < 0 {
|
||||||
|
ry = rx;
|
||||||
|
}
|
||||||
|
rx = math::min(math::max(rx, 0.0), width / 2);
|
||||||
|
ry = math::min(math::max(ry, 0.0), height / 2);
|
||||||
|
made.rectangle(x, y, width, height, rx, ry);
|
||||||
|
} else if name == "circle" {
|
||||||
|
val r := this.length_of(at, "r", axis::diagonal, 0);
|
||||||
|
if r > 0 {
|
||||||
|
made.ellipse(this.length_of(at, "cx", axis::x, 0), this.length_of(at, "cy", axis::y, 0), r, r);
|
||||||
|
}
|
||||||
|
} else if name == "ellipse" {
|
||||||
|
var rx := this.length_of(at, "rx", axis::x, -1);
|
||||||
|
var ry := this.length_of(at, "ry", axis::y, -1);
|
||||||
|
rx = rx < 0 ? ry : rx;
|
||||||
|
ry = ry < 0 ? rx : ry;
|
||||||
|
if rx > 0 && ry > 0 {
|
||||||
|
made.ellipse(this.length_of(at, "cx", axis::x, 0), this.length_of(at, "cy", axis::y, 0), rx, ry);
|
||||||
|
}
|
||||||
|
} else if name == "line" {
|
||||||
|
made.move_to(point { x = this.length_of(at, "x1", axis::x, 0), y = this.length_of(at, "y1", axis::y, 0) });
|
||||||
|
made.line_to(point { x = this.length_of(at, "x2", axis::x, 0), y = this.length_of(at, "y2", axis::y, 0) });
|
||||||
|
} else if name == "polyline" || name == "polygon" {
|
||||||
|
val written := at.attribute("points") else { return made; };
|
||||||
|
var read := numbers::of(written);
|
||||||
|
var first := true;
|
||||||
|
while true {
|
||||||
|
val at_point := read.point() else { break; };
|
||||||
|
if first {
|
||||||
|
made.move_to(at_point);
|
||||||
|
first = false;
|
||||||
|
} else {
|
||||||
|
made.line_to(at_point);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if name == "polygon" && !first {
|
||||||
|
made.close();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return made;
|
||||||
|
}
|
||||||
@@ -0,0 +1,276 @@
|
|||||||
|
#! Contains the rules of an SVG's `<style>` sheets: each selector of types,
|
||||||
|
#! classes, and IDs, and descendant and child combinators, read with how
|
||||||
|
#! specific it is, and those matching an element applied the least specific
|
||||||
|
#! first.
|
||||||
|
|
||||||
|
import std::xml;
|
||||||
|
module malunal::image::svg;
|
||||||
|
|
||||||
|
|
||||||
|
# How a selector's compound relates to the one before it.
|
||||||
|
enum combinator: u8 {
|
||||||
|
none, #! It's the first.
|
||||||
|
descendant, #! Within it, however deep, as a space says.
|
||||||
|
child, #! Within it directly, as `>` says.
|
||||||
|
}
|
||||||
|
|
||||||
|
# A compound selector: a type, an ID, and classes, each of which may be left out.
|
||||||
|
struct compound {
|
||||||
|
var tag: strview; #! Empty, or `*`, for any.
|
||||||
|
var id: strview;
|
||||||
|
var classes: strview; #! As written, as `.a.b`.
|
||||||
|
var combinator: combinator;
|
||||||
|
}
|
||||||
|
|
||||||
|
# A rule of a style sheet: one of its selectors, how specific it is, where it
|
||||||
|
# stands, and its declarations.
|
||||||
|
struct rule {
|
||||||
|
var first: u64; #! Its compounds, in the sheet's.
|
||||||
|
var count: u64;
|
||||||
|
var specificity: u64;
|
||||||
|
var order: u64;
|
||||||
|
var body: strview;
|
||||||
|
}
|
||||||
|
|
||||||
|
# The rules of an SVG's `<style>` sheets.
|
||||||
|
struct sheet {
|
||||||
|
var texts: vector<string>; #! Each sheet's text, without its comments, which the rules view.
|
||||||
|
var compounds: vector<compound>;
|
||||||
|
var rules: vector<rule>;
|
||||||
|
}
|
||||||
|
|
||||||
|
def sheet::new(): sheet {
|
||||||
|
return sheet { texts = vector::<string>::new(), compounds = vector::<compound>::new(), rules = vector::<rule>::new() };
|
||||||
|
}
|
||||||
|
|
||||||
|
# Reads a style sheet's rules, skipping at-rules, and selectors of what isn't
|
||||||
|
# matched: attributes, pseudo-classes, and siblings.
|
||||||
|
def sheet::add(&mut this, written: strview): void {
|
||||||
|
# Comments are taken out first.
|
||||||
|
var text := string::new(nothing {});
|
||||||
|
var at: u64 = 0;
|
||||||
|
while at < written.length {
|
||||||
|
if written.substr(at, 2) == "/*" {
|
||||||
|
val end := written.substr(at + 2, written.length - at - 2).find("*/") else { break; };
|
||||||
|
at += end + 4;
|
||||||
|
text.push(' ');
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
text.push(written[at]);
|
||||||
|
at++;
|
||||||
|
}
|
||||||
|
this.texts.append(move(text));
|
||||||
|
val source := this.texts.last.span;
|
||||||
|
|
||||||
|
at = 0;
|
||||||
|
while at < source.length {
|
||||||
|
while at < source.length && source[at].is_space {
|
||||||
|
at++;
|
||||||
|
}
|
||||||
|
if at >= source.length {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
val open := source.substr(at, source.length - at).find("{") else { break; };
|
||||||
|
val prelude := source.substr(at, open).trim();
|
||||||
|
val body_start := at + open + 1;
|
||||||
|
# The body ends at the brace matching its own, past any within.
|
||||||
|
var end := body_start;
|
||||||
|
var depth := 1;
|
||||||
|
while end < source.length && depth > 0 {
|
||||||
|
if source[end] == '{' {
|
||||||
|
depth++;
|
||||||
|
} else if source[end] == '}' {
|
||||||
|
depth--;
|
||||||
|
}
|
||||||
|
end++;
|
||||||
|
}
|
||||||
|
val body := source.substr(body_start, end - body_start - 1);
|
||||||
|
at = end;
|
||||||
|
if prelude.starts_with("@") {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
var from: u64 = 0;
|
||||||
|
while from <= prelude.length {
|
||||||
|
val comma := prelude.substr(from, prelude.length - from).find(",") else prelude.length - from;
|
||||||
|
this.add_selector(prelude.substr(from, comma).trim(), body);
|
||||||
|
from += comma + 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
def sheet::add_selector(&mut this, selector: strview, body: strview): void {
|
||||||
|
if selector.length == 0 || selector.find_any("[:+~") is some(_) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
val first := this.compounds.length;
|
||||||
|
var specificity: u64 = 0;
|
||||||
|
var next := combinator::none;
|
||||||
|
var at: u64 = 0;
|
||||||
|
while at < selector.length {
|
||||||
|
while at < selector.length && selector[at].is_space {
|
||||||
|
if next == combinator::none && this.compounds.length > first {
|
||||||
|
next = combinator::descendant;
|
||||||
|
}
|
||||||
|
at++;
|
||||||
|
}
|
||||||
|
if at >= selector.length {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
if selector[at] == '>' {
|
||||||
|
next = combinator::child;
|
||||||
|
at++;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
# A compound: a type or `*`, then `#id` and `.class` in any order.
|
||||||
|
var made := compound { combinator = this.compounds.length > first ? next : combinator::none };
|
||||||
|
var end := at;
|
||||||
|
while end < selector.length && !selector[end].is_space && selector[end] != '>' {
|
||||||
|
end++;
|
||||||
|
}
|
||||||
|
val written := selector.substr(at, end - at);
|
||||||
|
var part := 0u;
|
||||||
|
while part < written.length && written[part] != '#' && written[part] != '.' {
|
||||||
|
part++;
|
||||||
|
}
|
||||||
|
made.tag = written.substr(0, part);
|
||||||
|
if made.tag.length != 0 && made.tag != "*" {
|
||||||
|
specificity += 1;
|
||||||
|
}
|
||||||
|
var classes_start := part;
|
||||||
|
var classes_end := part;
|
||||||
|
while part < written.length {
|
||||||
|
var stop := part + 1;
|
||||||
|
while stop < written.length && written[stop] != '#' && written[stop] != '.' {
|
||||||
|
stop++;
|
||||||
|
}
|
||||||
|
if written[part] == '#' {
|
||||||
|
made.id = written.substr(part + 1, stop - part - 1);
|
||||||
|
specificity += 10000;
|
||||||
|
} else {
|
||||||
|
if classes_end == classes_start {
|
||||||
|
classes_start = part;
|
||||||
|
}
|
||||||
|
classes_end = stop;
|
||||||
|
specificity += 100;
|
||||||
|
}
|
||||||
|
part = stop;
|
||||||
|
}
|
||||||
|
made.classes = written.substr(classes_start, classes_end - classes_start);
|
||||||
|
this.compounds.append(made);
|
||||||
|
next = combinator::none;
|
||||||
|
at = end;
|
||||||
|
}
|
||||||
|
if this.compounds.length == first {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
this.rules.append(rule {
|
||||||
|
first = first,
|
||||||
|
count = this.compounds.length - first,
|
||||||
|
specificity = specificity,
|
||||||
|
order = this.rules.length,
|
||||||
|
body = body
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
# Sets the properties of the rules matching an element, the least specific
|
||||||
|
# first, and of those equally specific, the first written first.
|
||||||
|
def sheet::apply(&this, at: &xml::element, made: &mut style, parent: &style, view: &viewport): void {
|
||||||
|
var matched := vector::<u64>::new();
|
||||||
|
for index in 0..this.rules.length {
|
||||||
|
val held := &this.rules[index];
|
||||||
|
if this.matches(held, held.count - 1, at) {
|
||||||
|
matched.append(index);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
# Few match any element, so they're ordered by insertion.
|
||||||
|
for index in 1..matched.length {
|
||||||
|
var back := index;
|
||||||
|
while back > 0 && this.before(matched[back], matched[back - 1]) {
|
||||||
|
val swap := matched[back];
|
||||||
|
matched[back] = matched[back - 1];
|
||||||
|
matched[back - 1] = swap;
|
||||||
|
back--;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for index in matched {
|
||||||
|
made.declare(this.rules[index].body, parent, view);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
def sheet::before(&this, first: u64, second: u64): bool {
|
||||||
|
val a := &this.rules[first];
|
||||||
|
val b := &this.rules[second];
|
||||||
|
return a.specificity < b.specificity || (a.specificity == b.specificity && a.order < b.order);
|
||||||
|
}
|
||||||
|
|
||||||
|
# Whether an element matches a rule's compounds up to one, from the last back.
|
||||||
|
def sheet::matches(&this, held: &rule, last: u64, at: &xml::element): bool {
|
||||||
|
val part := &this.compounds[held.first + last];
|
||||||
|
if !matches_compound(part, at) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if last == 0 {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
var above := at.parent;
|
||||||
|
if part.combinator == combinator::child {
|
||||||
|
val parent := above else { return false; };
|
||||||
|
return this.matches(held, last - 1, &parent);
|
||||||
|
}
|
||||||
|
while above is some(ancestor) {
|
||||||
|
if this.matches(held, last - 1, &ancestor) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
above = ancestor.parent;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
def matches_compound(part: &compound, at: &xml::element): bool {
|
||||||
|
if part.tag.length != 0 && part.tag != "*" && part.tag != at.local {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if part.id.length != 0 {
|
||||||
|
val id := at.attribute("id") else { return false; };
|
||||||
|
if id != part.id {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if part.classes.length == 0 {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
val classes := at.attribute("class") else { return false; };
|
||||||
|
var from: u64 = 1;
|
||||||
|
while from < part.classes.length {
|
||||||
|
var stop := from;
|
||||||
|
while stop < part.classes.length && part.classes[stop] != '.' {
|
||||||
|
stop++;
|
||||||
|
}
|
||||||
|
if !has_word(classes, part.classes.substr(from, stop - from)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
from = stop + 1;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
# Whether whitespace-separated words hold one.
|
||||||
|
def has_word(words: strview, word: strview): bool {
|
||||||
|
var at: u64 = 0;
|
||||||
|
while at < words.length {
|
||||||
|
while at < words.length && words[at].is_space {
|
||||||
|
at++;
|
||||||
|
}
|
||||||
|
var end := at;
|
||||||
|
while end < words.length && !words[end].is_space {
|
||||||
|
end++;
|
||||||
|
}
|
||||||
|
if end > at && words.substr(at, end - at) == word {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
at = end;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
@@ -0,0 +1,244 @@
|
|||||||
|
#! Contains the stroker, which makes a stroke of an outline the polygons it
|
||||||
|
#! covers: a quadrilateral along each line, the joins between them, and the
|
||||||
|
#! caps at the ends of polylines, dashed first.
|
||||||
|
|
||||||
|
import std::math;
|
||||||
|
module malunal::image::svg;
|
||||||
|
|
||||||
|
|
||||||
|
# What strokes an outline: half its width, and how its ends, corners, and dashes
|
||||||
|
# are drawn.
|
||||||
|
struct pen {
|
||||||
|
var half: f64;
|
||||||
|
var cap: line_cap;
|
||||||
|
var join: line_join;
|
||||||
|
var miter_limit: f64;
|
||||||
|
var dashes: f64[16];
|
||||||
|
var dash_count: u64;
|
||||||
|
var dash_offset: f64;
|
||||||
|
var within: f64; #! How far round ends and corners may stray from a circle.
|
||||||
|
}
|
||||||
|
|
||||||
|
# The polygons a stroke of an outline covers: a quadrilateral along each line,
|
||||||
|
# the corners between them, and the ends of polylines, dashed first.
|
||||||
|
def stroke(shape: &outline, with: &pen): outline {
|
||||||
|
var made := outline::new();
|
||||||
|
var piece := vector::<point>::new();
|
||||||
|
for held in shape.contours {
|
||||||
|
val points := shape.points.span[held.start:held.count];
|
||||||
|
if with.dash_count == 0 {
|
||||||
|
stroke_polyline(points, held.closed, with, &mut made);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
dash(points, held.closed, with, &mut piece, &mut made);
|
||||||
|
}
|
||||||
|
return made;
|
||||||
|
}
|
||||||
|
|
||||||
|
# Strokes the dashes of a polyline, the pattern begun again at each, at its
|
||||||
|
# offset.
|
||||||
|
def dash(points: span<point>, closed: bool, with: &pen, piece: &mut vector<point>, made: &mut outline): void {
|
||||||
|
var total: f64 = 0;
|
||||||
|
for index in 0..with.dash_count {
|
||||||
|
total += with.dashes[index];
|
||||||
|
}
|
||||||
|
# Where in the pattern the polyline begins.
|
||||||
|
var which: u64 = 0;
|
||||||
|
var offset := with.dash_offset % total;
|
||||||
|
if offset < 0 {
|
||||||
|
offset += total;
|
||||||
|
}
|
||||||
|
while offset >= with.dashes[which] {
|
||||||
|
offset -= with.dashes[which];
|
||||||
|
which = (which + 1) % with.dash_count;
|
||||||
|
}
|
||||||
|
var left := with.dashes[which] - offset;
|
||||||
|
|
||||||
|
piece.clear();
|
||||||
|
if which % 2 == 0 {
|
||||||
|
piece.append(points[0]);
|
||||||
|
}
|
||||||
|
val segments := closed ? points.length : points.length - 1;
|
||||||
|
for index in 0..segments {
|
||||||
|
val a := points[index];
|
||||||
|
val b := points[(index + 1) % points.length];
|
||||||
|
val length := math::hypot(b.x - a.x, b.y - a.y);
|
||||||
|
var along: f64 = 0;
|
||||||
|
while length - along > left {
|
||||||
|
along += left;
|
||||||
|
val at := point { x = a.x + (b.x - a.x) * along / length, y = a.y + (b.y - a.y) * along / length };
|
||||||
|
if which % 2 == 0 {
|
||||||
|
piece.append(at);
|
||||||
|
stroke_polyline(piece.span, false, with, made);
|
||||||
|
piece.clear();
|
||||||
|
} else {
|
||||||
|
piece.append(at);
|
||||||
|
}
|
||||||
|
which = (which + 1) % with.dash_count;
|
||||||
|
left = with.dashes[which];
|
||||||
|
}
|
||||||
|
left -= length - along;
|
||||||
|
if which % 2 == 0 {
|
||||||
|
piece.append(b);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if which % 2 == 0 && !piece.empty {
|
||||||
|
stroke_polyline(piece.span, false, with, made);
|
||||||
|
}
|
||||||
|
piece.clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
# Strokes a polyline, or a polygon.
|
||||||
|
def stroke_polyline(given: span<point>, closed_given: bool, with: &pen, made: &mut outline): void {
|
||||||
|
# Points the same as the one before add nothing.
|
||||||
|
var points := vector::<point>::new();
|
||||||
|
for at in given {
|
||||||
|
if points.empty || !same_point(at, points.last) {
|
||||||
|
points.append(at);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
var closed := closed_given;
|
||||||
|
if closed && points.length > 1 && same_point(points[0], points.last) {
|
||||||
|
points.truncate();
|
||||||
|
}
|
||||||
|
if points.length == 0 {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if points.length == 1 {
|
||||||
|
# A path of no length is drawn by its caps alone.
|
||||||
|
if with.cap == line_cap::round {
|
||||||
|
circle(points[0], with.half, with, made);
|
||||||
|
} else if with.cap == line_cap::square {
|
||||||
|
val at := points[0];
|
||||||
|
val h := with.half;
|
||||||
|
made.polygon([point { x = at.x - h, y = at.y - h }, point { x = at.x + h, y = at.y - h },
|
||||||
|
point { x = at.x + h, y = at.y + h }, point { x = at.x - h, y = at.y + h }]);
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if points.length == 2 {
|
||||||
|
closed = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
val count := points.length;
|
||||||
|
val segments := closed ? count : count - 1;
|
||||||
|
for index in 0..segments {
|
||||||
|
val a := points[index];
|
||||||
|
val b := points[(index + 1) % count];
|
||||||
|
val across := normal(a, b, with.half);
|
||||||
|
made.polygon([offset(a, &across), offset(b, &across), point { x = b.x - across.x, y = b.y - across.y },
|
||||||
|
point { x = a.x - across.x, y = a.y - across.y }]);
|
||||||
|
}
|
||||||
|
|
||||||
|
val first_corner: u64 = closed ? 0 : 1;
|
||||||
|
val last_corner := closed ? count : count - 1;
|
||||||
|
for index in first_corner..last_corner {
|
||||||
|
val before := points[(index + count - 1) % count];
|
||||||
|
val here := points[index];
|
||||||
|
val after := points[(index + 1) % count];
|
||||||
|
corner(before, here, after, with, made);
|
||||||
|
}
|
||||||
|
if !closed {
|
||||||
|
end_cap(points[1], points[0], with, made);
|
||||||
|
end_cap(points[count - 2], points[count - 1], with, made);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
# The corner where a line from one point to another turns to a third: a miter,
|
||||||
|
# where it's no longer than the limit, a bevel, or a round, on its outer side.
|
||||||
|
def corner(before: point, here: point, after: point, with: &pen, made: &mut outline): void {
|
||||||
|
val in_length := math::hypot(here.x - before.x, here.y - before.y);
|
||||||
|
val out_length := math::hypot(after.x - here.x, after.y - here.y);
|
||||||
|
val in_x := (here.x - before.x) / in_length;
|
||||||
|
val in_y := (here.y - before.y) / in_length;
|
||||||
|
val out_x := (after.x - here.x) / out_length;
|
||||||
|
val out_y := (after.y - here.y) / out_length;
|
||||||
|
val cross := in_x * out_y - in_y * out_x;
|
||||||
|
val dot := in_x * out_x + in_y * out_y;
|
||||||
|
if math::abs(cross) < 1e-12 && dot > 0 {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
# The outer side is the one the line turns from.
|
||||||
|
val side := cross > 0 ? -with.half : with.half;
|
||||||
|
val first := point { x = -in_y * side, y = in_x * side };
|
||||||
|
val second := point { x = -out_y * side, y = out_x * side };
|
||||||
|
val a := offset(here, &first);
|
||||||
|
val b := offset(here, &second);
|
||||||
|
if with.join == line_join::round {
|
||||||
|
var fan := vector::<point>::new();
|
||||||
|
fan.append(here);
|
||||||
|
arc(here, first, second, with, &mut fan);
|
||||||
|
made.polygon(fan.span);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if with.join == line_join::miter && dot > -0.999999 && 1 / math::sqrt((1 + dot) / 2) <= with.miter_limit {
|
||||||
|
val tip := point { x = here.x + (first.x + second.x) / (1 + dot), y = here.y + (first.y + second.y) / (1 + dot) };
|
||||||
|
made.polygon([here, a, tip, b]);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
made.polygon([here, a, b]);
|
||||||
|
}
|
||||||
|
|
||||||
|
# The cap at the end of a polyline, from the point before it.
|
||||||
|
def end_cap(before: point, end: point, with: &pen, made: &mut outline): void {
|
||||||
|
if with.cap == line_cap::round {
|
||||||
|
circle(end, with.half, with, made);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if with.cap == line_cap::square {
|
||||||
|
val across := normal(before, end, with.half);
|
||||||
|
val ahead := point { x = across.y, y = -across.x };
|
||||||
|
made.polygon([offset(end, &across), point { x = end.x + across.x + ahead.x, y = end.y + across.y + ahead.y },
|
||||||
|
point { x = end.x - across.x + ahead.x, y = end.y - across.y + ahead.y },
|
||||||
|
point { x = end.x - across.x, y = end.y - across.y }]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
# The normal of a line, at a length, to its left as it goes.
|
||||||
|
def normal(from: point, to: point, length: f64): point {
|
||||||
|
val size := math::hypot(to.x - from.x, to.y - from.y);
|
||||||
|
return point { x = -(to.y - from.y) / size * length, y = (to.x - from.x) / size * length };
|
||||||
|
}
|
||||||
|
|
||||||
|
def same_point(a: point, b: point): bool {
|
||||||
|
return math::abs(a.x - b.x) < 1e-9 && math::abs(a.y - b.y) < 1e-9;
|
||||||
|
}
|
||||||
|
|
||||||
|
# How many steps a whole circle of a radius takes to stay within the pen's
|
||||||
|
# distance of it.
|
||||||
|
def circle_steps(radius: f64, with: &pen): f64 {
|
||||||
|
if radius <= with.within {
|
||||||
|
return 8;
|
||||||
|
}
|
||||||
|
val steps := math::ceil(math::pi / math::acos(1 - with.within / radius));
|
||||||
|
return steps < 8 ? 8 : (steps > 360 ? 360 : steps);
|
||||||
|
}
|
||||||
|
|
||||||
|
def circle(center: point, radius: f64, with: &pen, made: &mut outline): void {
|
||||||
|
val steps := circle_steps(radius, with);
|
||||||
|
var round := vector::<point>::new();
|
||||||
|
for step in 0..steps as u64 {
|
||||||
|
val angle := 2 * math::pi * step as f64 / steps;
|
||||||
|
round.append(point { x = center.x + radius * math::cos(angle), y = center.y + radius * math::sin(angle) });
|
||||||
|
}
|
||||||
|
made.polygon(round.span);
|
||||||
|
}
|
||||||
|
|
||||||
|
# Appends the points of the shorter arc from one offset of a center to another.
|
||||||
|
def arc(center: point, from: point, to: point, with: &pen, into: &mut vector<point>): void {
|
||||||
|
val radius := math::hypot(from.x, from.y);
|
||||||
|
val begin := math::atan2(from.y, from.x);
|
||||||
|
var turn := math::atan2(to.y, to.x) - begin;
|
||||||
|
if turn > math::pi {
|
||||||
|
turn -= 2 * math::pi;
|
||||||
|
} else if turn < -math::pi {
|
||||||
|
turn += 2 * math::pi;
|
||||||
|
}
|
||||||
|
var steps := math::ceil(math::abs(turn) / (2 * math::pi) * circle_steps(radius, with));
|
||||||
|
steps = steps < 1 ? 1 : steps;
|
||||||
|
for step in 0..=steps as u64 {
|
||||||
|
val angle := begin + turn * step as f64 / steps;
|
||||||
|
into.append(point { x = center.x + radius * math::cos(angle), y = center.y + radius * math::sin(angle) });
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,276 @@
|
|||||||
|
#! Contains SVG's styling: the properties each element has, which its
|
||||||
|
#! presentation attributes, the rules of `<style>` sheets, and its `style`
|
||||||
|
#! attribute set, in that order, over what it inherits.
|
||||||
|
|
||||||
|
import std::math;
|
||||||
|
module malunal::image::svg;
|
||||||
|
|
||||||
|
|
||||||
|
enum line_cap: u8 {
|
||||||
|
butt,
|
||||||
|
round,
|
||||||
|
square,
|
||||||
|
}
|
||||||
|
|
||||||
|
enum line_join: u8 {
|
||||||
|
miter,
|
||||||
|
round,
|
||||||
|
bevel,
|
||||||
|
}
|
||||||
|
|
||||||
|
# The most dashes a stroke's pattern holds.
|
||||||
|
const most_dashes: u64 = 16;
|
||||||
|
|
||||||
|
# The properties of an element, after its own and what it inherits.
|
||||||
|
struct style {
|
||||||
|
# Those inherited.
|
||||||
|
var fill: paint = paint { kind = paint_kind::color };
|
||||||
|
var fill_opacity: f64 = 1;
|
||||||
|
var even_odd: bool;
|
||||||
|
var stroke: paint;
|
||||||
|
var stroke_opacity: f64 = 1;
|
||||||
|
var stroke_width: f64 = 1;
|
||||||
|
var cap: line_cap;
|
||||||
|
var join: line_join;
|
||||||
|
var miter_limit: f64 = 4;
|
||||||
|
var dashes: f64[16];
|
||||||
|
var dash_count: u64;
|
||||||
|
var dash_offset: f64;
|
||||||
|
var color: color;
|
||||||
|
var visible: bool = true;
|
||||||
|
var clip_even_odd: bool;
|
||||||
|
# Those not.
|
||||||
|
var opacity: f64 = 1;
|
||||||
|
var displayed: bool = true;
|
||||||
|
var clip_path: strview;
|
||||||
|
var mask: strview;
|
||||||
|
var stop_color: color;
|
||||||
|
var stop_opacity: f64 = 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
# The properties an element's presentation attributes may set.
|
||||||
|
const presentation: strview[20] = [
|
||||||
|
"fill", "fill-opacity", "fill-rule", "stroke", "stroke-width", "stroke-opacity", "stroke-linecap",
|
||||||
|
"stroke-linejoin", "stroke-miterlimit", "stroke-dasharray", "stroke-dashoffset", "opacity", "color",
|
||||||
|
"display", "visibility", "clip-path", "clip-rule", "mask", "stop-color", "stop-opacity",
|
||||||
|
];
|
||||||
|
|
||||||
|
# The style a child begins with: what its parent's is that's inherited, and the
|
||||||
|
# rest as it begins.
|
||||||
|
def style::inherited(&this): style {
|
||||||
|
var made := copy(this);
|
||||||
|
made.opacity = 1;
|
||||||
|
made.displayed = true;
|
||||||
|
made.clip_path = "";
|
||||||
|
made.mask = "";
|
||||||
|
made.stop_color = color {};
|
||||||
|
made.stop_opacity = 1;
|
||||||
|
return made;
|
||||||
|
}
|
||||||
|
|
||||||
|
# Sets a property of a style by its name and its value as written, leaving it as
|
||||||
|
# it was where either isn't one known, or the value is wrong, as CSS does.
|
||||||
|
def style::set(&mut this, name: strview, given: strview, parent: &style, view: &viewport): void {
|
||||||
|
val value := given.trim();
|
||||||
|
if value == "inherit" {
|
||||||
|
this.inherit(name, parent);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if name == "fill" {
|
||||||
|
this.fill = parse_paint(value) else { return; };
|
||||||
|
} else if name == "stroke" {
|
||||||
|
this.stroke = parse_paint(value) else { return; };
|
||||||
|
} else if name == "fill-opacity" || name == "stroke-opacity" || name == "opacity" || name == "stop-opacity" {
|
||||||
|
val read := parse_fraction(value) else { return; };
|
||||||
|
val clamped := math::clamp(read, 0.0, 1.0);
|
||||||
|
if name == "fill-opacity" {
|
||||||
|
this.fill_opacity = clamped;
|
||||||
|
} else if name == "stroke-opacity" {
|
||||||
|
this.stroke_opacity = clamped;
|
||||||
|
} else if name == "opacity" {
|
||||||
|
this.opacity = clamped;
|
||||||
|
} else {
|
||||||
|
this.stop_opacity = clamped;
|
||||||
|
}
|
||||||
|
} else if name == "fill-rule" {
|
||||||
|
if value == "evenodd" || value == "nonzero" {
|
||||||
|
this.even_odd = value == "evenodd";
|
||||||
|
}
|
||||||
|
} else if name == "clip-rule" {
|
||||||
|
if value == "evenodd" || value == "nonzero" {
|
||||||
|
this.clip_even_odd = value == "evenodd";
|
||||||
|
}
|
||||||
|
} else if name == "stroke-width" {
|
||||||
|
val width := parse_length(value, view, axis::diagonal) else { return; };
|
||||||
|
if width >= 0 {
|
||||||
|
this.stroke_width = width;
|
||||||
|
}
|
||||||
|
} else if name == "stroke-linecap" {
|
||||||
|
if value == "butt" {
|
||||||
|
this.cap = line_cap::butt;
|
||||||
|
} else if value == "round" {
|
||||||
|
this.cap = line_cap::round;
|
||||||
|
} else if value == "square" {
|
||||||
|
this.cap = line_cap::square;
|
||||||
|
}
|
||||||
|
} else if name == "stroke-linejoin" {
|
||||||
|
if value == "miter" || value == "miter-clip" || value == "arcs" {
|
||||||
|
this.join = line_join::miter;
|
||||||
|
} else if value == "round" {
|
||||||
|
this.join = line_join::round;
|
||||||
|
} else if value == "bevel" {
|
||||||
|
this.join = line_join::bevel;
|
||||||
|
}
|
||||||
|
} else if name == "stroke-miterlimit" {
|
||||||
|
val limit := parse_fraction(value) else { return; };
|
||||||
|
if limit >= 1 {
|
||||||
|
this.miter_limit = limit;
|
||||||
|
}
|
||||||
|
} else if name == "stroke-dasharray" {
|
||||||
|
this.set_dashes(value, view);
|
||||||
|
} else if name == "stroke-dashoffset" {
|
||||||
|
this.dash_offset = parse_length(value, view, axis::diagonal) else { return; };
|
||||||
|
} else if name == "color" {
|
||||||
|
this.color = parse_color(value) else { return; };
|
||||||
|
} else if name == "stop-color" {
|
||||||
|
if same_letters(value, "currentColor") {
|
||||||
|
this.stop_color = this.color;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
this.stop_color = parse_color(value) else { return; };
|
||||||
|
} else if name == "display" {
|
||||||
|
this.displayed = value != "none";
|
||||||
|
} else if name == "visibility" {
|
||||||
|
this.visible = value == "visible";
|
||||||
|
} else if name == "clip-path" {
|
||||||
|
this.clip_path = url_of(value);
|
||||||
|
} else if name == "mask" {
|
||||||
|
this.mask = url_of(value);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
# Reads a dash pattern, a list repeated where it's odd, which with any length
|
||||||
|
# below zero, or none above it, dashes nothing.
|
||||||
|
def style::set_dashes(&mut this, value: strview, view: &viewport): void {
|
||||||
|
this.dash_count = 0;
|
||||||
|
if value == "none" {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
var read: f64[16];
|
||||||
|
var count: u64 = 0;
|
||||||
|
var total: f64 = 0;
|
||||||
|
var at: u64 = 0;
|
||||||
|
while at < value.length {
|
||||||
|
while at < value.length && (value[at].is_space || value[at] == ',') {
|
||||||
|
at++;
|
||||||
|
}
|
||||||
|
if at >= value.length {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
var end := at;
|
||||||
|
while end < value.length && !value[end].is_space && value[end] != ',' {
|
||||||
|
end++;
|
||||||
|
}
|
||||||
|
val length := parse_length(value.substr(at, end - at), view, axis::diagonal) else { return; };
|
||||||
|
if length < 0 || count >= most_dashes / 2 {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
read[count] = length;
|
||||||
|
total += length;
|
||||||
|
count++;
|
||||||
|
at = end;
|
||||||
|
}
|
||||||
|
if total <= 0 {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
for index in 0..count {
|
||||||
|
this.dashes[index] = read[index];
|
||||||
|
this.dashes[index + count] = read[index];
|
||||||
|
}
|
||||||
|
this.dash_count = count % 2 == 1 ? count * 2 : count;
|
||||||
|
}
|
||||||
|
|
||||||
|
# Takes a property from the parent's style, as `inherit` says.
|
||||||
|
def style::inherit(&mut this, name: strview, parent: &style): void {
|
||||||
|
if name == "fill" {
|
||||||
|
this.fill = parent.fill;
|
||||||
|
} else if name == "stroke" {
|
||||||
|
this.stroke = parent.stroke;
|
||||||
|
} else if name == "fill-opacity" {
|
||||||
|
this.fill_opacity = parent.fill_opacity;
|
||||||
|
} else if name == "stroke-opacity" {
|
||||||
|
this.stroke_opacity = parent.stroke_opacity;
|
||||||
|
} else if name == "opacity" {
|
||||||
|
this.opacity = parent.opacity;
|
||||||
|
} else if name == "fill-rule" {
|
||||||
|
this.even_odd = parent.even_odd;
|
||||||
|
} else if name == "clip-rule" {
|
||||||
|
this.clip_even_odd = parent.clip_even_odd;
|
||||||
|
} else if name == "stroke-width" {
|
||||||
|
this.stroke_width = parent.stroke_width;
|
||||||
|
} else if name == "stroke-linecap" {
|
||||||
|
this.cap = parent.cap;
|
||||||
|
} else if name == "stroke-linejoin" {
|
||||||
|
this.join = parent.join;
|
||||||
|
} else if name == "stroke-miterlimit" {
|
||||||
|
this.miter_limit = parent.miter_limit;
|
||||||
|
} else if name == "stroke-dasharray" {
|
||||||
|
this.dashes = parent.dashes;
|
||||||
|
this.dash_count = parent.dash_count;
|
||||||
|
} else if name == "stroke-dashoffset" {
|
||||||
|
this.dash_offset = parent.dash_offset;
|
||||||
|
} else if name == "color" {
|
||||||
|
this.color = parent.color;
|
||||||
|
} else if name == "stop-color" {
|
||||||
|
this.stop_color = parent.stop_color;
|
||||||
|
} else if name == "stop-opacity" {
|
||||||
|
this.stop_opacity = parent.stop_opacity;
|
||||||
|
} else if name == "display" {
|
||||||
|
this.displayed = parent.displayed;
|
||||||
|
} else if name == "visibility" {
|
||||||
|
this.visible = parent.visible;
|
||||||
|
} else if name == "clip-path" {
|
||||||
|
this.clip_path = parent.clip_path;
|
||||||
|
} else if name == "mask" {
|
||||||
|
this.mask = parent.mask;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
# Sets each property a list of declarations sets, as `name: value;` writes each.
|
||||||
|
def style::declare(&mut this, declarations: strview, parent: &style, view: &viewport): void {
|
||||||
|
var at: u64 = 0;
|
||||||
|
while at < declarations.length {
|
||||||
|
# A declaration ends at a `;` not within parentheses or quotes.
|
||||||
|
var end := at;
|
||||||
|
var depth := 0;
|
||||||
|
var quote: u8 = 0;
|
||||||
|
while end < declarations.length {
|
||||||
|
val byte := declarations[end];
|
||||||
|
if quote != 0 {
|
||||||
|
if byte == quote {
|
||||||
|
quote = 0;
|
||||||
|
}
|
||||||
|
} else if byte == '"' || byte == '\'' {
|
||||||
|
quote = byte;
|
||||||
|
} else if byte == '(' {
|
||||||
|
depth++;
|
||||||
|
} else if byte == ')' {
|
||||||
|
depth--;
|
||||||
|
} else if byte == ';' && depth <= 0 {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
end++;
|
||||||
|
}
|
||||||
|
val declaration := declarations.substr(at, end - at);
|
||||||
|
at = end + 1;
|
||||||
|
val colon := declaration.find(":") else { continue; };
|
||||||
|
val name := declaration.substr(0, colon).trim();
|
||||||
|
var value := declaration.substr(colon + 1, declaration.length - colon - 1).trim();
|
||||||
|
if value.find("!important") is some(important) {
|
||||||
|
value = value.substr(0, important).trim();
|
||||||
|
}
|
||||||
|
val lowered := name.lower();
|
||||||
|
this.set(lowered.span, value, parent, view);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,132 @@
|
|||||||
|
#! Contains SVG's renderer, which draws the static part of SVG 1.1 that icons and
|
||||||
|
#! illustrations are made of: paths and the basic shapes; groups, `use`, and
|
||||||
|
#! `symbol`; nested `svg` viewports, with `viewBox` and `preserveAspectRatio`;
|
||||||
|
#! fills by either rule and strokes with their caps, joins, miter limits, and
|
||||||
|
#! dashes; colors, linear and radial gradients with every spread, `opacity`,
|
||||||
|
#! `clip-path`, and `mask`. Styles come from presentation attributes, `<style>`
|
||||||
|
#! sheets of type, class, and ID selectors, and `style` attributes.
|
||||||
|
#!
|
||||||
|
#! Left undrawn: text, embedded images, patterns, markers, filters, and nested
|
||||||
|
#! viewports' clipping. Animation and scripts are ignored. SVG is drawn, and not
|
||||||
|
#! written.
|
||||||
|
|
||||||
|
import std::containers;
|
||||||
|
import std::math;
|
||||||
|
import std::xml;
|
||||||
|
module malunal::image::svg;
|
||||||
|
|
||||||
|
|
||||||
|
const svg_namespace: strview = "http://www.w3.org/2000/svg";
|
||||||
|
const xlink_namespace: strview = "http://www.w3.org/1999/xlink";
|
||||||
|
|
||||||
|
# How deep elements, and references from `use`, may nest before what's deeper is
|
||||||
|
# left undrawn, against a `use` within what it refers to.
|
||||||
|
const deepest: u32 = 64;
|
||||||
|
|
||||||
|
# Elements drawn only by reference, or never.
|
||||||
|
const undrawn: strview[17] = [
|
||||||
|
"defs", "symbol", "clipPath", "mask", "linearGradient", "radialGradient", "pattern", "marker", "style",
|
||||||
|
"title", "desc", "metadata", "script", "filter", "text", "image", "foreignObject",
|
||||||
|
];
|
||||||
|
|
||||||
|
# What drawing a document keeps.
|
||||||
|
struct renderer {
|
||||||
|
var ids: dict<strview, xml::element>;
|
||||||
|
var sheet: sheet;
|
||||||
|
var canvas: canvas;
|
||||||
|
var view: viewport; #! The viewport percentages are of, in the current user space.
|
||||||
|
var clipping: bool; #! Whether shapes are drawn as a clip path's, each solid.
|
||||||
|
var depth: u32;
|
||||||
|
}
|
||||||
|
|
||||||
|
#! Draws an SVG.
|
||||||
|
#! @param bytes The SVG's text.
|
||||||
|
#! @param size The size to draw it at.
|
||||||
|
#! @returns The image, or `malformed` where the text isn't XML whose root is an
|
||||||
|
#! SVG element, or whose size is none, and `too_large` where it would
|
||||||
|
#! be drawn with too many pixels.
|
||||||
|
pub def render(bytes: span<u8>, size: svg_size): result<image, image_error> {
|
||||||
|
val doc := xml::parse(bytes) else (_) { return image_error::malformed; };
|
||||||
|
val root := doc.root;
|
||||||
|
if root.local != "svg" || !is_svg(&root) {
|
||||||
|
return image_error::malformed;
|
||||||
|
}
|
||||||
|
|
||||||
|
# The SVG's own size: its width and height, or its view box's, either making
|
||||||
|
# the other keep the view box's shape.
|
||||||
|
val fixed := viewport { width = 100, height = 100 };
|
||||||
|
val box := view_box(&root);
|
||||||
|
var width := absolute_length(&root, "width", &fixed);
|
||||||
|
var height := absolute_length(&root, "height", &fixed);
|
||||||
|
if box is some(seen) {
|
||||||
|
if width is none && height is none {
|
||||||
|
width = seen[2];
|
||||||
|
height = seen[3];
|
||||||
|
} else if width is none {
|
||||||
|
width = height.unwrap() * seen[2] / seen[3];
|
||||||
|
} else if height is none {
|
||||||
|
height = width.unwrap() * seen[3] / seen[2];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
val own_width := width else 100.0;
|
||||||
|
val own_height := height else 100.0;
|
||||||
|
if own_width <= 0 || own_height <= 0 {
|
||||||
|
return image_error::malformed;
|
||||||
|
}
|
||||||
|
|
||||||
|
# The size asked for, which keeps the SVG's shape where only one side is.
|
||||||
|
var out_width := own_width;
|
||||||
|
var out_height := own_height;
|
||||||
|
if size.width != 0 && size.height != 0 {
|
||||||
|
out_width = size.width as f64;
|
||||||
|
out_height = size.height as f64;
|
||||||
|
} else if size.width != 0 {
|
||||||
|
out_width = size.width as f64;
|
||||||
|
out_height = own_height * out_width / own_width;
|
||||||
|
} else if size.height != 0 {
|
||||||
|
out_height = size.height as f64;
|
||||||
|
out_width = own_width * out_height / own_height;
|
||||||
|
}
|
||||||
|
out_width *= size.scale;
|
||||||
|
out_height *= size.scale;
|
||||||
|
val pixels_wide := math::max(1.0, math::round(out_width));
|
||||||
|
val pixels_high := math::max(1.0, math::round(out_height));
|
||||||
|
if !math::is_finite(pixels_wide) || !math::is_finite(pixels_high) || pixels_wide * pixels_high > image::max_pixels as f64 {
|
||||||
|
return image_error::too_large;
|
||||||
|
}
|
||||||
|
val columns := pixels_wide as u64;
|
||||||
|
val rows := pixels_high as u64;
|
||||||
|
|
||||||
|
var drawing := renderer {
|
||||||
|
ids = dict::<strview, xml::element>::new(),
|
||||||
|
sheet = sheet::new(),
|
||||||
|
canvas = canvas::new(columns, rows)
|
||||||
|
};
|
||||||
|
drawing.index(&root);
|
||||||
|
|
||||||
|
# User space: the view box's, fit to the image, or the SVG's own units scaled.
|
||||||
|
var placed := scaling(columns as f64 / own_width, rows as f64 / own_height);
|
||||||
|
drawing.view = viewport { width = own_width, height = own_height };
|
||||||
|
if box is some(seen) {
|
||||||
|
placed = fit_view_box(seen, root.attribute("preserveAspectRatio") else "", 0, 0, columns as f64, rows as f64);
|
||||||
|
drawing.view = viewport { width = seen[2], height = seen[3] };
|
||||||
|
}
|
||||||
|
drawing.draw(&root, &style {}, &placed);
|
||||||
|
|
||||||
|
# The canvas is premultiplied, and the image straight.
|
||||||
|
var made := image::blank(columns as u32, rows as u32) else (e) { return e; };
|
||||||
|
val drawn := drawing.canvas.layers[0].span;
|
||||||
|
var at: u64 = 0;
|
||||||
|
while at < drawn.length {
|
||||||
|
val alpha := drawn[at + 3] as u32;
|
||||||
|
if alpha != 0 {
|
||||||
|
for channel in 0u..3u {
|
||||||
|
val straight := (drawn[at + channel] as u32 * 255 + alpha / 2) / alpha;
|
||||||
|
made.pixels[at + channel] = (straight > 255 ? 255 : straight) as u8;
|
||||||
|
}
|
||||||
|
made.pixels[at + 3] = alpha as u8;
|
||||||
|
}
|
||||||
|
at += 4;
|
||||||
|
}
|
||||||
|
return move(made);
|
||||||
|
}
|
||||||
@@ -0,0 +1,164 @@
|
|||||||
|
#! Contains viewports: nested `svg`s, and the `symbol`s and `svg`s a `use`
|
||||||
|
#! draws, each a place and size its view box is fit within, as
|
||||||
|
#! `preserveAspectRatio` says, and the lengths measured in them.
|
||||||
|
|
||||||
|
import std::math;
|
||||||
|
import std::xml;
|
||||||
|
module malunal::image::svg;
|
||||||
|
|
||||||
|
|
||||||
|
# Draws an `svg` within another, or a `symbol` or `svg` a `use` draws: a viewport
|
||||||
|
# at its place and size, its view box fit within it.
|
||||||
|
def renderer::viewport(&mut this, at: &xml::element, own: &style, placed: &matrix, sized: &xml::element,
|
||||||
|
width_given: maybe<f64>, height_given: maybe<f64>): void {
|
||||||
|
val x := this.length_of(sized, "x", axis::x, 0);
|
||||||
|
val y := this.length_of(sized, "y", axis::y, 0);
|
||||||
|
val width := width_given else this.length_of(sized, "width", axis::x, this.view.width);
|
||||||
|
val height := height_given else this.length_of(sized, "height", axis::y, this.view.height);
|
||||||
|
if width <= 0 || height <= 0 {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
var inner := translation(x, y);
|
||||||
|
var view := viewport { width = width, height = height };
|
||||||
|
if view_box(at) is some(box) {
|
||||||
|
inner = fit_view_box(box, at.attribute("preserveAspectRatio") else "", x, y, width, height);
|
||||||
|
view = viewport { width = box[2], height = box[3] };
|
||||||
|
}
|
||||||
|
val saved := this.view;
|
||||||
|
this.view = view;
|
||||||
|
this.children(at, own, &inner.then(placed));
|
||||||
|
this.view = saved;
|
||||||
|
}
|
||||||
|
|
||||||
|
# Draws what a `use` refers to, moved by its `x` and `y`, inheriting the `use`'s
|
||||||
|
# style.
|
||||||
|
def renderer::use_element(&mut this, at: &xml::element, own: &style, placed: &matrix): void {
|
||||||
|
val href := href_of(at);
|
||||||
|
if !href.starts_with("#") {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
val id := href.substr(1, href.length - 1);
|
||||||
|
val target := this.ids.get(&id) else { return; };
|
||||||
|
val x := this.length_of(at, "x", axis::x, 0);
|
||||||
|
val y := this.length_of(at, "y", axis::y, 0);
|
||||||
|
val moved := translation(x, y).then(placed);
|
||||||
|
|
||||||
|
if target.local == "symbol" || target.local == "svg" {
|
||||||
|
# Its viewport takes the `use`'s width and height, where it gives them.
|
||||||
|
val symbol_style := this.style_of(&target, own);
|
||||||
|
if !symbol_style.displayed {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
var width: maybe<f64> = nothing {};
|
||||||
|
var height: maybe<f64> = nothing {};
|
||||||
|
if at.attribute("width") is some(_) {
|
||||||
|
width = this.length_of(at, "width", axis::x, 0);
|
||||||
|
}
|
||||||
|
if at.attribute("height") is some(_) {
|
||||||
|
height = this.length_of(at, "height", axis::y, 0);
|
||||||
|
}
|
||||||
|
if target.local == "symbol" {
|
||||||
|
this.symbol(&target, &symbol_style, &moved, width, height);
|
||||||
|
} else {
|
||||||
|
this.depth++;
|
||||||
|
this.viewport(&target, &symbol_style, &moved, &target, width, height);
|
||||||
|
this.depth--;
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
this.draw(&target, own, &moved);
|
||||||
|
}
|
||||||
|
|
||||||
|
# Draws a symbol's children in the viewport a `use` gives it, of 100% each way
|
||||||
|
# where it gives none.
|
||||||
|
def renderer::symbol(&mut this, at: &xml::element, own: &style, placed: &matrix, width_given: maybe<f64>, height_given: maybe<f64>): void {
|
||||||
|
val width := width_given else this.view.width;
|
||||||
|
val height := height_given else this.view.height;
|
||||||
|
if width <= 0 || height <= 0 {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
var inner := matrix {};
|
||||||
|
var view := viewport { width = width, height = height };
|
||||||
|
if view_box(at) is some(box) {
|
||||||
|
inner = fit_view_box(box, at.attribute("preserveAspectRatio") else "", 0, 0, width, height);
|
||||||
|
view = viewport { width = box[2], height = box[3] };
|
||||||
|
}
|
||||||
|
val saved := this.view;
|
||||||
|
this.view = view;
|
||||||
|
this.depth++;
|
||||||
|
this.children(at, own, &inner.then(placed));
|
||||||
|
this.depth--;
|
||||||
|
this.view = saved;
|
||||||
|
}
|
||||||
|
|
||||||
|
# A length attribute, in user units, or what it is where it's left out or wrong.
|
||||||
|
def renderer::length_of(&this, at: &xml::element, name: strview, along: axis, fallback: f64): f64 {
|
||||||
|
val written := at.attribute(name) else { return fallback; };
|
||||||
|
return parse_length(written, &this.view, along) else fallback;
|
||||||
|
}
|
||||||
|
|
||||||
|
# A length of the root, where it's given in absolute units rather than a
|
||||||
|
# percentage, which has nothing to be of.
|
||||||
|
def absolute_length(at: &xml::element, name: strview, view: &viewport): maybe<f64> {
|
||||||
|
val written := at.attribute(name) else { return nothing {}; };
|
||||||
|
if written.find("%") is some(_) {
|
||||||
|
return nothing {};
|
||||||
|
}
|
||||||
|
return parse_length(written, view, axis::x);
|
||||||
|
}
|
||||||
|
|
||||||
|
# An element's `viewBox`: its least x and y, and its width and height, which
|
||||||
|
# must be more than none.
|
||||||
|
def view_box(at: &xml::element): maybe<f64[4]> {
|
||||||
|
val written := at.attribute("viewBox") else { return nothing {}; };
|
||||||
|
var read := numbers::of(written);
|
||||||
|
var box: f64[4];
|
||||||
|
for index in 0u..4u {
|
||||||
|
box[index] = read.next() else { return nothing {}; };
|
||||||
|
}
|
||||||
|
if box[2] <= 0 || box[3] <= 0 {
|
||||||
|
return nothing {};
|
||||||
|
}
|
||||||
|
return box;
|
||||||
|
}
|
||||||
|
|
||||||
|
# The transform fitting a view box within a viewport, as `preserveAspectRatio`
|
||||||
|
# says: stretched, or scaled the same each way to meet or slice it, and aligned.
|
||||||
|
def fit_view_box(box: f64[4], aspect: strview, x: f64, y: f64, width: f64, height: f64): matrix {
|
||||||
|
var words := aspect.trim();
|
||||||
|
if words.starts_with("defer") {
|
||||||
|
words = words.substr(5, words.length - 5).trim();
|
||||||
|
}
|
||||||
|
var align := words;
|
||||||
|
var slice := false;
|
||||||
|
if words.find(" ") is some(space) {
|
||||||
|
align = words.substr(0, space);
|
||||||
|
slice = words.substr(space, words.length - space).trim() == "slice";
|
||||||
|
}
|
||||||
|
if align.length == 0 {
|
||||||
|
align = "xMidYMid";
|
||||||
|
}
|
||||||
|
|
||||||
|
var sx := width / box[2];
|
||||||
|
var sy := height / box[3];
|
||||||
|
if align != "none" {
|
||||||
|
val scale := slice ? math::max(sx, sy) : math::min(sx, sy);
|
||||||
|
sx = scale;
|
||||||
|
sy = scale;
|
||||||
|
}
|
||||||
|
var tx := x - box[0] * sx;
|
||||||
|
var ty := y - box[1] * sy;
|
||||||
|
val spare_x := width - box[2] * sx;
|
||||||
|
val spare_y := height - box[3] * sy;
|
||||||
|
if align.find("xMid") is some(_) {
|
||||||
|
tx += spare_x / 2;
|
||||||
|
} else if align.find("xMax") is some(_) {
|
||||||
|
tx += spare_x;
|
||||||
|
}
|
||||||
|
if align.find("YMid") is some(_) {
|
||||||
|
ty += spare_y / 2;
|
||||||
|
} else if align.find("YMax") is some(_) {
|
||||||
|
ty += spare_y;
|
||||||
|
}
|
||||||
|
return matrix { a = sx, d = sy, e = tx, f = ty };
|
||||||
|
}
|
||||||
@@ -0,0 +1,59 @@
|
|||||||
|
#! Contains writing an image, as bytes, into a stream, or to a file, in the
|
||||||
|
#! format asked for, or that a file's extension names, as each format's own
|
||||||
|
#! `encode` writes it by default.
|
||||||
|
|
||||||
|
import std::io;
|
||||||
|
module malunal::image;
|
||||||
|
|
||||||
|
|
||||||
|
#! Writes an image in a format, as that format's `encode` does by default:
|
||||||
|
#! `image::png::encode`, or `image::jpeg::encode`.
|
||||||
|
#! @param picture The image.
|
||||||
|
#! @param kind The format to write it in.
|
||||||
|
#! @returns The bytes, or why the image couldn't be written: `unsupported` for
|
||||||
|
#! SVG, which isn't written.
|
||||||
|
pub def encode(picture: &image, kind: format): result<vector<u8>, image_error> {
|
||||||
|
if kind == format::png {
|
||||||
|
return image::png::encode(picture);
|
||||||
|
}
|
||||||
|
if kind == format::jpeg {
|
||||||
|
return image::jpeg::encode(picture);
|
||||||
|
}
|
||||||
|
return image_error::unsupported;
|
||||||
|
}
|
||||||
|
|
||||||
|
#! Writes an image in a format into a stream, as `encode` does.
|
||||||
|
#! @param picture The image.
|
||||||
|
#! @param kind The format to write it in.
|
||||||
|
#! @param out The stream to write to, which is not flushed: whoever made it
|
||||||
|
#! does that.
|
||||||
|
#! @returns Nothing, or why the image couldn't be written: `unwritable` where the
|
||||||
|
#! stream failed.
|
||||||
|
pub def write_to(picture: &image, kind: format, out: &mut writable): result<void, image_error> {
|
||||||
|
val bytes := encode(picture, kind) else (e) { return e; };
|
||||||
|
out.write(bytes.span) else (_) { return image_error::unwritable; };
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
#! Writes an image to a file, in the format its extension names, as `encode`
|
||||||
|
#! does, replacing what the file held.
|
||||||
|
#! @param picture The image.
|
||||||
|
#! @param at The file's path, as `.png`, `.jpg`, or `.jpeg` ends one.
|
||||||
|
#! @returns Nothing, or why the image couldn't be written: `unrecognized` where
|
||||||
|
#! the extension names no format, and `unwritable` where the file
|
||||||
|
#! couldn't be written.
|
||||||
|
pub def save(picture: &image, at: &path): result<void, image_error> {
|
||||||
|
val kind := format_named(at.extension) else { return image_error::unrecognized; };
|
||||||
|
val bytes := encode(picture, kind) else (e) { return e; };
|
||||||
|
io::write_file(at, bytes.span) else (_) { return image_error::unwritable; };
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
#! Writes an image to a file named by text, as `save` does.
|
||||||
|
#! @param picture The image.
|
||||||
|
#! @param at The file's path, as text.
|
||||||
|
#! @returns Nothing, or why the image couldn't be written.
|
||||||
|
pub def save(picture: &image, at: strview): result<void, image_error> {
|
||||||
|
val named := path::parse(at) else (_) { return image_error::unwritable; };
|
||||||
|
return save(picture, &named);
|
||||||
|
}
|
||||||
@@ -0,0 +1,82 @@
|
|||||||
|
#! Contains the tests of `image`'s own functions: which format bytes, or a
|
||||||
|
#! file's extension, say they're in, and an image read and written by them.
|
||||||
|
|
||||||
|
import std::io;
|
||||||
|
import std::testing;
|
||||||
|
import malunal::image;
|
||||||
|
|
||||||
|
@test def finds_each_format_by_its_first_bytes(t: &mut tester): void {
|
||||||
|
val png := bytes_of("tests/images/rgb8.png");
|
||||||
|
val jpeg := bytes_of("tests/images/rgb.jpg");
|
||||||
|
t.expects(format_is(png.span, image::format::png));
|
||||||
|
t.expects(format_is(jpeg.span, image::format::jpeg));
|
||||||
|
t.expects(format_is("<?xml version='1.0'?>\n<!-- drawn -->\n<!DOCTYPE svg [<!ENTITY a 'b'>]><svg/>", image::format::svg));
|
||||||
|
t.expects(format_is("<svg:svg xmlns:svg='http://www.w3.org/2000/svg'/>", image::format::svg));
|
||||||
|
t.expects(image::format_of("<html><svg/></html>") is none);
|
||||||
|
t.expects(image::format_of("GIF89a") is none);
|
||||||
|
t.expects(fails(image::decode("plain text"), image::image_error::unrecognized));
|
||||||
|
t.expects(fails(image::load("tests/images/missing.png"), image::image_error::unreadable));
|
||||||
|
}
|
||||||
|
|
||||||
|
@test def names_formats_by_their_extensions(t: &mut tester): void {
|
||||||
|
t.expects(image::format_named("png") is some(_) && image::format_named("PNG").unwrap() == image::format::png);
|
||||||
|
t.expects(image::format_named("jpg").unwrap() == image::format::jpeg);
|
||||||
|
t.expects(image::format_named("JPEG").unwrap() == image::format::jpeg);
|
||||||
|
t.expects(image::format_named("jfif").unwrap() == image::format::jpeg);
|
||||||
|
t.expects(image::format_named("svg").unwrap() == image::format::svg);
|
||||||
|
t.expects(image::format_named("gif") is none);
|
||||||
|
t.expects(image::format_named("") is none);
|
||||||
|
}
|
||||||
|
|
||||||
|
@test def writes_in_the_format_asked(t: &mut tester): void {
|
||||||
|
val picture := made_of("rgba", 24, 20);
|
||||||
|
val png := image::encode(&picture, image::format::png) else (_) { t.expects(false); return; };
|
||||||
|
val jpeg := image::encode(&picture, image::format::jpeg) else (_) { t.expects(false); return; };
|
||||||
|
t.expects(format_is(png.span, image::format::png) && format_is(jpeg.span, image::format::jpeg));
|
||||||
|
val again := read_back(png.span);
|
||||||
|
t.expects(apart(&again, &picture) == 0);
|
||||||
|
t.expects(fails_writing(image::encode(&picture, image::format::svg), image::image_error::unsupported));
|
||||||
|
|
||||||
|
# An image whose pixels aren't as many as its size says isn't written.
|
||||||
|
var short := made_of("rgb", 4, 4);
|
||||||
|
short.height = 5;
|
||||||
|
t.expects(fails_writing(image::encode(&short, image::format::png), image::image_error::malformed));
|
||||||
|
t.expects(fails_writing(image::encode(&short, image::format::jpeg), image::image_error::malformed));
|
||||||
|
val empty := image::image { pixels = vector::<u8>::new() };
|
||||||
|
t.expects(fails_writing(image::encode(&empty, image::format::png), image::image_error::malformed));
|
||||||
|
}
|
||||||
|
|
||||||
|
@test def writes_into_a_stream(t: &mut tester): void {
|
||||||
|
val picture := made_of("palette", 24, 20);
|
||||||
|
var out := string::new(nothing {});
|
||||||
|
t.expects(image::write_to(&picture, image::format::png, &mut out) is value);
|
||||||
|
val again := read_back(out.span);
|
||||||
|
t.expects(apart(&again, &picture) == 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
@test def saves_by_the_extension_and_loads_again(t: &mut tester): void {
|
||||||
|
val picture := made_of("gray_alpha", 24, 20);
|
||||||
|
t.expects(image::save(&picture, "tests/written.png") is value);
|
||||||
|
val loaded := image::load("tests/written.png") else (_) { t.expects(false); return; };
|
||||||
|
t.expects(apart(&loaded, &picture) == 0);
|
||||||
|
t.expects(image::save(&picture, "tests/written.jpg") is value);
|
||||||
|
val lossy := image::load("tests/written.jpg") else (_) { t.expects(false); return; };
|
||||||
|
t.expects(lossy.width == 24 && lossy.height == 20);
|
||||||
|
|
||||||
|
match image::save(&picture, "tests/written.gif") {
|
||||||
|
value(_) => t.expects(false);
|
||||||
|
error(e) => t.expects(e == image::image_error::unrecognized);
|
||||||
|
}
|
||||||
|
match image::save(&picture, "tests/written.svg") {
|
||||||
|
value(_) => t.expects(false);
|
||||||
|
error(e) => t.expects(e == image::image_error::unsupported);
|
||||||
|
}
|
||||||
|
match image::save(&picture, "tests/no/such/folder/written.png") {
|
||||||
|
value(_) => t.expects(false);
|
||||||
|
error(e) => t.expects(e == image::image_error::unwritable);
|
||||||
|
}
|
||||||
|
for written in ["tests/written.png", "tests/written.jpg"] {
|
||||||
|
val at := path::parse(written) else (_) { continue; };
|
||||||
|
_ = io::remove(&at);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
After Width: | Height: | Size: 429 B |
|
After Width: | Height: | Size: 222 B |
|
After Width: | Height: | Size: 204 B |
|
After Width: | Height: | Size: 285 B |
|
After Width: | Height: | Size: 260 B |
|
After Width: | Height: | Size: 811 B |
|
After Width: | Height: | Size: 167 B |
|
After Width: | Height: | Size: 171 B |
|
After Width: | Height: | Size: 157 B |
@@ -0,0 +1,94 @@
|
|||||||
|
#! Contains the tests of `image::jpeg`: the test images read, what isn't read
|
||||||
|
#! refused, and images written and read back near the colors they were, as
|
||||||
|
#! JPEG keeps them.
|
||||||
|
|
||||||
|
import std::testing;
|
||||||
|
import malunal::image;
|
||||||
|
|
||||||
|
# The byte of a JPEG this encoder writes whose frame says how many components
|
||||||
|
# it has: past the start of image, JFIF's 18, the quantization tables' 4, each
|
||||||
|
# table's 65, and the frame's marker, length, precision, height, and width.
|
||||||
|
def components_of(written: &vector<u8>, tables: u64): u8 {
|
||||||
|
return written[2 + 18 + 4 + 65 * tables + 9];
|
||||||
|
}
|
||||||
|
|
||||||
|
# Writes an image as JPEG, and how far what's read back strays in color.
|
||||||
|
def written_apart(picture: &image::image, given: image::jpeg::options): u32 {
|
||||||
|
val written := image::jpeg::encode(picture, given) else (_) { return 256; };
|
||||||
|
val again := read_back(written.span);
|
||||||
|
return colors_apart(&again, picture);
|
||||||
|
}
|
||||||
|
|
||||||
|
@test def reads_baseline_jpeg(t: &mut tester): void {
|
||||||
|
# Quality 95 strays a little from the pattern, as JPEG does.
|
||||||
|
val color := stray("tests/images/rgb.jpg", "rgb");
|
||||||
|
val gray := stray("tests/images/gray.jpg", "gray");
|
||||||
|
t.expects(color <= 12);
|
||||||
|
t.expects(gray <= 4);
|
||||||
|
}
|
||||||
|
|
||||||
|
@test def refuses_jpeg_it_does_not_read(t: &mut tester): void {
|
||||||
|
# Arithmetic coding, and samples of 12 bits.
|
||||||
|
t.expects(fails(image::decode("\xFF\xD8\xFF\xC9\x00\x0B\x08\x00\x10\x00\x10\x01\x01\x11\x00\xFF\xD9"), image::image_error::unsupported));
|
||||||
|
t.expects(fails(image::decode("\xFF\xD8\xFF\xC0\x00\x0B\x0C\x00\x10\x00\x10\x01\x01\x11\x00\xFF\xD9"), image::image_error::unsupported));
|
||||||
|
# No frame at all.
|
||||||
|
t.expects(fails(image::decode("\xFF\xD8\xFF\xD9"), image::image_error::malformed));
|
||||||
|
t.expects(fails(image::decode("\xFF\xD8\xFF\xC0\x00\x0B\x08\x80\x00\x80\x00\x01\x01\x11\x00\xFF\xD9"), image::image_error::too_large));
|
||||||
|
|
||||||
|
# Cut short, it gives what it has.
|
||||||
|
val whole := bytes_of("tests/images/rgb.jpg");
|
||||||
|
val cut := image::decode(whole.span[0:whole.length - 100]) else (_) { t.expects(false); return; };
|
||||||
|
t.expects(cut.width == 24 && cut.height == 20);
|
||||||
|
}
|
||||||
|
|
||||||
|
@test def writes_jpeg_near_its_colors(t: &mut tester): void {
|
||||||
|
val picture := made_of("rgb", 24, 20);
|
||||||
|
# Every chroma sample kept, at quality 100, strays only as rounding does.
|
||||||
|
t.expects(written_apart(&picture, image::jpeg::options { quality = 100, chroma = image::jpeg::subsampling::none }) <= 3);
|
||||||
|
t.expects(written_apart(&picture, image::jpeg::options { quality = 95, chroma = image::jpeg::subsampling::none }) <= 8);
|
||||||
|
t.expects(written_apart(&picture, image::jpeg::options { quality = 95, chroma = image::jpeg::subsampling::across }) <= 10);
|
||||||
|
t.expects(written_apart(&picture, image::jpeg::options { quality = 95 }) <= 12);
|
||||||
|
t.expects(written_apart(&picture, image::jpeg::options { quality = 50 }) <= 24);
|
||||||
|
}
|
||||||
|
|
||||||
|
@test def writes_gray_jpeg_as_gray(t: &mut tester): void {
|
||||||
|
val gray := made_of("gray", 24, 20);
|
||||||
|
val written := image::jpeg::encode(&gray, image::jpeg::options { quality = 100 }) else (_) { t.expects(false); return; };
|
||||||
|
t.expects(components_of(&written, 1) == 1);
|
||||||
|
val again := read_back(written.span);
|
||||||
|
t.expects(apart(&again, &gray) <= 2);
|
||||||
|
|
||||||
|
val color := image::jpeg::encode(&made_of("rgb", 24, 20)) else (_) { t.expects(false); return; };
|
||||||
|
t.expects(components_of(&color, 2) == 3);
|
||||||
|
}
|
||||||
|
|
||||||
|
@test def writes_jpeg_smaller_at_lower_quality(t: &mut tester): void {
|
||||||
|
val noise := made_of("noise", 64, 64);
|
||||||
|
val high := image::jpeg::encode(&noise, image::jpeg::options { quality = 95 }) else (_) { t.expects(false); return; };
|
||||||
|
val low := image::jpeg::encode(&noise, image::jpeg::options { quality = 30 }) else (_) { t.expects(false); return; };
|
||||||
|
t.expects(low.length < high.length);
|
||||||
|
t.expects(read_back(low.span).width == 64);
|
||||||
|
}
|
||||||
|
|
||||||
|
@test def writes_jpeg_of_any_size(t: &mut tester): void {
|
||||||
|
# Sizes of part of an MCU, of every subsampling.
|
||||||
|
for chroma in subsamplings {
|
||||||
|
for index in 0u..5u {
|
||||||
|
val picture := made_of("rgb", widths[index], heights[index]);
|
||||||
|
t.expects(written_apart(&picture, image::jpeg::options { quality = 100, chroma = chroma }) <= 16);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
var wide := image::image { width = 70000, height = 1, pixels = vector::<u8>::new() };
|
||||||
|
wide.pixels.resize(70000 * 4);
|
||||||
|
t.expects(fails_writing(image::jpeg::encode(&wide), image::image_error::too_large));
|
||||||
|
}
|
||||||
|
|
||||||
|
# Sizes of images, across and down, of part of an MCU, no wider than the
|
||||||
|
# pattern's red stays below 256, past which a sharp edge of red is, which
|
||||||
|
# halved chroma blurs.
|
||||||
|
const widths: u32[5] = [1, 17, 8, 25, 3];
|
||||||
|
const heights: u32[5] = [1, 9, 16, 2, 31];
|
||||||
|
|
||||||
|
const subsamplings: image::jpeg::subsampling[3] = [
|
||||||
|
image::jpeg::subsampling::none, image::jpeg::subsampling::across, image::jpeg::subsampling::both,
|
||||||
|
];
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
#! Contains the `main` that runs image's tests, each in a copy of the program of
|
||||||
|
#! its own. `blossom test` runs them, and `--test TEXT` those whose name
|
||||||
|
#! holds the text.
|
||||||
|
|
||||||
|
import system;
|
||||||
|
import std::testing;
|
||||||
|
|
||||||
|
def main(args: span<strview>): void {
|
||||||
|
exit(tester::run(args));
|
||||||
|
}
|
||||||
@@ -0,0 +1,140 @@
|
|||||||
|
#! Contains the tests of `image::png`: the test images read, broken ones
|
||||||
|
#! refused, and images written and read back exactly, in the color type and
|
||||||
|
#! depth that hold them.
|
||||||
|
|
||||||
|
import std::testing;
|
||||||
|
import malunal::image;
|
||||||
|
|
||||||
|
# The bytes of a PNG that `IHDR` gives its depth and color type at.
|
||||||
|
const depth_at: u64 = 24;
|
||||||
|
const color_at: u64 = 25;
|
||||||
|
|
||||||
|
# The shifts of a big-endian word's bytes, the most significant first.
|
||||||
|
const byte_shifts: u32[4] = [24, 16, 8, 0];
|
||||||
|
|
||||||
|
# The CRC-32 of bytes, as PNG's chunks end with.
|
||||||
|
def crc32(data: strview): u32 {
|
||||||
|
var crc: u32 = 0xFFFFFFFF;
|
||||||
|
for byte in data {
|
||||||
|
crc ^= byte as u32;
|
||||||
|
for _ in 0..8 {
|
||||||
|
crc = (crc & 1) != 0 ? 0xEDB88320 ^ (crc >> 1) : crc >> 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return crc ^ 0xFFFFFFFF;
|
||||||
|
}
|
||||||
|
|
||||||
|
# Appends a PNG chunk, its length, type, data, and CRC.
|
||||||
|
def chunk(into: &mut string, kind: strview, data: strview): void {
|
||||||
|
val start := into.length;
|
||||||
|
for shift in byte_shifts {
|
||||||
|
into.push(((data.length as u32) >> shift) as u8);
|
||||||
|
}
|
||||||
|
into.append(kind);
|
||||||
|
into.append(data);
|
||||||
|
val crc := crc32(into.span[start + 4:kind.length + data.length]);
|
||||||
|
for shift in byte_shifts {
|
||||||
|
into.push((crc >> shift) as u8);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
# Writes an image as PNG, and whether it reads back exactly, in a color type
|
||||||
|
# and depth.
|
||||||
|
def round_trips(picture: &image::image, given: image::png::options, color: u8, depth: u8): bool {
|
||||||
|
val written := image::png::encode(picture, given) else (_) { return false; };
|
||||||
|
val again := read_back(written.span);
|
||||||
|
return apart(&again, picture) == 0 && written[color_at] == color && written[depth_at] == depth;
|
||||||
|
}
|
||||||
|
|
||||||
|
@test def reads_png_of_every_color_type(t: &mut tester): void {
|
||||||
|
t.expects(stray("tests/images/rgba8.png", "rgba") == 0);
|
||||||
|
t.expects(stray("tests/images/rgb8.png", "rgb") == 0);
|
||||||
|
t.expects(stray("tests/images/gray8.png", "gray") == 0);
|
||||||
|
t.expects(stray("tests/images/gray16.png", "gray") == 0);
|
||||||
|
t.expects(stray("tests/images/rgba16.png", "rgba") == 0);
|
||||||
|
t.expects(stray("tests/images/palette4.png", "palette") == 0);
|
||||||
|
t.expects(stray("tests/images/interlaced.png", "rgba") == 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
@test def refuses_broken_png(t: &mut tester): void {
|
||||||
|
val whole := bytes_of("tests/images/rgb8.png");
|
||||||
|
t.expects(fails(image::decode(whole.span[0:whole.length - 20]), image::image_error::malformed));
|
||||||
|
|
||||||
|
# A changed byte breaks its chunk's CRC.
|
||||||
|
var changed := string::copy_of(&whole);
|
||||||
|
changed[40] = changed[40] ^ 0x10;
|
||||||
|
t.expects(fails(image::decode(changed.span), image::image_error::malformed));
|
||||||
|
|
||||||
|
# A header too large is refused before anything is inflated.
|
||||||
|
var huge := string::from("\x89PNG\r\n\x1A\n", nothing {});
|
||||||
|
chunk(&mut huge, "IHDR", "\x00\x01\x00\x00\x00\x01\x00\x00\x08\x06\x00\x00\x00");
|
||||||
|
t.expects(fails(image::decode(huge.span), image::image_error::too_large));
|
||||||
|
|
||||||
|
# A critical chunk PNG doesn't define can't be read past; an ancillary one can.
|
||||||
|
var critical := string::from(whole.span[0:33], nothing {});
|
||||||
|
chunk(&mut critical, "ABCD", "data");
|
||||||
|
critical.append(whole.span[33:whole.length - 33]);
|
||||||
|
t.expects(fails(image::decode(critical.span), image::image_error::unsupported));
|
||||||
|
var ancillary := string::from(whole.span[0:33], nothing {});
|
||||||
|
chunk(&mut ancillary, "abCD", "data");
|
||||||
|
ancillary.append(whole.span[33:whole.length - 33]);
|
||||||
|
t.expects(image::decode(ancillary.span) is value);
|
||||||
|
}
|
||||||
|
|
||||||
|
@test def writes_png_in_the_least_color_type(t: &mut tester): void {
|
||||||
|
val given := image::png::options {};
|
||||||
|
# Gray of 1, 4, and 8 bits, gray with alpha, RGB, and RGBA.
|
||||||
|
t.expects(round_trips(&made_of("bw", 24, 20), given, 0, 1));
|
||||||
|
t.expects(round_trips(&made_of("gray4", 24, 20), given, 0, 4));
|
||||||
|
t.expects(round_trips(&made_of("gray", 24, 20), given, 0, 8));
|
||||||
|
t.expects(round_trips(&made_of("gray_alpha", 24, 20), given, 4, 8));
|
||||||
|
t.expects(round_trips(&made_of("rgb", 24, 20), given, 2, 8));
|
||||||
|
t.expects(round_trips(&made_of("noise", 24, 20), given, 6, 8));
|
||||||
|
# A palette, of as few bits as its colors need, its alpha in `tRNS`.
|
||||||
|
t.expects(round_trips(&made_of("palette", 24, 20), given, 3, 4));
|
||||||
|
t.expects(round_trips(&made_of("rgba", 12, 10), given, 3, 8));
|
||||||
|
t.expects(round_trips(&made_of("rgba", 24, 20), given, 6, 8));
|
||||||
|
# RGBA of 8 bits, where it's asked for whatever the pixels are.
|
||||||
|
t.expects(round_trips(&made_of("bw", 24, 20), image::png::options { reduced = false }, 6, 8));
|
||||||
|
}
|
||||||
|
|
||||||
|
@test def writes_png_at_every_level_and_interlaced(t: &mut tester): void {
|
||||||
|
for level in 0u..10u {
|
||||||
|
t.expects(round_trips(&made_of("rgb", 24, 20), image::png::options { level = level as u32 }, 2, 8));
|
||||||
|
}
|
||||||
|
# Each pass of Adam7, even those an image too small has none of.
|
||||||
|
t.expects(round_trips(&made_of("rgba", 24, 20), image::png::options { interlaced = true }, 6, 8));
|
||||||
|
t.expects(round_trips(&made_of("noise", 13, 11), image::png::options { interlaced = true }, 3, 8));
|
||||||
|
t.expects(round_trips(&made_of("noise", 19, 17), image::png::options { interlaced = true }, 6, 8));
|
||||||
|
t.expects(round_trips(&made_of("bw", 3, 2), image::png::options { interlaced = true }, 0, 1));
|
||||||
|
t.expects(round_trips(&made_of("noise", 1, 1), image::png::options { interlaced = true }, 3, 1));
|
||||||
|
}
|
||||||
|
|
||||||
|
@test def compresses_what_repeats(t: &mut tester): void {
|
||||||
|
# A ramp repeated down: each row the same, which the filters make zeros.
|
||||||
|
val flat := made_of("rgb", 64, 256);
|
||||||
|
val stored := image::png::encode(&flat, image::png::options { level = 0 }) else (_) { t.expects(false); return; };
|
||||||
|
val compressed := image::png::encode(&flat, image::png::options { level = 9 }) else (_) { t.expects(false); return; };
|
||||||
|
t.expects(stored.length > 64 * 256 * 3);
|
||||||
|
t.expects(compressed.length < 1000);
|
||||||
|
# Noise, too many colors for a palette, across blocks of several kinds.
|
||||||
|
val noise := made_of("noise", 96, 96);
|
||||||
|
t.expects(round_trips(&noise, image::png::options {}, 6, 8));
|
||||||
|
t.expects(round_trips(&noise, image::png::options { level = 1 }, 6, 8));
|
||||||
|
}
|
||||||
|
|
||||||
|
@test def writes_again_what_it_reads(t: &mut tester): void {
|
||||||
|
for file in test_files {
|
||||||
|
val read := image::load(file) else (_) { t.expects(false); continue; };
|
||||||
|
val written := image::png::encode(&read) else (_) { t.expects(false); continue; };
|
||||||
|
val again := read_back(written.span);
|
||||||
|
t.expects(apart(&again, &read) == 0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
# The test images, PNG and JPEG.
|
||||||
|
const test_files: strview[9] = [
|
||||||
|
"tests/images/rgba8.png", "tests/images/rgb8.png", "tests/images/gray8.png", "tests/images/gray16.png",
|
||||||
|
"tests/images/rgba16.png", "tests/images/palette4.png", "tests/images/interlaced.png",
|
||||||
|
"tests/images/rgb.jpg", "tests/images/gray.jpg",
|
||||||
|
];
|
||||||
@@ -0,0 +1,146 @@
|
|||||||
|
#! Contains what the tests of `image` share: the pattern the test images were
|
||||||
|
#! made of, images made of it and of others in memory, and how far one image
|
||||||
|
#! strays from another.
|
||||||
|
|
||||||
|
import std::io;
|
||||||
|
import malunal::image;
|
||||||
|
|
||||||
|
# The pattern the test images were made of, at a pixel, for a kind of image,
|
||||||
|
# and others images are made of to be written: gray exact at 4 bits, black and
|
||||||
|
# white, gray with alpha, and noise.
|
||||||
|
def expected(kind: strview, x: u32, y: u32): u8[4] {
|
||||||
|
if kind == "palette" {
|
||||||
|
val entry := ((x >> 2) + (y >> 2) * 6) % 16;
|
||||||
|
return [(16 * entry) as u8, (255 - 16 * entry) as u8, (8 * entry) as u8, (255 - 8 * entry) as u8];
|
||||||
|
}
|
||||||
|
if kind == "gray" {
|
||||||
|
val g := (12 * y) as u8;
|
||||||
|
return [g, g, g, 255];
|
||||||
|
}
|
||||||
|
if kind == "gray4" {
|
||||||
|
val g := (17 * ((x + y) % 16)) as u8;
|
||||||
|
return [g, g, g, 255];
|
||||||
|
}
|
||||||
|
if kind == "bw" {
|
||||||
|
val g: u8 = ((x / 3 + y / 2) % 2 == 0) ? 0 : 255;
|
||||||
|
return [g, g, g, 255];
|
||||||
|
}
|
||||||
|
if kind == "gray_alpha" {
|
||||||
|
val g := (12 * y) as u8;
|
||||||
|
return [g, g, g, (55 + 8 * x) as u8];
|
||||||
|
}
|
||||||
|
if kind == "noise" {
|
||||||
|
var seed := (x * 7919 + y * 104729 + 12345) as u32;
|
||||||
|
seed = seed ^ (seed << 13);
|
||||||
|
seed = seed ^ (seed >> 17);
|
||||||
|
seed = seed ^ (seed << 5);
|
||||||
|
return [seed as u8, (seed >> 8) as u8, (seed >> 16) as u8, (seed >> 24) as u8];
|
||||||
|
}
|
||||||
|
val alpha: u8 = kind == "rgba" ? (55 + 8 * x) as u8 : 255;
|
||||||
|
return [(10 * x) as u8, (12 * y) as u8, (5 * (x + y)) as u8, alpha];
|
||||||
|
}
|
||||||
|
|
||||||
|
# An image of a size, of a kind's pattern.
|
||||||
|
def made_of(kind: strview, width: u32, height: u32): image::image {
|
||||||
|
var pixels := vector::<u8>::new();
|
||||||
|
for y in 0..height {
|
||||||
|
for x in 0..width {
|
||||||
|
val color := expected(kind, x, y);
|
||||||
|
for channel in 0u..4u {
|
||||||
|
pixels.append(color[channel]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return image::image { width = width, height = height, pixels = move(pixels) };
|
||||||
|
}
|
||||||
|
|
||||||
|
# How far an image strays from another at most, in any channel, or 256 where
|
||||||
|
# they're of other sizes.
|
||||||
|
def apart(a: &image::image, b: &image::image): u32 {
|
||||||
|
if a.width != b.width || a.height != b.height || a.pixels.length != b.pixels.length {
|
||||||
|
return 256;
|
||||||
|
}
|
||||||
|
var most: u32 = 0;
|
||||||
|
for index in 0..a.pixels.length {
|
||||||
|
val x := a.pixels[index] as u32;
|
||||||
|
val y := b.pixels[index] as u32;
|
||||||
|
val gap := x > y ? x - y : y - x;
|
||||||
|
most = gap > most ? gap : most;
|
||||||
|
}
|
||||||
|
return most;
|
||||||
|
}
|
||||||
|
|
||||||
|
# How far an image strays from another in its colors alone, as JPEG keeps
|
||||||
|
# them, or 256 where they're of other sizes.
|
||||||
|
def colors_apart(a: &image::image, b: &image::image): u32 {
|
||||||
|
if a.width != b.width || a.height != b.height || a.pixels.length != b.pixels.length {
|
||||||
|
return 256;
|
||||||
|
}
|
||||||
|
var most: u32 = 0;
|
||||||
|
for index in 0..a.pixels.length {
|
||||||
|
if index % 4 == 3 {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
val x := a.pixels[index] as u32;
|
||||||
|
val y := b.pixels[index] as u32;
|
||||||
|
val gap := x > y ? x - y : y - x;
|
||||||
|
most = gap > most ? gap : most;
|
||||||
|
}
|
||||||
|
return most;
|
||||||
|
}
|
||||||
|
|
||||||
|
# How far an image strays from the pattern at most, in any channel, or 256 where
|
||||||
|
# it can't be read or is another size.
|
||||||
|
def stray(file: strview, kind: strview): u32 {
|
||||||
|
val read := image::load(file) else { return 256; };
|
||||||
|
val want := made_of(kind, 24, 20);
|
||||||
|
return apart(&read, &want);
|
||||||
|
}
|
||||||
|
|
||||||
|
# A pixel's red, green, blue, and alpha.
|
||||||
|
def rgba(r: u8, g: u8, b: u8, a: u8): u8[4] {
|
||||||
|
return [r, g, b, a];
|
||||||
|
}
|
||||||
|
|
||||||
|
# Whether reading an image failed, for a reason.
|
||||||
|
def fails(read: result<image::image, image::image_error>, why: image::image_error): bool {
|
||||||
|
match read {
|
||||||
|
value(&_) => return false;
|
||||||
|
error(e) => return e == why;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
# Whether writing an image failed, for a reason.
|
||||||
|
def fails_writing(written: result<vector<u8>, image::image_error>, why: image::image_error): bool {
|
||||||
|
match written {
|
||||||
|
value(&_) => return false;
|
||||||
|
error(e) => return e == why;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
# Whether bytes are found to be in a format.
|
||||||
|
def format_is(bytes: span<u8>, which: image::format): bool {
|
||||||
|
val found := image::format_of(bytes) else { return false; };
|
||||||
|
return found == which;
|
||||||
|
}
|
||||||
|
|
||||||
|
# Reads a test image's bytes.
|
||||||
|
def bytes_of(file: strview): string {
|
||||||
|
val at := path::parse(file) else (_) { return string::new(nothing {}); };
|
||||||
|
match io::read_file(&at) {
|
||||||
|
value(&read) => return string::copy_of(&read);
|
||||||
|
error(_) => return string::new(nothing {});
|
||||||
|
}
|
||||||
|
return string::new(nothing {});
|
||||||
|
}
|
||||||
|
|
||||||
|
# Reads bytes as an image, or an empty one where they aren't.
|
||||||
|
def read_back(bytes: span<u8>): image::image {
|
||||||
|
match image::decode(bytes) {
|
||||||
|
value(&made) => return image::image { width = made.width, height = made.height, pixels = vector::<u8>::copy_of(&made.pixels) };
|
||||||
|
error(_) => return image::image { pixels = vector::<u8>::new() };
|
||||||
|
}
|
||||||
|
return image::image { pixels = vector::<u8>::new() };
|
||||||
|
}
|
||||||
@@ -0,0 +1,129 @@
|
|||||||
|
#! Contains the tests of `image::svg`: shapes, sizes, strokes, gradients,
|
||||||
|
#! groups, and style sheets drawn, and broken SVG refused.
|
||||||
|
|
||||||
|
import std::testing;
|
||||||
|
import malunal::image;
|
||||||
|
|
||||||
|
# Draws an SVG at its own size.
|
||||||
|
def draw(text: strview): image::image {
|
||||||
|
return read_back(text);
|
||||||
|
}
|
||||||
|
|
||||||
|
@test def draws_svg_shapes(t: &mut tester): void {
|
||||||
|
val made := draw("""
|
||||||
|
<svg xmlns="http://www.w3.org/2000/svg" width="40" height="20">
|
||||||
|
<rect x="0" y="0" width="10" height="10" fill="red"/>
|
||||||
|
<circle cx="25" cy="10" r="6" fill="#0000ff"/>
|
||||||
|
<rect x="10.5" y="15" width="1" height="5" fill="lime"/>
|
||||||
|
<path d="M30 0 h10 v10 h-10 z m3 3 v4 h4 v-4 z" fill="black" fill-rule="evenodd"/>
|
||||||
|
</svg>
|
||||||
|
""");
|
||||||
|
t.expects(made.width == 40 && made.height == 20);
|
||||||
|
t.expects(made.at(5, 5) == rgba(255, 0, 0, 255));
|
||||||
|
t.expects(made.at(25, 10) == rgba(0, 0, 255, 255));
|
||||||
|
t.expects(made.at(15, 5) == rgba(0, 0, 0, 0));
|
||||||
|
# Half a pixel covered is half as opaque, and still the color.
|
||||||
|
val half := made.at(10, 17);
|
||||||
|
t.expects(half[1] == 255 && half[3] >= 126 && half[3] <= 129);
|
||||||
|
# The even-odd rule leaves a hole where the inner square crosses the outer.
|
||||||
|
t.expects(made.at(31, 1) == rgba(0, 0, 0, 255));
|
||||||
|
t.expects(made.at(35, 5) == rgba(0, 0, 0, 0));
|
||||||
|
}
|
||||||
|
|
||||||
|
@test def draws_svg_at_the_size_asked(t: &mut tester): void {
|
||||||
|
val text := "<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 10 5'><rect width='5' height='5' fill='#808080'/></svg>";
|
||||||
|
val own := draw(text);
|
||||||
|
t.expects(own.width == 10 && own.height == 5);
|
||||||
|
|
||||||
|
val wide := image::decode(text, image::svg_size { width = 100 }) else (_) { t.expects(false); return; };
|
||||||
|
t.expects(wide.width == 100 && wide.height == 50);
|
||||||
|
t.expects(wide.at(25, 25) == rgba(128, 128, 128, 255) && wide.at(75, 25) == rgba(0, 0, 0, 0));
|
||||||
|
|
||||||
|
val scaled := image::decode(text, image::svg_size { scale = 3 }) else (_) { t.expects(false); return; };
|
||||||
|
t.expects(scaled.width == 30 && scaled.height == 15);
|
||||||
|
|
||||||
|
# A view box of another shape is fit within, centered.
|
||||||
|
val square := image::decode(text, image::svg_size { width = 20, height = 20 }) else (_) { t.expects(false); return; };
|
||||||
|
t.expects(square.at(5, 2) == rgba(0, 0, 0, 0) && square.at(5, 10) == rgba(128, 128, 128, 255));
|
||||||
|
}
|
||||||
|
|
||||||
|
@test def strokes_svg_paths(t: &mut tester): void {
|
||||||
|
val made := draw("""
|
||||||
|
<svg xmlns="http://www.w3.org/2000/svg" width="40" height="30">
|
||||||
|
<line x1="10" y1="5" x2="30" y2="5" stroke="black" stroke-width="4"/>
|
||||||
|
<line x1="10" y1="15" x2="30" y2="15" stroke="black" stroke-width="4" stroke-linecap="square"/>
|
||||||
|
<line x1="10" y1="25" x2="30" y2="25" stroke="black" stroke-width="4" stroke-dasharray="5 5"/>
|
||||||
|
</svg>
|
||||||
|
""");
|
||||||
|
t.expects(made.at(20, 5) == rgba(0, 0, 0, 255) && made.at(20, 3) == rgba(0, 0, 0, 255) && made.at(20, 8) == rgba(0, 0, 0, 0));
|
||||||
|
# A butt cap ends at the end, and a square one past it.
|
||||||
|
t.expects(made.at(8, 5) == rgba(0, 0, 0, 0) && made.at(8, 15) == rgba(0, 0, 0, 255));
|
||||||
|
# Dashes, then gaps, five long each.
|
||||||
|
t.expects(made.at(12, 25) == rgba(0, 0, 0, 255) && made.at(17, 25) == rgba(0, 0, 0, 0) && made.at(22, 25) == rgba(0, 0, 0, 255));
|
||||||
|
}
|
||||||
|
|
||||||
|
@test def paints_svg_gradients(t: &mut tester): void {
|
||||||
|
val made := draw("""
|
||||||
|
<svg xmlns="http://www.w3.org/2000/svg" width="256" height="4">
|
||||||
|
<linearGradient id="ramp"><stop offset="0" stop-color="black"/><stop offset="1" stop-color="white"/></linearGradient>
|
||||||
|
<rect width="256" height="4" fill="url(#ramp)"/>
|
||||||
|
</svg>
|
||||||
|
""");
|
||||||
|
val middle := made.at(128, 2);
|
||||||
|
t.expects(middle[0] >= 126 && middle[0] <= 130 && middle[3] == 255);
|
||||||
|
t.expects(made.at(0, 2)[0] <= 2 && made.at(255, 2)[0] >= 253);
|
||||||
|
}
|
||||||
|
|
||||||
|
@test def composites_svg_groups(t: &mut tester): void {
|
||||||
|
val made := draw("""
|
||||||
|
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="40" height="20">
|
||||||
|
<defs>
|
||||||
|
<rect id="block" width="10" height="10"/>
|
||||||
|
<clipPath id="left"><rect width="25" height="20"/></clipPath>
|
||||||
|
</defs>
|
||||||
|
<g opacity="0.5" fill="blue">
|
||||||
|
<use xlink:href="#block"/>
|
||||||
|
<use xlink:href="#block" x="5"/>
|
||||||
|
</g>
|
||||||
|
<rect x="20" y="0" width="10" height="10" fill="red" clip-path="url(#left)"/>
|
||||||
|
</svg>
|
||||||
|
""");
|
||||||
|
# The group is drawn whole, then made half as opaque, so where its parts
|
||||||
|
# overlap is no more opaque than where they don't.
|
||||||
|
val alone := made.at(2, 5);
|
||||||
|
val overlapped := made.at(7, 5);
|
||||||
|
t.expects(alone[2] == 255 && alone[3] >= 127 && alone[3] <= 128);
|
||||||
|
t.expects(overlapped[3] == alone[3]);
|
||||||
|
# The clip keeps the red left of 25.
|
||||||
|
t.expects(made.at(22, 5) == rgba(255, 0, 0, 255) && made.at(27, 5) == rgba(0, 0, 0, 0));
|
||||||
|
}
|
||||||
|
|
||||||
|
@test def styles_svg_by_its_sheets(t: &mut tester): void {
|
||||||
|
val made := draw("""
|
||||||
|
<svg xmlns="http://www.w3.org/2000/svg" width="40" height="10" style="color: #00ff00">
|
||||||
|
<style>
|
||||||
|
.warm { fill: orange }
|
||||||
|
#hot { fill: red }
|
||||||
|
g rect { stroke: none }
|
||||||
|
</style>
|
||||||
|
<rect class="warm" width="10" height="10" fill="blue"/>
|
||||||
|
<rect class="warm" id="hot" x="10" width="10" height="10"/>
|
||||||
|
<rect x="20" width="10" height="10" style="fill: currentColor"/>
|
||||||
|
<rect x="30" width="10" height="10" fill="purple" fill-opacity="0.5"/>
|
||||||
|
</svg>
|
||||||
|
""");
|
||||||
|
t.expects(made.at(5, 5) == rgba(255, 165, 0, 255));
|
||||||
|
t.expects(made.at(15, 5) == rgba(255, 0, 0, 255));
|
||||||
|
t.expects(made.at(25, 5) == rgba(0, 255, 0, 255));
|
||||||
|
val faint := made.at(35, 5);
|
||||||
|
t.expects(faint[0] == 128 && faint[3] >= 127 && faint[3] <= 128);
|
||||||
|
}
|
||||||
|
|
||||||
|
@test def refuses_broken_svg(t: &mut tester): void {
|
||||||
|
t.expects(fails(image::decode("<svg xmlns='http://www.w3.org/2000/svg'><rect></svg>"), image::image_error::malformed));
|
||||||
|
t.expects(fails(image::decode("<svg xmlns='http://www.w3.org/2000/svg' width='0' height='10'/>"), image::image_error::malformed));
|
||||||
|
t.expects(fails(image::decode("<svg xmlns='http://www.w3.org/2000/svg' width='100000' height='100000'/>"), image::image_error::too_large));
|
||||||
|
# Path data broken partway is drawn as far as it goes.
|
||||||
|
val partial := draw("<svg xmlns='http://www.w3.org/2000/svg' width='10' height='10'><path d='M0 0 H10 V10 H0 Z L oops'/></svg>");
|
||||||
|
t.expects(partial.at(5, 5) == rgba(0, 0, 0, 255));
|
||||||
|
}
|
||||||
@@ -0,0 +1,123 @@
|
|||||||
|
#! Times writing and reading each format, of two images of 1024 by 1024 pixels:
|
||||||
|
#! one as a photograph is, smooth gradients with a little noise over them, and
|
||||||
|
#! one as an interface is, flat colors with hard edges. PNG is written at levels
|
||||||
|
#! 1, 6, and 9, and JPEG at quality 90, its chrominance halved both ways and
|
||||||
|
#! kept whole. Each is the best of three.
|
||||||
|
#!
|
||||||
|
#! `blossom build`, then run `malunal.image.bench`, as an executable: the
|
||||||
|
#! VM's times aren't the program's.
|
||||||
|
|
||||||
|
import std::io;
|
||||||
|
import std::time;
|
||||||
|
import malunal::image;
|
||||||
|
|
||||||
|
const side: u32 = 1024;
|
||||||
|
const tries: u32 = 3;
|
||||||
|
|
||||||
|
# A photograph's worth: gradients across, down, and along the diagonal, and
|
||||||
|
# noise of a few levels over them.
|
||||||
|
def photograph(): image::image {
|
||||||
|
var pixels := vector::<u8>::new();
|
||||||
|
pixels.reserve((side as u64) * (side as u64) * 4);
|
||||||
|
var seed: u32 = 12345;
|
||||||
|
for y in 0..side {
|
||||||
|
for x in 0..side {
|
||||||
|
seed = seed ^ (seed << 13);
|
||||||
|
seed = seed ^ (seed >> 17);
|
||||||
|
seed = seed ^ (seed << 5);
|
||||||
|
val noise := (seed % 9) as i32 - 4;
|
||||||
|
pixels.append(clamp((x * 255 / side) as i32 + noise));
|
||||||
|
pixels.append(clamp((y * 255 / side) as i32 + noise));
|
||||||
|
pixels.append(clamp(((x + y) * 255 / (2 * side)) as i32 - noise));
|
||||||
|
pixels.append(255);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return image::image { width = side, height = side, pixels = move(pixels) };
|
||||||
|
}
|
||||||
|
|
||||||
|
# An interface's worth: panels of a few flat colors, each with a border.
|
||||||
|
def interface(): image::image {
|
||||||
|
var pixels := vector::<u8>::new();
|
||||||
|
pixels.reserve((side as u64) * (side as u64) * 4);
|
||||||
|
for y in 0..side {
|
||||||
|
for x in 0..side {
|
||||||
|
val panel := (x / 128 + (y / 96) * 3) % 5;
|
||||||
|
val border := x % 128 < 2 || y % 96 < 2;
|
||||||
|
val color: u32 = border ? 0x303030 : panel_colors[panel as u64];
|
||||||
|
pixels.append((color >> 16) as u8);
|
||||||
|
pixels.append((color >> 8) as u8);
|
||||||
|
pixels.append(color as u8);
|
||||||
|
pixels.append(255);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return image::image { width = side, height = side, pixels = move(pixels) };
|
||||||
|
}
|
||||||
|
|
||||||
|
const panel_colors: u32[5] = [0xF0F0F0, 0x2D6CDF, 0xE8E8E8, 0xFFFFFF, 0xD04040];
|
||||||
|
|
||||||
|
def clamp(value: i32): u8 {
|
||||||
|
return (value < 0 ? 0 : (value > 255 ? 255 : value)) as u8;
|
||||||
|
}
|
||||||
|
|
||||||
|
# Writes an image, then reads it, each the best of a few tries, and says how
|
||||||
|
# long each took and how many bytes it was.
|
||||||
|
def time_png(what: strview, picture: &image::image, level: u32): void {
|
||||||
|
var best_write: f64 = 1e30;
|
||||||
|
var best_read: f64 = 1e30;
|
||||||
|
var size: u64 = 0;
|
||||||
|
for _ in 0..tries {
|
||||||
|
var at := instant::now();
|
||||||
|
val written := image::png::encode(picture, image::png::options { level = level }) else (_) { println("couldn't write"); return; };
|
||||||
|
val wrote := at.elapsed().in_nanoseconds as f64;
|
||||||
|
at = instant::now();
|
||||||
|
val read := image::decode(written.span) else (_) { println("couldn't read"); return; };
|
||||||
|
val took := at.elapsed().in_nanoseconds as f64;
|
||||||
|
best_write = wrote < best_write ? wrote : best_write;
|
||||||
|
best_read = took < best_read ? took : best_read;
|
||||||
|
size = written.length;
|
||||||
|
if read.pixels.length != picture.pixels.length {
|
||||||
|
println("read back another size");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
report(what, best_write, best_read, size);
|
||||||
|
}
|
||||||
|
|
||||||
|
def time_jpeg(what: strview, picture: &image::image, chroma: image::jpeg::subsampling): void {
|
||||||
|
var best_write: f64 = 1e30;
|
||||||
|
var best_read: f64 = 1e30;
|
||||||
|
var size: u64 = 0;
|
||||||
|
for _ in 0..tries {
|
||||||
|
var at := instant::now();
|
||||||
|
val written := image::jpeg::encode(picture, image::jpeg::options { quality = 90, chroma = chroma }) else (_) { println("couldn't write"); return; };
|
||||||
|
val wrote := at.elapsed().in_nanoseconds as f64;
|
||||||
|
at = instant::now();
|
||||||
|
val read := image::decode(written.span) else (_) { println("couldn't read"); return; };
|
||||||
|
val took := at.elapsed().in_nanoseconds as f64;
|
||||||
|
best_write = wrote < best_write ? wrote : best_write;
|
||||||
|
best_read = took < best_read ? took : best_read;
|
||||||
|
size = written.length;
|
||||||
|
if read.pixels.length != picture.pixels.length {
|
||||||
|
println("read back another size");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
report(what, best_write, best_read, size);
|
||||||
|
}
|
||||||
|
|
||||||
|
def report(what: strview, wrote: f64, read: f64, size: u64): void {
|
||||||
|
val pixels := (side as f64) * (side as f64);
|
||||||
|
println($"{what}: written in {(wrote / 1000000) as u64} ms ({(pixels * 1000 / wrote) as u64} MP/s), read in {(read / 1000000) as u64} ms, {size / 1024} KiB");
|
||||||
|
}
|
||||||
|
|
||||||
|
def main(): void {
|
||||||
|
val photo := photograph();
|
||||||
|
val flat := interface();
|
||||||
|
time_png("PNG level 1, photograph", &photo, 1);
|
||||||
|
time_png("PNG level 6, photograph", &photo, 6);
|
||||||
|
time_png("PNG level 9, photograph", &photo, 9);
|
||||||
|
time_png("PNG level 1, interface", &flat, 1);
|
||||||
|
time_png("PNG level 6, interface", &flat, 6);
|
||||||
|
time_png("PNG level 9, interface", &flat, 9);
|
||||||
|
time_jpeg("JPEG 90, 4:2:0, photograph", &photo, image::jpeg::subsampling::both);
|
||||||
|
time_jpeg("JPEG 90, 4:4:4, photograph", &photo, image::jpeg::subsampling::none);
|
||||||
|
time_jpeg("JPEG 90, 4:2:0, interface", &flat, image::jpeg::subsampling::both);
|
||||||
|
}
|
||||||
@@ -0,0 +1,78 @@
|
|||||||
|
# Writes the images `tests/` reads into `tests/images/`, with Windows' own encoders, which are no
|
||||||
|
# part of image's decoders. Each is 24 by 20 pixels of a pattern the tests work out again, as
|
||||||
|
# `tests/support.sakura` does, red rising across, green down, and blue along the diagonal:
|
||||||
|
#
|
||||||
|
# r = 10x, g = 12y, b = 5(x + y), a = 55 + 8x where it has alpha
|
||||||
|
#
|
||||||
|
# powershell -File tools/test_images.ps1
|
||||||
|
Add-Type -AssemblyName PresentationCore
|
||||||
|
$out = Join-Path $PSScriptRoot "..\tests\images"
|
||||||
|
New-Item -ItemType Directory -Force $out | Out-Null
|
||||||
|
$width = 24; $height = 20
|
||||||
|
$formats = [System.Windows.Media.PixelFormats]
|
||||||
|
|
||||||
|
# The pattern as BGRA, and as the samples of the other formats.
|
||||||
|
function Pattern([string]$kind) {
|
||||||
|
$bytes = New-Object System.Collections.Generic.List[byte]
|
||||||
|
for ($y = 0; $y -lt $height; $y++) {
|
||||||
|
for ($x = 0; $x -lt $width; $x++) {
|
||||||
|
$r = 10 * $x; $g = 12 * $y; $b = 5 * ($x + $y); $a = 55 + 8 * $x
|
||||||
|
switch ($kind) {
|
||||||
|
"bgra" { $bytes.Add($b); $bytes.Add($g); $bytes.Add($r); $bytes.Add($a) }
|
||||||
|
"bgr" { $bytes.Add($b); $bytes.Add($g); $bytes.Add($r) }
|
||||||
|
"gray" { $bytes.Add($g) }
|
||||||
|
"gray16" { $v = $g * 257; $bytes.Add($v -band 0xFF); $bytes.Add($v -shr 8) }
|
||||||
|
"rgba64" { foreach ($c in @($r, $g, $b, $a)) { $v = $c * 257; $bytes.Add($v -band 0xFF); $bytes.Add($v -shr 8) } }
|
||||||
|
"index" { $bytes.Add([byte]((($x -shr 2) + ($y -shr 2) * 6) % 16)) }
|
||||||
|
"bw" { }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return ,$bytes.ToArray()
|
||||||
|
}
|
||||||
|
|
||||||
|
function Save($encoder, [string]$name, $source) {
|
||||||
|
$encoder.Frames.Add([System.Windows.Media.Imaging.BitmapFrame]::Create($source))
|
||||||
|
$stream = [System.IO.File]::Create((Join-Path $out $name))
|
||||||
|
$encoder.Save($stream)
|
||||||
|
$stream.Close()
|
||||||
|
}
|
||||||
|
|
||||||
|
function Source($format, [byte[]]$pixels, [int]$bitsPerPixel, $palette = $null) {
|
||||||
|
$stride = [int][Math]::Ceiling($width * $bitsPerPixel / 8.0)
|
||||||
|
return [System.Windows.Media.Imaging.BitmapSource]::Create($width, $height, 96, 96, $format, $palette, $pixels, $stride)
|
||||||
|
}
|
||||||
|
|
||||||
|
function Png([string]$name, $source, [bool]$interlaced = $false) {
|
||||||
|
$encoder = New-Object System.Windows.Media.Imaging.PngBitmapEncoder
|
||||||
|
if ($interlaced) { $encoder.Interlace = [System.Windows.Media.Imaging.PngInterlaceOption]::On }
|
||||||
|
Save $encoder $name $source
|
||||||
|
}
|
||||||
|
|
||||||
|
Png "rgba8.png" (Source $formats::Bgra32 (Pattern "bgra") 32)
|
||||||
|
Png "rgb8.png" (Source $formats::Bgr24 (Pattern "bgr") 24)
|
||||||
|
Png "gray8.png" (Source $formats::Gray8 (Pattern "gray") 8)
|
||||||
|
Png "gray16.png" (Source $formats::Gray16 (Pattern "gray16") 16)
|
||||||
|
Png "rgba16.png" (Source $formats::Rgba64 (Pattern "rgba64") 64)
|
||||||
|
Png "interlaced.png" (Source $formats::Bgra32 (Pattern "bgra") 32) $true
|
||||||
|
|
||||||
|
# Sixteen colors, entry i being (16i, 255 - 16i, 8i), each with alpha 255 - 8i.
|
||||||
|
$colors = New-Object System.Collections.Generic.List[System.Windows.Media.Color]
|
||||||
|
for ($i = 0; $i -lt 16; $i++) { $colors.Add([System.Windows.Media.Color]::FromArgb(255 - 8 * $i, 16 * $i, 255 - 16 * $i, 8 * $i)) }
|
||||||
|
$palette = New-Object System.Windows.Media.Imaging.BitmapPalette -ArgumentList (,$colors)
|
||||||
|
$indices = Pattern "index"
|
||||||
|
$packed = New-Object byte[] (12 * $height)
|
||||||
|
for ($i = 0; $i -lt $indices.Length; $i++) {
|
||||||
|
$row = [Math]::Floor($i / $width); $column = $i % $width
|
||||||
|
$packed[$row * 12 + ($column -shr 1)] = $packed[$row * 12 + ($column -shr 1)] -bor ($indices[$i] -shl (4 * (1 - ($column -band 1))))
|
||||||
|
}
|
||||||
|
Png "palette4.png" (Source $formats::Indexed4 $packed 4 $palette)
|
||||||
|
|
||||||
|
$jpeg = New-Object System.Windows.Media.Imaging.JpegBitmapEncoder
|
||||||
|
$jpeg.QualityLevel = 95
|
||||||
|
Save $jpeg "rgb.jpg" (Source $formats::Bgr24 (Pattern "bgr") 24)
|
||||||
|
$gray = New-Object System.Windows.Media.Imaging.JpegBitmapEncoder
|
||||||
|
$gray.QualityLevel = 95
|
||||||
|
Save $gray "gray.jpg" (Source $formats::Gray8 (Pattern "gray") 8)
|
||||||
|
|
||||||
|
Get-ChildItem $out | ForEach-Object { "$($_.Name) $($_.Length)" }
|
||||||