1// PNG images, the bitmap glyphs of CBDT and sbix are kept as2// (decisions/F10.md, "Color emoji"): 8-bit images (gray, gray3// and alpha, RGB, RGBA, palettes of 1 to 8 bits; 16-bit samples keep4// their high byte; not interlaced) read into RGBA, the zlib stream5// (RFC 1950) inflated by std::deflate.67import std::string;8import std::vector;9import std::option;10import std::result;11import std::deflate;1213// An image, RGBA with straight alpha, row after row from the top.14exp type RgbaImage = struct {15 exp width: u32,16 exp height: u32,17 exp pixels: Vector<u8>,18};1920// How a PNG's pixels hold their color, by its header's code.21type ColorType = enum {22 Gray,23 Rgb,24 Palette,25 GrayAlpha,26 Rgba,27};2829fn ColorType::of(code: u8) -> Option<ColorType> => match (code) {30 0 ::Some(ColorType::Gray);31 2 ::Some(ColorType::Rgb);32 3 ::Some(ColorType::Palette);33 4 ::Some(ColorType::GrayAlpha);34 6 ::Some(ColorType::Rgba);35 else ::None;36};3738// The samples a pixel has.39fn channels(self kind: &ColorType) -> u32 => match (kind) {40 ::Gray, ::Palette 1;41 ::GrayAlpha 2;42 ::Rgb 3;43 ::Rgba 4;44};4546// The image the bytes hold, or why not.47exp fn read_png(bytes: &[u8]) -> Result<RgbaImage, String> {48 const signature: [u8 : 8] = [137, 80, 78, 71, 13, 10, 26, 10];49 if (bytes.length() < 8 || bytes[..8] != signature[..]) {50 return ::Err(String::from(&"not a PNG"));51 }52 var at: u64 = 8;53 var width: u32 = 0;54 var height: u32 = 0;55 var depth: u32 = 0;56 var code: u8 = 0; // the color type's57 var interlaced = false;58 var palette: &[u8] = &bytes[..0];59 var transparency: &[u8] = &bytes[..0];60 var data = Vector<u8>::empty();61 while (at + 8 <= bytes.length()) {62 const length = be32(&bytes, at) to u64;63 if (at + 12 + length > bytes.length()) {64 return ::Err(String::from(&"a chunk runs past the end"));65 }66 const body = &bytes[at + 8..at + 8 + length];67 match (bytes[at + 4..at + 8]) {68 "IHDR" {69 if (length >= 13) {70 width = be32(&body, 0);71 height = be32(&body, 4);72 depth = body[8] to u32;73 code = body[9];74 interlaced = body[12] != 0;75 }76 }77 "PLTE" {78 palette = &body;79 }80 "tRNS" {81 transparency = &body;82 }83 "IDAT" {84 data.append(&body);85 }86 "IEND" {87 break;88 }89 }90 at += 12 + length;91 }92 if (width == 0 || height == 0 || width > 16384 || height > 16384) {93 return ::Err(String::from(&"no image size"));94 }95 if (interlaced) {96 return ::Err(String::from(&"interlaced PNGs are not read"));97 }98 const kind = if (ColorType::of(code) is ::Some |k|) k else {99 return ::Err(String::from(&"an unknown kind of PNG"));100 };101 // bit depths below 8 only for gray and palettes102 const small = (depth == 1 || depth == 2 || depth == 4) && (kind is ::Gray || kind is ::Palette);103 if ((depth != 8 && depth != 16 && !small) || (kind is ::Palette && depth > 8)) {104 return ::Err(String::from(&"an unknown kind of PNG"));105 }106 const bits = kind.channels() * depth;107 const row = ((width to u64 * bits to u64) + 7) / 8;108 const size = height to u64 * (row + 1);109 // grown by `inflate` past the first 4 MB, so a header alone allocates little110 var raw = Vector<u8>::filled(0, if (size > 1 << 22) 1 << 22 else size);111 const inflated = if (112 data.length() >= 2 && inflate(&data.view()[2..], &var raw, size) is ::Ok |n|113 ) n else 0;114 if (inflated != size) {115 return ::Err(String::from(&"its compressed data is damaged"));116 }117 if (!unfilter(&var raw.items(), height to u64, row, if (bits >= 8) bits to u64 / 8 else 1)) {118 return ::Err(String::from(&"a row has an unknown filter"));119 }120 var pixels = Vector<u8>::filled(255, width to u64 * height to u64 * 4);121 const out = &var pixels.items();122 const w = width to u64;123 for ([..height to u64]) |y| {124 const line = &raw.view()[y * (row + 1) + 1..(y + 1) * (row + 1)];125 const into = &var out[y * w * 4..(y + 1) * w * 4];126 if (depth == 8) {127 match (kind) {128 ::Rgba {129 into[..] = line[..];130 }131 ::Rgb {132 for ([..w]) |x| {133 into[x * 4..x * 4 + 3] = line[x * 3..x * 3 + 3];134 }135 }136 ::Gray {137 for (line, [..w]) |v, x| {138 into[x * 4] = v;139 into[x * 4 + 1] = v;140 into[x * 4 + 2] = v;141 }142 }143 ::GrayAlpha {144 for ([..w]) |x| {145 const v = line[x * 2];146 into[x * 4] = v;147 into[x * 4 + 1] = v;148 into[x * 4 + 2] = v;149 into[x * 4 + 3] = line[x * 2 + 1];150 }151 }152 ::Palette {153 for (line, [..w]) |index, x| {154 look_up(&var into[x * 4..x * 4 + 4], index to u64, &palette, &transparency);155 }156 }157 }158 } else if (kind is ::Palette) {159 for ([..w]) |x| {160 look_up(161 &var into[x * 4..x * 4 + 4],162 sample(&line, x, depth) to u64,163 &palette,164 &transparency165 );166 }167 } else if (depth < 8) {168 for ([..w]) |x| {169 const v = (sample(&line, x, depth) * (255 / ((1 << depth) - 1))) to u8;170 into[x * 4] = v;171 into[x * 4 + 1] = v;172 into[x * 4 + 2] = v;173 }174 } else {175 // 16 bits a sample, the high byte first176 const channels = kind.channels() to u64;177 for ([..w]) |x| {178 const s = &line[x * channels * 2..(x + 1) * channels * 2];179 match (kind) {180 ::Gray, ::GrayAlpha {181 into[x * 4] = s[0];182 into[x * 4 + 1] = s[0];183 into[x * 4 + 2] = s[0];184 if (kind is ::GrayAlpha) {185 into[x * 4 + 3] = s[2];186 }187 }188 else {189 into[x * 4] = s[0];190 into[x * 4 + 1] = s[2];191 into[x * 4 + 2] = s[4];192 if (kind is ::Rgba) {193 into[x * 4 + 3] = s[6];194 }195 }196 }197 }198 }199 }200 return ::Ok(RgbaImage { .width = width, .height = height, .pixels = move pixels });201}202203// A palette's color, its alpha from `tRNS`; black past the palette.204fn look_up(into: &var [u8], index: u64, palette: &[u8], transparency: &[u8]) {205 for ([..3 to u64]) |c| {206 into[c] = if (index * 3 + 2 < palette.length()) palette[index * 3 + c] else 0;207 }208 into[3] = if (index < transparency.length()) transparency[index] else 255;209}210211// Undoes each row's filter in place: `rows` rows of `row` bytes, each212// after its filter's byte, `step` bytes a pixel back; false for an213// unknown filter.214fn unfilter(raw: &var [u8], rows: u64, row: u64, step: u64) -> bool {215 const stride = row + 1;216 for ([..rows]) |y| {217 const line = y * stride + 1;218 const up = if (y > 0) line - stride else 0; // the row above219 match (raw[line - 1]) {220 0 {}221 1 {222 for ([step..row]) |x| {223 raw[line + x] = raw[line + x] +% raw[line + x - step];224 }225 }226 2 {227 if (y > 0) {228 for ([..row]) |x| {229 raw[line + x] = raw[line + x] +% raw[up + x];230 }231 }232 }233 3 {234 for ([..row]) |x| {235 const a = if (x >= step) raw[line + x - step] to u32 else 0;236 const b = if (y > 0) raw[up + x] to u32 else 0;237 raw[line + x] = raw[line + x] +% ((a + b) / 2) to u8;238 }239 }240 4 {241 for ([..row]) |x| {242 const a = if (x >= step) raw[line + x - step] to i32 else 0;243 const b = if (y > 0) raw[up + x] to i32 else 0;244 const c = if (x >= step && y > 0) raw[up + x - step] to i32 else 0;245 raw[line + x] = raw[line + x] +% paeth(a, b, c) to u8;246 }247 }248 else {249 return false;250 }251 }252 }253 return true;254}255256// The x-th sample of `depth` bits below 8, from the high bits first.257fn sample(line: &[u8], x: u64, depth: u32) -> u32 {258 const bit = x * depth to u64;259 const byte = line[bit / 8] to u32;260 const shift = 8 - depth - (bit % 8) to u32;261 return (byte >> shift) & ((1 << depth) - 1);262}263264fn paeth(a: i32, b: i32, c: i32) -> i32 {265 const p = a + b - c;266 const pa = abs(p - a);267 const pb = abs(p - b);268 const pc = abs(p - c);269 if (pa <= pb && pa <= pc) {270 return a;271 }272 return if (pb <= pc) b else c;273}274275fn abs(v: i32) -> i32 => if (v < 0) -v else v;276277fn be32(bytes: &[u8], at: u64) -> u32 {278 return bytes[at] to u32 << 24 | bytes[279 at + 1280 ] to u32 << 16 | bytes[at + 2] to u32 << 8 | bytes[at + 3] to u32;281}