///| Compressed PNG encoding (screenshots). /// /// `encode_png` stores the pixels uncompressed, which is fine for test frames but makes a /// 1080p screenshot an 8 MB file. `encode_png_compressed` picks a PNG filter per row (None, /// Sub or Up, whichever leaves the smallest values) and deflates the result with LZ77 and the /// fixed Huffman codes: desktop pictures, with their flat areas and repeated rows, shrink by /// one or two orders of magnitude, and the encoder stays small and dependency-free. ///| Bits written least-significant first, as deflate wants them. priv struct BitWriter { out : Array[Byte] mut acc : UInt mut n : Int } ///| fn BitWriter::new(cap : Int) -> BitWriter { { out: Array(capacity=cap), acc: 0U, n: 0 } } ///| Append the low `count` bits of `v`, least significant first. fn BitWriter::bits(self : BitWriter, v : UInt, count : Int) -> Unit { self.acc = self.acc | (v << self.n) self.n = self.n + count while self.n >= 8 { self.out.push((self.acc & 0xFFU).to_byte()) self.acc = self.acc >> 8 self.n = self.n - 8 } } ///| Append a Huffman code of `len` bits (codes are sent most-significant bit first). fn BitWriter::code(self : BitWriter, code : UInt, len : Int) -> Unit { let mut rev = 0U for i = 0; i < len; i = i + 1 { rev = (rev << 1) | ((code >> i) & 1U) } self.bits(rev, len) } ///| fn BitWriter::flush(self : BitWriter) -> Unit { if self.n > 0 { self.out.push((self.acc & 0xFFU).to_byte()) self.acc = 0U self.n = 0 } } ///| A literal or length symbol (0..285) with the fixed Huffman code. fn BitWriter::lit(self : BitWriter, sym : Int) -> Unit { if sym < 144 { self.code((0x30 + sym).reinterpret_as_uint(), 8) } else if sym < 256 { self.code((0x190 + sym - 144).reinterpret_as_uint(), 9) } else if sym < 280 { self.code((sym - 256).reinterpret_as_uint(), 7) } else { self.code((0xC0 + sym - 280).reinterpret_as_uint(), 8) } } // The length and distance tables (len_base, len_extra, dist_base, dist_extra) are the // decoder's, in png.mbt. ///| Send a back-reference of `len` (3..258) bytes `dist` (1..32768) back. fn BitWriter::match_(self : BitWriter, len : Int, dist : Int) -> Unit { let mut li = 28 while len_base[li] > len { li = li - 1 } self.lit(257 + li) if len_extra[li] > 0 { self.bits((len - len_base[li]).reinterpret_as_uint(), len_extra[li]) } let mut di = 29 while dist_base[di] > dist { di = di - 1 } self.code(di.reinterpret_as_uint(), 5) if dist_extra[di] > 0 { self.bits((dist - dist_base[di]).reinterpret_as_uint(), dist_extra[di]) } } ///| A zlib stream (one fixed-Huffman deflate block) of `data`. pub fn zlib_compress(data : FixedArray[Byte]) -> Array[Byte] { let n = data.length() let w = BitWriter::new(n / 8 + 64) w.out.push(b'\x78') w.out.push(b'\x01') w.bits(1U, 1) // BFINAL w.bits(1U, 2) // BTYPE = fixed Huffman let hash_bits = 15 let hsize = 1 << hash_bits // Most recent and previous positions with the same 3-byte hash (a short chain). let head : FixedArray[Int] = FixedArray::make(hsize, -1) let prev : FixedArray[Int] = FixedArray::make(32768, -1) let window = 32768 let max_chain = 8 let hash = fn(i : Int) -> Int { let v = (data[i].to_int() << 16) | (data[i + 1].to_int() << 8) | data[i + 2].to_int() ((v.reinterpret_as_uint() * 2654435761U) >> (32 - hash_bits)).reinterpret_as_int() & (hsize - 1) } let insert = fn(i : Int) { if i + 2 < n { let h = hash(i) prev[i & (window - 1)] = head[h] head[h] = i } } let mut i = 0 while i < n { let mut best_len = 0 let mut best_dist = 0 if i + 2 < n { let mut cand = head[hash(i)] let mut chain = 0 let limit = if n - i < 258 { n - i } else { 258 } while cand >= 0 && i - cand <= window && chain < max_chain { if data[cand + best_len] == data[i + best_len] || best_len == 0 { let mut l = 0 while l < limit && data[cand + l] == data[i + l] { l = l + 1 } if l > best_len { best_len = l best_dist = i - cand if l == limit { break } } } let nxt = prev[cand & (window - 1)] if nxt >= cand { break } cand = nxt chain = chain + 1 } } if best_len >= 3 { w.match_(best_len, best_dist) // Long runs are typical (flat colours): index only their first bytes, it is plenty. let stop = i + best_len let index_to = if best_len > 32 { i + 32 } else { stop } while i < index_to { insert(i) i = i + 1 } i = stop } else { w.lit(data[i].to_int()) insert(i) i = i + 1 } } w.lit(256) // end of block w.flush() // Adler-32 of the uncompressed data. let mut s1 = 1U let mut s2 = 0U let mut k = 0 while k < n { let end = if n - k > 5552 { k + 5552 } else { n } while k < end { s1 = s1 + data[k].to_uint() s2 = s2 + s1 k = k + 1 } s1 = s1 % 65521U s2 = s2 % 65521U } push_u32_be(w.out, (s2 << 16) | s1) w.out } ///| Encode `p` as an RGBA PNG with per-row filtering and deflate compression. pub fn encode_png_compressed(p : Pixmap) -> Bytes { let out : Array[Byte] = [ b'\x89', b'\x50', b'\x4e', b'\x47', b'\x0d', b'\x0a', b'\x1a', b'\x0a', ] let ihdr : Array[Byte] = [] push_u32_be(ihdr, p.width.reinterpret_as_uint()) push_u32_be(ihdr, p.height.reinterpret_as_uint()) ihdr.push(b'\x08') // bit depth 8 ihdr.push(b'\x06') // RGBA ihdr.push(b'\x00') ihdr.push(b'\x00') ihdr.push(b'\x00') push_png_chunk(out, "IHDR", ihdr) let stride = p.width * 4 let row_bytes = 1 + stride let raw : FixedArray[Byte] = FixedArray::make(row_bytes * p.height, b'\x00') for y = 0; y < p.height; y = y + 1 { let src = y * stride let dst = y * row_bytes // Score each filter by the sum of its outputs taken as signed bytes; keep the smallest. let mut s_none = 0 let mut s_sub = 0 let mut s_up = 0 for i = 0; i < stride; i = i + 1 { let v = p.data[src + i].to_int() let left = if i >= 4 { p.data[src + i - 4].to_int() } else { 0 } let up = if y > 0 { p.data[src - stride + i].to_int() } else { 0 } s_none = s_none + signed_mag(v) s_sub = s_sub + signed_mag((v - left) & 0xFF) s_up = s_up + signed_mag((v - up) & 0xFF) } let filter = if s_up <= s_sub && s_up <= s_none && y > 0 { 2 } else if s_sub <= s_none { 1 } else { 0 } raw[dst] = filter.to_byte() for i = 0; i < stride; i = i + 1 { let v = p.data[src + i].to_int() let f = match filter { 1 => (v - (if i >= 4 { p.data[src + i - 4].to_int() } else { 0 })) & 0xFF 2 => (v - p.data[src - stride + i].to_int()) & 0xFF _ => v } raw[dst + 1 + i] = f.to_byte() } } push_png_chunk(out, "IDAT", zlib_compress(raw)) push_png_chunk(out, "IEND", []) Bytes::from_array(out) } ///| |b| for a byte read as a signed value (the usual PNG filter heuristic). fn signed_mag(b : Int) -> Int { if b < 128 { b } else { 256 - b } }