Add std/base64, portable JPEG decoding, and portable PNG inflate

This commit is contained in:
waozi committed 2026-11-18 02:55:40 -03:00
1 parent 6669a95333
commit 4f49aa9aff
7 files changed
+1071 -11

No files matched your search

+9 -5
View File
@@ -1944,11 +1944,12 @@ runs an Emscripten `.js` such as `node`, or `WASI_RUN`, one that runs a
standalone `.wasm` such as `wasmtime run`, with `EMCC` for WebAssembly) to
compare every kernel with the scalar loops and those with std/image.
`std/png_linux.zi` reads every standard PNG into an `Image` and writes RGBA,
RGB and palette files; `std/jpeg.zi` writes baseline JPEGs at an IJG quality;
`std/zlib_linux.zi` compresses and decompresses whole zlib, gzip or raw
deflate streams into growing vectors. The PNG and zlib modules link `-lz`.
Run `sh tests/std_image_linux.sh build/bin/ziran`, which also compares with
Pillow when it is installed.
RGB and palette files; `std/jpeg.zi` reads baseline and progressive JPEGs into
an `Image` (`ReadJPEG`) and writes baseline JPEGs at an IJG quality
(`WriteJPEG`); `std/zlib_linux.zi` compresses and decompresses whole zlib,
gzip or raw deflate streams into growing vectors. The PNG writer and zlib
modules link `-lz`. Run `sh tests/std_image_linux.sh build/bin/ziran`, which
also compares with Pillow when it is installed.
`std/vorbis.zi` reads what an Ogg Vorbis stream in memory declares without
decoding it: `VorbisProbe(bytes, *audio)` checks that the bytes are whole
pages of one stream with a Vorbis identification header and gives its
@@ -2056,6 +2057,9 @@ and NaN, so native targets and portable bundles agree without reinterpreting
memory. Run `sh tests/std_binary.sh build/bin/ziran`, which also compares the
decoding with the C compiler's over a million random patterns.
`std/binary_linux.zi` keeps 64-bit fields for native Linux programs.
`std/base64.zi` encodes and decodes RFC 4648 base64 (`Base64EncodeInto`,
`Base64Encode`, `Base64DecodeInto`, `Base64Decode`) for `data:` URIs and binary
payloads; run `sh tests/std_base64.sh build/bin/ziran`.
### Constant tables
+132
View File
@@ -0,0 +1,132 @@
// RFC 4648 base64 encoding and decoding on every target, for data: URIs,
// embedded binary payloads and wire protocols.
//
// bytes: Vec(u8)
// if !Base64DecodeInto(encoded, *bytes) { ... }
// text := Base64Encode(VecSlice(bytes, 0, bytes.count))
using Vectors :: #import "vec"
#scope_file
Space :: (byte: u8) -> bool {
return byte == 32 || byte == 9 || byte == 10 || byte == 13
}
Sextet :: (byte: u8) -> s32 {
if byte >= #char "A" && byte <= #char "Z" { return cast(s32)(byte - #char "A") }
if byte >= #char "a" && byte <= #char "z" { return cast(s32)(byte - #char "a") + 26 }
if byte >= #char "0" && byte <= #char "9" { return cast(s32)(byte - #char "0") + 52 }
if byte == #char "+" || byte == #char "-" { return 62 }
if byte == #char "/" || byte == #char "_" { return 63 }
return -1
}
#scope_export
// Appends the standard padded RFC 4648 base64 encoding of BYTES to OUTPUT.
#program_export
Base64EncodeInto :: (bytes: []u8, output: *Vec(u8)) {
alphabet := "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
at: s64 = 0
while at + 3 <= bytes.count {
b0 := cast(u32)bytes[at]
b1 := cast(u32)bytes[at + 1]
b2 := cast(u32)bytes[at + 2]
word := (b0 << 16) | (b1 << 8) | b2
VecPush(<<output, alphabet[(word >> 18) & 63])
VecPush(<<output, alphabet[(word >> 12) & 63])
VecPush(<<output, alphabet[(word >> 6) & 63])
VecPush(<<output, alphabet[word & 63])
at += 3
}
remaining := bytes.count - at
if remaining == 1 {
b0 := cast(u32)bytes[at]
VecPush(<<output, alphabet[(b0 >> 2) & 63])
VecPush(<<output, alphabet[(b0 << 4) & 63])
VecPush(<<output, #char "=")
VecPush(<<output, #char "=")
} else if remaining == 2 {
b0 := cast(u32)bytes[at]
b1 := cast(u32)bytes[at + 1]
word := (b0 << 8) | b1
VecPush(<<output, alphabet[(word >> 10) & 63])
VecPush(<<output, alphabet[(word >> 4) & 63])
VecPush(<<output, alphabet[(word << 2) & 63])
VecPush(<<output, #char "=")
}
}
// The standard padded RFC 4648 base64 text for BYTES.
#program_export
Base64Encode :: (bytes: []u8) -> Text {
output: Vec(u8)
Base64EncodeInto(bytes, *output)
return BuilderFinish(output)
}
// Appends the bytes decoded from TEXT to OUTPUT. Accepts standard (+/) and
// URL-safe (-_) alphabets and skips ASCII whitespace; refuses bad characters,
// truncated groups or misplaced '=' padding.
#program_export
Base64DecodeInto :: (text: string, output: *Vec(u8)) -> bool {
start := output.count
quad: [4]s32
pads: s32 = 0
in_quad: s32 = 0
padded := false
for index: 0..text.count - 1 {
byte := text[index]
if Space(byte) { continue }
if padded {
output.count = start
return false
}
if byte == #char "=" {
if in_quad < 2 {
output.count = start
return false
}
quad[in_quad] = 0
pads += 1
in_quad += 1
} else {
if pads > 0 {
output.count = start
return false
}
value := Sextet(byte)
if value < 0 {
output.count = start
return false
}
quad[in_quad] = value
in_quad += 1
}
if in_quad == 4 {
word := (cast(u32)quad[0] << 18) | (cast(u32)quad[1] << 12) | (cast(u32)quad[2] << 6) | cast(u32)quad[3]
VecPush(<<output, cast(u8)((word >> 16) & 255))
if pads < 2 { VecPush(<<output, cast(u8)((word >> 8) & 255)) }
if pads == 0 { VecPush(<<output, cast(u8)(word & 255)) }
else { padded = true }
in_quad = 0
pads = 0
}
}
if in_quad != 0 {
output.count = start
return false
}
return true
}
// Decodes TEXT into byte text and sets OK to whether TEXT was valid base64.
#program_export
Base64Decode :: (text: string, ok: *bool) -> Text {
output: Vec(u8)
valid := Base64DecodeInto(text, *output)
if ok != null { <<ok = valid }
if !valid {
VecFree(output)
return TextCopy("")
}
return BuilderFinish(output)
}
+618 -3
View File
@@ -1,9 +1,11 @@
// Baseline JPEG files from std/image pictures, on every target: JFIF with
// 4:2:0 chroma subsampling, the standard Huffman tables and the IJG quality
// scale that libjpeg and Pillow use. Alpha is ignored.
// Baseline and progressive JPEG files to and from std/image pictures, on every
// target: JFIF writing with 4:2:0 chroma subsampling, standard Huffman tables
// and the IJG quality scale that libjpeg and Pillow use; reading accepts
// baseline (SOF0/SOF1) and progressive (SOF2) greyscale and YCbCr JPEGs.
//
// bytes: Vec(u8)
// if WriteJPEG(*title, *bytes, 82) { WriteEntireFile("title.jpg", BuilderFinish(bytes)) }
// decoded := ReadJPEG(VecSlice(bytes, 0, bytes.count))
#import "image"
#import "math"
using Vectors :: #import "vec"
@@ -247,3 +249,616 @@ WriteJPEG :: (image: *Image, output: *Vec(u8), quality: s32 = 75) -> bool {
Word(output, 65497)
return true
}
#scope_file
JpegHuff :: struct {
counts: [16]s32
symbols: [256]u8
valid: bool
}
JpegBuildHuff :: (table: *JpegHuff, counts: []u8, symbols: []u8) -> bool {
if counts.count < 16 { return false }
total: s32 = 0
left: s32 = 1
for i: 0..15 {
c := cast(s32)counts[i]
table.counts[i] = c
total += c
left = (left << 1) - c
if left < 0 { return false }
}
if total > 256 || symbols.count < total { return false }
for i: 0..total - 1 { table.symbols[i] = symbols[i] }
table.valid = true
return true
}
JpegReader :: struct {
bytes: []u8
pos: s64
bits: u32
count: s32
hit_marker: bool
corrupt: bool
}
JpegFillBits :: (r: *JpegReader) {
while r.count <= 24 && !r.hit_marker {
if r.pos >= r.bytes.count {
r.hit_marker = true
break
}
b := r.bytes[r.pos]
if b == 255 {
if r.pos + 1 >= r.bytes.count {
r.hit_marker = true
break
}
b2 := r.bytes[r.pos + 1]
if b2 == 0 {
r.pos += 2
r.bits = (r.bits << 8) | 255
r.count += 8
} else if b2 == 255 {
r.pos += 1
} else {
r.hit_marker = true
break
}
} else {
r.pos += 1
r.bits = (r.bits << 8) | cast(u32)b
r.count += 8
}
}
}
JpegReceive :: (r: *JpegReader, n: s32) -> s32 {
if n == 0 { return 0 }
if r.count < n { JpegFillBits(r) }
if r.count < n {
r.corrupt = true
return 0
}
r.count -= n
return cast(s32)((r.bits >> cast(u32)r.count) & ((cast(u32)1 << cast(u32)n) - 1))
}
JpegExtend :: (val: s32, n: s32) -> s32 {
if n <= 0 { return 0 }
vt := 1 << (n - 1)
if val < vt { return val + ((-1) << n) + 1 }
return val
}
JpegDecodeHuff :: (r: *JpegReader, table: *JpegHuff) -> s32 {
if !table.valid { r.corrupt = true; return 0 }
code: s32 = 0
first: s32 = 0
index: s32 = 0
for len: 0..15 {
if r.count < 1 { JpegFillBits(r) }
if r.count < 1 { r.corrupt = true; return 0 }
r.count -= 1
bit := cast(s32)((r.bits >> cast(u32)r.count) & 1)
code = (code << 1) | bit
c := table.counts[len]
if code - c < first {
return cast(s32)table.symbols[index + (code - first)]
}
index += c
first = (first + c) << 1
}
r.corrupt = true
return 0
}
JpegComp :: struct {
id: s32
h_samp: s32
v_samp: s32
tq: s32
blocks_w: s32
blocks_h: s32
stride: s32
dc_pred: s32
coeffs: Vec(s32)
pixels: Vec(u8)
}
JpegClampByte :: (v: float64) -> u8 {
n := cast(s32)(ifx v < 0.0 then v - 0.5 else v + 0.5)
if n < 0 { return 0 }
if n > 255 { return 255 }
return cast(u8)n
}
JpegDecodeBlockSeq :: (r: *JpegReader, dc: *JpegHuff, ac: *JpegHuff, pred: *s32, coeffs: *Vec(s32), base: s64) -> bool {
s := JpegDecodeHuff(r, dc)
if r.corrupt || s > 15 { return false }
diff := ifx s > 0 then JpegExtend(JpegReceive(r, s), s) else 0
if r.corrupt { return false }
<<pred += diff
(<<coeffs)[base] = <<pred
k: s32 = 1
while k <= 63 {
rs := JpegDecodeHuff(r, ac)
if r.corrupt { return false }
run := (rs >> 4) & 15
sz := rs & 15
if sz == 0 {
if run == 15 { k += 16 }
else { break }
} else {
k += run
if k > 63 || sz > 15 { return false }
(<<coeffs)[base + k] = JpegExtend(JpegReceive(r, sz), sz)
if r.corrupt { return false }
k += 1
}
}
return true
}
JpegDecodeBlockProgDC :: (r: *JpegReader, dc: *JpegHuff, pred: *s32, coeffs: *Vec(s32), base: s64, ah: s32, al: s32) -> bool {
if ah == 0 {
s := JpegDecodeHuff(r, dc)
if r.corrupt || s > 15 { return false }
diff := ifx s > 0 then JpegExtend(JpegReceive(r, s), s) else 0
if r.corrupt { return false }
<<pred += diff
(<<coeffs)[base] = <<pred << al
} else {
bit := JpegReceive(r, 1)
if r.corrupt { return false }
(<<coeffs)[base] = (<<coeffs)[base] | (bit << al)
}
return true
}
JpegDecodeBlockProgACFirst :: (r: *JpegReader, ac: *JpegHuff, eob_run: *s32, coeffs: *Vec(s32), base: s64, ss: s32, se: s32, al: s32) -> bool {
if <<eob_run > 0 {
<<eob_run -= 1
return true
}
k := ss
while k <= se {
rs := JpegDecodeHuff(r, ac)
if r.corrupt { return false }
run := (rs >> 4) & 15
sz := rs & 15
if sz == 0 {
if run == 15 {
k += 16
} else {
<<eob_run = (1 << run) - 1
if run > 0 {
<<eob_run += JpegReceive(r, run)
if r.corrupt { return false }
}
break
}
} else {
k += run
if k > se || sz > 15 { return false }
(<<coeffs)[base + k] = JpegExtend(JpegReceive(r, sz), sz) << al
if r.corrupt { return false }
k += 1
}
}
return true
}
JpegDecodeBlockProgACRefine :: (r: *JpegReader, ac: *JpegHuff, eob_run: *s32, coeffs: *Vec(s32), base: s64, ss: s32, se: s32, al: s32) -> bool {
p1 := 1 << al
m1 := (-1) << al
k := ss
if <<eob_run == 0 {
while k <= se {
rs := JpegDecodeHuff(r, ac)
if r.corrupt { return false }
run := (rs >> 4) & 15
sz := rs & 15
val: s32 = 0
if sz == 0 {
if run < 15 {
<<eob_run = 1 << run
if run > 0 {
<<eob_run += JpegReceive(r, run)
if r.corrupt { return false }
}
break
}
} else if sz == 1 {
bit := JpegReceive(r, 1)
if r.corrupt { return false }
val = ifx bit != 0 then p1 else m1
} else {
return false
}
while k <= se {
cur := (<<coeffs)[base + k]
if cur != 0 {
bit := JpegReceive(r, 1)
if r.corrupt { return false }
if bit != 0 && (cur & p1) == 0 {
(<<coeffs)[base + k] = cur + (ifx cur > 0 then p1 else m1)
}
k += 1
} else {
if run == 0 { break }
run -= 1
k += 1
}
}
if val != 0 && k <= se {
(<<coeffs)[base + k] = val
k += 1
}
}
}
if <<eob_run > 0 {
while k <= se {
cur := (<<coeffs)[base + k]
if cur != 0 {
bit := JpegReceive(r, 1)
if r.corrupt { return false }
if bit != 0 && (cur & p1) == 0 {
(<<coeffs)[base + k] = cur + (ifx cur > 0 then p1 else m1)
}
}
k += 1
}
<<eob_run -= 1
}
return true
}
JpegCheckRestart :: (r: *JpegReader, comps: []JpegComp, eob_run: *s32) {
r.bits = 0
r.count = 0
r.hit_marker = false
for c: 0..2 { comps[c].dc_pred = 0 }
<<eob_run = 0
while r.pos < r.bytes.count && r.bytes[r.pos] == 255 { r.pos += 1 }
if r.pos < r.bytes.count && r.bytes[r.pos] >= 208 && r.bytes[r.pos] <= 215 {
r.pos += 1
} else if r.pos > 0 && r.bytes[r.pos - 1] == 255 {
r.pos -= 1
}
}
#scope_export
// Decodes a baseline or progressive JPEG file's bytes (1-channel greyscale or
// 3-channel YCbCr with any standard chroma subsampling) into an Image.
// Returns an invalid Image (see ImageValid) when BYTES is not a supported JPEG.
ReadJPEG :: (bytes: []u8) -> Image {
if bytes.count < 4 || bytes[0] != 255 || bytes[1] != 216 { return NewImage(0, 0) }
q_tables: [4][64]s32
q_valid: [4]bool
dc_huff: [4]JpegHuff
ac_huff: [4]JpegHuff
unused JpegBuildHuff(*dc_huff[0], DC_LUMINANCE_COUNTS[:], DC_SYMBOLS[:])
unused JpegBuildHuff(*dc_huff[1], DC_CHROMINANCE_COUNTS[:], DC_SYMBOLS[:])
unused JpegBuildHuff(*ac_huff[0], AC_LUMINANCE_COUNTS[:], AC_LUMINANCE_SYMBOLS[:])
unused JpegBuildHuff(*ac_huff[1], AC_CHROMINANCE_COUNTS[:], AC_CHROMINANCE_SYMBOLS[:])
comps: [3]JpegComp
defer {
VecFree(comps[0].coeffs); VecFree(comps[0].pixels)
VecFree(comps[1].coeffs); VecFree(comps[1].pixels)
VecFree(comps[2].coeffs); VecFree(comps[2].pixels)
}
n_comp: s32 = 0
width: s32 = 0
height: s32 = 0
h_max: s32 = 1
v_max: s32 = 1
mcu_cols: s32 = 0
mcu_rows: s32 = 0
restart_interval: s32 = 0
have_sof := false
progressive := false
have_scan := false
at: s64 = 2
while at < bytes.count {
while at < bytes.count && bytes[at] != 255 { at += 1 }
while at < bytes.count && bytes[at] == 255 { at += 1 }
if at >= bytes.count { break }
marker := bytes[at]
at += 1
if marker == 0 || (marker >= 208 && marker <= 215) || marker == 216 { continue }
if marker == 217 { break }
if at + 2 > bytes.count { return NewImage(0, 0) }
seg_len := (cast(s64)bytes[at] << 8) | cast(s64)bytes[at + 1]
if seg_len < 2 || at + seg_len > bytes.count { return NewImage(0, 0) }
seg_start := at + 2
seg_end := at + seg_len
if marker == 219 {
p := seg_start
while p < seg_end {
pq_tq := bytes[p]
p += 1
pq := (pq_tq >> 4) & 15
tq := pq_tq & 15
if tq > 3 || (pq != 0 && pq != 1) { return NewImage(0, 0) }
need: s64 = ifx pq == 0 then 64 else 128
if p + need > seg_end { return NewImage(0, 0) }
for i: 0..63 {
q_tables[tq][i] = ifx pq == 0 then cast(s32)bytes[p + i] else (cast(s32)bytes[p + i * 2] << 8) | cast(s32)bytes[p + i * 2 + 1]
}
q_valid[tq] = true
p += need
}
} else if marker == 196 {
p := seg_start
while p < seg_end {
if p + 17 > seg_end { return NewImage(0, 0) }
tc_th := bytes[p]
p += 1
tc := (tc_th >> 4) & 15
th := tc_th & 15
if (tc != 0 && tc != 1) || th > 3 { return NewImage(0, 0) }
total: s64 = 0
for i: 0..15 { total += cast(s64)bytes[p + i] }
if total > 256 || p + 16 + total > seg_end { return NewImage(0, 0) }
target := ifx tc == 0 then *dc_huff[th] else *ac_huff[th]
if !JpegBuildHuff(target, bytes[p:p + 16], bytes[p + 16:p + 16 + total]) { return NewImage(0, 0) }
p += 16 + total
}
} else if marker == 221 {
if seg_len != 4 { return NewImage(0, 0) }
restart_interval = (cast(s32)bytes[seg_start] << 8) | cast(s32)bytes[seg_start + 1]
} else if marker == 192 || marker == 193 || marker == 194 {
if have_sof || seg_len < 8 { return NewImage(0, 0) }
prec := bytes[seg_start]
height = (cast(s32)bytes[seg_start + 1] << 8) | cast(s32)bytes[seg_start + 2]
width = (cast(s32)bytes[seg_start + 3] << 8) | cast(s32)bytes[seg_start + 4]
n_comp = cast(s32)bytes[seg_start + 5]
if prec != 8 || width <= 0 || height <= 0 || cast(s64)width * height > 67108864 ||
(n_comp != 1 && n_comp != 3) || seg_len != 8 + cast(s64)n_comp * 3 { return NewImage(0, 0) }
progressive = marker == 194
h_max = 1
v_max = 1
for c: 0..n_comp - 1 {
cp := seg_start + 6 + c * 3
comps[c].id = cast(s32)bytes[cp]
samp := cast(s32)bytes[cp + 1]
comps[c].h_samp = (samp >> 4) & 15
comps[c].v_samp = samp & 15
comps[c].tq = cast(s32)bytes[cp + 2]
if comps[c].h_samp < 1 || comps[c].h_samp > 4 ||
comps[c].v_samp < 1 || comps[c].v_samp > 4 || comps[c].tq > 3 { return NewImage(0, 0) }
if comps[c].h_samp > h_max { h_max = comps[c].h_samp }
if comps[c].v_samp > v_max { v_max = comps[c].v_samp }
}
if n_comp == 1 {
comps[0].h_samp = 1
comps[0].v_samp = 1
h_max = 1
v_max = 1
}
mcu_cols = (width + 8 * h_max - 1) / (8 * h_max)
mcu_rows = (height + 8 * v_max - 1) / (8 * v_max)
for c: 0..n_comp - 1 {
comps[c].stride = mcu_cols * comps[c].h_samp
comps[c].blocks_w = (cast(s32)((cast(s64)width * comps[c].h_samp + h_max - 1) / h_max) + 7) / 8
comps[c].blocks_h = (cast(s32)((cast(s64)height * comps[c].v_samp + v_max - 1) / v_max) + 7) / 8
total_coeffs := cast(s64)comps[c].stride * (mcu_rows * comps[c].v_samp) * 64
if !VecResize(comps[c].coeffs, total_coeffs) { return NewImage(0, 0) }
for idx: 0..total_coeffs - 1 { comps[c].coeffs[idx] = 0 }
}
have_sof = true
} else if marker >= 195 && marker <= 207 {
return NewImage(0, 0)
} else if marker == 218 {
if !have_sof || seg_len < 6 { return NewImage(0, 0) }
ns := cast(s32)bytes[seg_start]
if ns < 1 || ns > n_comp || seg_len != 6 + cast(s64)ns * 2 { return NewImage(0, 0) }
scan_comp: [3]s32
scan_td: [3]s32
scan_ta: [3]s32
for j: 0..ns - 1 {
cid := cast(s32)bytes[seg_start + 1 + j * 2]
td_ta := cast(s32)bytes[seg_start + 2 + j * 2]
td := (td_ta >> 4) & 15
ta := td_ta & 15
if td > 3 || ta > 3 { return NewImage(0, 0) }
found: s32 = -1
for c: 0..n_comp - 1 {
if comps[c].id == cid { found = c; break }
}
if found < 0 { return NewImage(0, 0) }
scan_comp[j] = found
scan_td[j] = td
scan_ta[j] = ta
}
ss := cast(s32)bytes[seg_start + 1 + ns * 2]
se := cast(s32)bytes[seg_start + 2 + ns * 2]
ah_al := cast(s32)bytes[seg_start + 3 + ns * 2]
ah := (ah_al >> 4) & 15
al := ah_al & 15
if !progressive {
if ss != 0 || se != 63 || ah != 0 || al != 0 { return NewImage(0, 0) }
} else {
if ss < 0 || se > 63 || ss > se || (ss == 0 && se != 0) || (ss > 0 && ns != 1) || al > 13 || ah > 13 { return NewImage(0, 0) }
}
reader: JpegReader
reader.bytes = bytes
reader.pos = seg_end
for c: 0..2 { comps[c].dc_pred = 0 }
eob_run: s32 = 0
mcu_count: s32 = 0
if ns == 1 {
c := scan_comp[0]
td := scan_td[0]
ta := scan_ta[0]
total_units := comps[c].blocks_w * comps[c].blocks_h
for by: 0..comps[c].blocks_h - 1 {
for bx: 0..comps[c].blocks_w - 1 {
if restart_interval > 0 && mcu_count > 0 && (mcu_count % restart_interval) == 0 {
JpegCheckRestart(*reader, comps[:], *eob_run)
}
base := (cast(s64)by * comps[c].stride + bx) * 64
ok := false
if !progressive {
ok = JpegDecodeBlockSeq(*reader, *dc_huff[td], *ac_huff[ta], *comps[c].dc_pred, *comps[c].coeffs, base)
} else if ss == 0 {
ok = JpegDecodeBlockProgDC(*reader, *dc_huff[td], *comps[c].dc_pred, *comps[c].coeffs, base, ah, al)
} else if ah == 0 {
ok = JpegDecodeBlockProgACFirst(*reader, *ac_huff[ta], *eob_run, *comps[c].coeffs, base, ss, se, al)
} else {
ok = JpegDecodeBlockProgACRefine(*reader, *ac_huff[ta], *eob_run, *comps[c].coeffs, base, ss, se, al)
}
if !ok { return NewImage(0, 0) }
mcu_count += 1
unused total_units
}
}
} else {
for mcu_y: 0..mcu_rows - 1 {
for mcu_x: 0..mcu_cols - 1 {
if restart_interval > 0 && mcu_count > 0 && (mcu_count % restart_interval) == 0 {
JpegCheckRestart(*reader, comps[:], *eob_run)
}
for j: 0..ns - 1 {
c := scan_comp[j]
td := scan_td[j]
ta := scan_ta[j]
for by: 0..comps[c].v_samp - 1 {
for bx: 0..comps[c].h_samp - 1 {
blk_x := mcu_x * comps[c].h_samp + bx
blk_y := mcu_y * comps[c].v_samp + by
base := (cast(s64)blk_y * comps[c].stride + blk_x) * 64
ok := false
if !progressive {
ok = JpegDecodeBlockSeq(*reader, *dc_huff[td], *ac_huff[ta], *comps[c].dc_pred, *comps[c].coeffs, base)
} else {
ok = JpegDecodeBlockProgDC(*reader, *dc_huff[td], *comps[c].dc_pred, *comps[c].coeffs, base, ah, al)
}
if !ok { return NewImage(0, 0) }
}
}
}
mcu_count += 1
}
}
}
have_scan = true
at = reader.pos
continue
}
at = seg_end
}
if !have_sof || !have_scan { return NewImage(0, 0) }
for c: 0..n_comp - 1 {
if !q_valid[comps[c].tq] { return NewImage(0, 0) }
}
basis: [64]float64
for x: 0..7 {
for u: 0..7 {
scale := ifx u == 0 then 0.35355339059327376 else 0.5
basis[x * 8 + u] = scale * Cos((2.0 * cast(float64)x + 1.0) * cast(float64)u * 3.14159265358979323846 / 16.0)
}
}
for c: 0..n_comp - 1 {
pw := comps[c].stride * 8
ph := mcu_rows * comps[c].v_samp * 8
if !VecResize(comps[c].pixels, cast(s64)pw * ph) { return NewImage(0, 0) }
qt := q_tables[comps[c].tq][:]
total_blocks_h := mcu_rows * comps[c].v_samp
deq: [64]float64
tmp: [64]float64
for by: 0..total_blocks_h - 1 {
for bx: 0..comps[c].stride - 1 {
base := (cast(s64)by * comps[c].stride + bx) * 64
ac_nonzero := false
for k: 1..63 {
if comps[c].coeffs[base + k] != 0 { ac_nonzero = true; break }
}
if !ac_nonzero {
dc_val := JpegClampByte(cast(float64)(comps[c].coeffs[base] * qt[0]) * 0.125 + 128.0)
for py: 0..7 {
row_off := cast(s64)(by * 8 + py) * pw + bx * 8
for px: 0..7 { comps[c].pixels[row_off + px] = dc_val }
}
} else {
for k: 0..63 {
deq[ZIGZAG[k]] = cast(float64)(comps[c].coeffs[base + k] * qt[k])
}
for y: 0..7 {
row := y * 8
for x: 0..7 {
sum: float64 = 0.0
for u: 0..7 { sum += deq[row + u] * basis[x * 8 + u] }
tmp[row + x] = sum
}
}
for y: 0..7 {
row_off := cast(s64)(by * 8 + y) * pw + bx * 8
for x: 0..7 {
sum: float64 = 0.0
for v: 0..7 { sum += tmp[v * 8 + x] * basis[y * 8 + v] }
comps[c].pixels[row_off + x] = JpegClampByte(sum + 128.0)
}
}
}
}
}
}
result := NewImage(width, height)
if n_comp == 1 {
pw := comps[0].stride * 8
for y: 0..height - 1 {
src_row := cast(s64)y * pw
dst_row := cast(s64)y * width * 4
for x: 0..width - 1 {
g := comps[0].pixels[src_row + x]
at_px := dst_row + x * 4
result.pixels[at_px] = g
result.pixels[at_px + 1] = g
result.pixels[at_px + 2] = g
result.pixels[at_px + 3] = 255
}
}
} else {
pw0 := comps[0].stride * 8
pw1 := comps[1].stride * 8
pw2 := comps[2].stride * 8
h0 := comps[0].h_samp; v0 := comps[0].v_samp
h1 := comps[1].h_samp; v1 := comps[1].v_samp
h2 := comps[2].h_samp; v2 := comps[2].v_samp
for y: 0..height - 1 {
y0 := (y * v0) / v_max
y1 := (y * v1) / v_max
y2 := (y * v2) / v_max
row0 := cast(s64)y0 * pw0
row1 := cast(s64)y1 * pw1
row2 := cast(s64)y2 * pw2
dst_row := cast(s64)y * width * 4
for x: 0..width - 1 {
x0 := (x * h0) / h_max
x1 := (x * h1) / h_max
x2 := (x * h2) / h_max
yv := cast(float64)comps[0].pixels[row0 + x0]
cb := cast(float64)comps[1].pixels[row1 + x1] - 128.0
cr := cast(float64)comps[2].pixels[row2 + x2] - 128.0
at_px := dst_row + x * 4
result.pixels[at_px] = JpegClampByte(yv + 1.402 * cr)
result.pixels[at_px + 1] = JpegClampByte(yv - 0.344136 * cb - 0.714136 * cr)
result.pixels[at_px + 2] = JpegClampByte(yv + 1.772 * cb)
result.pixels[at_px + 3] = 255
}
}
}
return result
}
+204 -3
View File
@@ -81,6 +81,204 @@ Scale :: (value: s32, depth: s32) -> u8 {
return cast(u8)(value * 255 / ((1 << depth) - 1))
}
PNG_LEN_BASE: [29]s32 = .[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];
PNG_LEN_EXTRA: [29]s32 = .[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];
PNG_DIST_BASE: [30]s32 = .[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];
PNG_DIST_EXTRA: [30]s32 = .[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];
PNG_CL_ORDER: [19]s32 = .[16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15];
PngHuff :: struct {
counts: [16]s32
symbols: [288]s32
}
PngBuildHuff :: (tree: *PngHuff, lengths: []s32, count: s32) -> bool {
for i: 0..15 { tree.counts[i] = 0 }
for i: 0..count - 1 {
len := lengths[i]
if len < 0 || len > 15 { return false }
tree.counts[len] += 1
}
if tree.counts[0] == count { return true }
left: s32 = 1
for len: 1..15 {
left = (left << 1) - tree.counts[len]
if left < 0 { return false }
}
offsets: [16]s32
sum: s32 = 0
for len: 1..15 {
offsets[len] = sum
sum += tree.counts[len]
}
for i: 0..count - 1 {
len := lengths[i]
if len != 0 {
tree.symbols[offsets[len]] = i
offsets[len] += 1
}
}
return true
}
PngBits :: (input: []u8, bit_pos: *s64, count: s32) -> s32 {
if count == 0 { return 0 }
pos := <<bit_pos
if pos + count > input.count * 8 { return -1 }
val: s32 = 0
for i: 0..count - 1 {
b := pos + i
bit := (cast(s32)input[b >> 3] >> cast(s32)(b & 7)) & 1
val |= bit << i
}
<<bit_pos = pos + count
return val
}
PngDecodeSym :: (input: []u8, bit_pos: *s64, tree: *PngHuff) -> s32 {
pos := <<bit_pos
total_bits := input.count * 8
code: s32 = 0
first: s32 = 0
index: s32 = 0
for len: 1..15 {
if pos >= total_bits { return -1 }
bit := (cast(s32)input[pos >> 3] >> cast(s32)(pos & 7)) & 1
pos += 1
code |= bit
count := tree.counts[len]
if code - count < first {
<<bit_pos = pos
return tree.symbols[index + (code - first)]
}
index += count
first = (first + count) << 1
code = code << 1
}
return -1
}
PngInflate :: (input: []u8, output: *Vec(u8), expected: s64) -> bool {
if input.count < 6 || expected < 0 { return false }
cmf := cast(u32)input[0]
flg := cast(u32)input[1]
if (cmf & 15) != 8 || (cmf >> 4) > 7 || ((cmf << 8 | flg) % 31) != 0 || (flg & 32) != 0 { return false }
bit_pos: s64 = 16
lit_tree: PngHuff
dist_tree: PngHuff
cl_tree: PngHuff
lengths: [320]s32
while true {
bfinal := PngBits(input, *bit_pos, 1)
btype := PngBits(input, *bit_pos, 2)
if bfinal < 0 || btype < 0 || btype == 3 { return false }
if btype == 0 {
bit_pos = (bit_pos + 7) & ~cast(s64)7
byte_pos := bit_pos >> 3
if byte_pos + 4 > input.count { return false }
len := cast(s32)input[byte_pos] | (cast(s32)input[byte_pos + 1] << 8)
nlen := cast(s32)input[byte_pos + 2] | (cast(s32)input[byte_pos + 3] << 8)
if (len ^ 65535) != nlen { return false }
byte_pos += 4
if byte_pos + len > input.count || output.count + len > expected { return false }
for i: 0..len - 1 { VecPush(<<output, input[byte_pos + i]) }
bit_pos = (byte_pos + len) * 8
} else {
if btype == 1 {
for i: 0..143 { lengths[i] = 8 }
for i: 144..255 { lengths[i] = 9 }
for i: 256..279 { lengths[i] = 7 }
for i: 280..287 { lengths[i] = 8 }
if !PngBuildHuff(*lit_tree, lengths[0:288], 288) { return false }
for i: 0..31 { lengths[i] = 5 }
if !PngBuildHuff(*dist_tree, lengths[0:32], 32) { return false }
} else {
hlit := PngBits(input, *bit_pos, 5)
hdist := PngBits(input, *bit_pos, 5)
hclen := PngBits(input, *bit_pos, 4)
if hlit < 0 || hdist < 0 || hclen < 0 { return false }
hlit += 257; hdist += 1; hclen += 4
if hlit > 286 || hdist > 30 { return false }
cl_lengths: [19]s32
for i: 0..hclen - 1 {
v := PngBits(input, *bit_pos, 3)
if v < 0 { return false }
cl_lengths[PNG_CL_ORDER[i]] = v
}
if !PngBuildHuff(*cl_tree, cl_lengths[:], 19) { return false }
total := hlit + hdist
idx: s32 = 0
while idx < total {
sym := PngDecodeSym(input, *bit_pos, *cl_tree)
if sym < 0 { return false }
if sym < 16 {
lengths[idx] = sym
idx += 1
} else if sym == 16 {
if idx == 0 { return false }
rep := PngBits(input, *bit_pos, 2)
if rep < 0 || idx + rep + 3 > total { return false }
prev := lengths[idx - 1]
for r: 0..rep + 2 { lengths[idx] = prev; idx += 1 }
} else if sym == 17 {
rep := PngBits(input, *bit_pos, 3)
if rep < 0 || idx + rep + 3 > total { return false }
for r: 0..rep + 2 { lengths[idx] = 0; idx += 1 }
} else {
rep := PngBits(input, *bit_pos, 7)
if rep < 0 || idx + rep + 11 > total { return false }
for r: 0..rep + 10 { lengths[idx] = 0; idx += 1 }
}
}
if lengths[256] == 0 { return false }
if !PngBuildHuff(*lit_tree, lengths[0:hlit], hlit) { return false }
if !PngBuildHuff(*dist_tree, lengths[hlit:hlit + hdist], hdist) { return false }
}
while true {
sym := PngDecodeSym(input, *bit_pos, *lit_tree)
if sym < 0 { return false }
if sym < 256 {
if output.count >= expected { return false }
VecPush(<<output, cast(u8)sym)
} else if sym == 256 {
break
} else {
len_idx := sym - 257
if len_idx < 0 || len_idx >= 29 { return false }
extra := PngBits(input, *bit_pos, PNG_LEN_EXTRA[len_idx])
if extra < 0 { return false }
length := PNG_LEN_BASE[len_idx] + extra
dist_sym := PngDecodeSym(input, *bit_pos, *dist_tree)
if dist_sym < 0 || dist_sym >= 30 { return false }
dist_extra := PngBits(input, *bit_pos, PNG_DIST_EXTRA[dist_sym])
if dist_extra < 0 { return false }
dist := PNG_DIST_BASE[dist_sym] + dist_extra
if dist > output.count || output.count + length > expected { return false }
for i: 0..length - 1 {
b := (<<output)[output.count - dist]
VecPush(<<output, b)
}
}
}
}
if bfinal == 1 { break }
}
byte_pos := (bit_pos + 7) >> 3
if byte_pos + 4 != input.count || output.count != expected { return false }
s1: u32 = 1
s2: u32 = 0
for i: 0..output.count - 1 {
s1 = (s1 + cast(u32)(<<output)[i]) % 65521
s2 = (s2 + s1) % 65521
}
adler := (s2 << 16) | s1
return adler == Big32(input, byte_pos)
}
#scope_export
// The picture a whole PNG file's bytes hold; an invalid Image (see
// ImageValid) when they are not a PNG this reads.
@@ -95,6 +293,7 @@ ReadPNG :: (bytes: []u8) -> Image {
transparent := false
key: [3]s32
packed: Vec(u8)
defer VecFree(packed)
at: s64 = 8
ended := false
while at + 12 <= bytes.count {
@@ -172,7 +371,8 @@ ReadPNG :: (bytes: []u8) -> Image {
if width > 0 && height > 0 { expected += cast(s64)height * (RowBytes(header, width) + 1) }
}
data: Vec(u8)
if !ZlibDecompress(VecSlice(packed, 0, packed.count), *data, expected) || data.count != expected { return NewImage(0, 0) }
defer VecFree(data)
if !PngInflate(VecSlice(packed, 0, packed.count), *data, expected) || data.count != expected { return NewImage(0, 0) }
result := NewImage(header.width, header.height)
step := cast(s64)((header.channels * header.depth + 7) / 8)
offset: s64 = 0
@@ -193,13 +393,13 @@ ReadPNG :: (bytes: []u8) -> Image {
previous: s64 = -1
for y: 0..height - 1 {
row := offset + 1
if !Unfilter(*data, row, previous, size, step, data[offset]) { return NewImage(0, 0) }
if !Unfilter(*data, row, previous, size, step, data[offset]) { VecFree(result.pixels); return NewImage(0, 0) }
for x: 0..width - 1 {
to := (cast(s64)(start_y + y * step_y) * header.width + start_x + x * step_x) * 4
depth := header.depth
if header.color == 3 {
entry := Sample(*data, row, x, depth)
if entry >= palette_count { return NewImage(0, 0) }
if entry >= palette_count { VecFree(result.pixels); return NewImage(0, 0) }
for channel: 0..3 { result.pixels[to + channel] = palette[entry][channel] }
} else if header.color == 0 || header.color == 4 {
grey := Sample(*data, row, cast(s64)x * header.channels, depth)
@@ -346,6 +546,7 @@ WriteIndexedPNG :: (image: *IndexedImage, output: *Vec(u8), level: s32 = 9) -> b
// The picture in a PNG file; invalid when it cannot be read.
ReadPNGFile :: (path: string) -> Image {
bytes: Vec(u8)
defer VecFree(bytes)
if !ReadFileInto(path, *bytes) { return NewImage(0, 0) }
return ReadPNG(VecSlice(bytes, 0, bytes.count))
}
+70
View File
@@ -0,0 +1,70 @@
#import "base64"
using Vectors :: #import "vec"
CheckDecode :: (encoded: string, expected: string) -> bool {
ok := false
decoded := Base64Decode(encoded, *ok)
return ok && decoded == expected
}
// RFC 4648 test vectors ("", "f", "fo", "foo", "foob", "fooba", "foobar"),
// whitespace tolerance, URL-safe alphabet and rejection of malformed inputs.
#program_export
SelfTest :: () -> s32 {
empty_vec: Vec(u8)
if Base64Encode(VecSlice(empty_vec, 0, 0)) != "" { return 1 }
f1: [1]u8 = .[#char "f"]
f2: [2]u8 = .[#char "f", #char "o"]
f3: [3]u8 = .[#char "f", #char "o", #char "o"]
f4: [4]u8 = .[#char "f", #char "o", #char "o", #char "b"]
f5: [5]u8 = .[#char "f", #char "o", #char "o", #char "b", #char "a"]
f6: [6]u8 = .[#char "f", #char "o", #char "o", #char "b", #char "a", #char "r"]
if Base64Encode(f1[:]) != "Zg==" ||
Base64Encode(f2[:]) != "Zm8=" ||
Base64Encode(f3[:]) != "Zm9v" ||
Base64Encode(f4[:]) != "Zm9vYg==" ||
Base64Encode(f5[:]) != "Zm9vYmE=" ||
Base64Encode(f6[:]) != "Zm9vYmFy" {
return 2
}
if !CheckDecode("", "") ||
!CheckDecode("Zg==", "f") ||
!CheckDecode("Zm8=", "fo") ||
!CheckDecode("Zm9v", "foo") ||
!CheckDecode("Zm9vYg==", "foob") ||
!CheckDecode("Zm9vYmE=", "fooba") ||
!CheckDecode("Zm9v\r\n YmFy\t", "foobar") {
return 3
}
// URL-safe '-' (62) and '_' (63) decode to 0xfb, 0xff, 0xbf.
raw_url: [3]u8 = .[251, 255, 191]
if Base64Encode(raw_url[:]) != "+/+/" { return 4 }
url_out: Vec(u8)
defer VecFree(url_out)
if !Base64DecodeInto("-_-_", *url_out) || url_out.count != 3 ||
url_out[0] != 251 || url_out[1] != 255 || url_out[2] != 191 {
return 5
}
// Malformed inputs are rejected and leave output untouched.
before := url_out.count
bad_ok := true
bad_text := Base64Decode("Zm$v", *bad_ok)
if Base64DecodeInto("A", *url_out) ||
Base64DecodeInto("AB", *url_out) ||
Base64DecodeInto("ABC", *url_out) ||
Base64DecodeInto("====", *url_out) ||
Base64DecodeInto("A===", *url_out) ||
Base64DecodeInto("Zg==Zg==", *url_out) ||
Base64DecodeInto("Zm=v", *url_out) ||
Base64DecodeInto("Zm$v", *url_out) ||
bad_ok || bad_text != "" ||
url_out.count != before {
return 6
}
return 42
}
+29
View File
@@ -0,0 +1,29 @@
#!/bin/sh
# std/base64: RFC 4648 encoding, decoding, whitespace and malformed-input
# rejection in the portable engine (from source and saved IR) and natively.
set -eu
ziran=${1:?pass the ziran command}
repo=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
work=$(mktemp -d)
trap 'rm -rf "$work"' EXIT HUP INT TERM
unset DISPLAY WAYLAND_DISPLAY
cd "$repo"
"$ziran" check --root tests/spec --module-path std tests/spec/std_base64.zi
"$ziran" ir --root tests/spec --module-path std -o "$work/ir" tests/spec/std_base64.zi
"$ziran" bundle --root tests/spec --module-path std \
--entry std_base64:SelfTest -o "$work/source.zx" tests/spec/std_base64.zi
"$ziran" bundle --root "$work/ir" --module-path "$work/ir" \
--entry std_base64:SelfTest -o "$work/saved.zx" "$work/ir/std_base64.zir"
cmp "$work/source.zx" "$work/saved.zx"
test "$("$ziran" run "$work/source.zx")" = 42
"$ziran" build --target=c --no-main --root tests/spec --module-path std -o "$work/c" tests/spec/std_base64.zi
cat > "$work/main.c" <<'C'
#include <stdint.h>
int32_t SelfTest(void);
int main(void) { return SelfTest() == 42 ? 0 : 1; }
C
cc -std=c11 -O2 -iquote "$work/c" "$work/c"/*.c "$work/main.c" -o "$work/run"
"$work/run"
echo 'std-base64-test-ok: RFC 4648 vectors and malformed inputs match across portable bundle and native C'
+9
View File
@@ -122,6 +122,15 @@ main :: (argc: s32, argv: **u8) -> s32 {
large := NewImage(37, 21, 90, 160, 200, 255)
if !WriteJPEG(*large, *jpeg, 82) || jpeg.count < 200 { return 15 }
if jpeg[0] != 255 || jpeg[1] != 216 || jpeg[jpeg.count - 2] != 255 || jpeg[jpeg.count - 1] != 217 { return 16 }
decoded_jpeg := ReadJPEG(VecSlice(jpeg, 0, jpeg.count))
if !ImageValid(*decoded_jpeg) || decoded_jpeg.width != 37 || decoded_jpeg.height != 21 { return 18 }
mid := (10 * 37 + 18) * 4
dr := cast(s32)decoded_jpeg.pixels[mid] - 90
dg := cast(s32)decoded_jpeg.pixels[mid + 1] - 160
db := cast(s32)decoded_jpeg.pixels[mid + 2] - 200
if dr < -4 || dr > 4 || dg < -4 || dg > 4 || db < -4 || db > 4 || decoded_jpeg.pixels[mid + 3] != 255 { return 19 }
broken_jpeg := ReadJPEG(VecSlice(jpeg, 0, 10))
if ImageValid(*broken_jpeg) { return 20 }
return 0
}
ZI