diff --git a/services/gam/Cargo.toml b/services/gam/Cargo.toml index c74c4aa6c..48b5f7bd9 100644 --- a/services/gam/Cargo.toml +++ b/services/gam/Cargo.toml @@ -33,6 +33,8 @@ locales = {path = "../../locales"} tts-frontend = {path="../tts"} qrcode = { version = "0.12", default-features = false } +miniz_oxide = "0.4.4" +# pix = "0.13" [target.'cfg(not(any(windows,unix)))'.dependencies] utralib = {path = "../../utralib"} diff --git a/services/gam/src/bitmap.rs b/services/gam/src/bitmap.rs index e235cf170..743b5a98f 100644 --- a/services/gam/src/bitmap.rs +++ b/services/gam/src/bitmap.rs @@ -2,8 +2,12 @@ use core::cmp::{max, min}; use graphics_server::api::*; use graphics_server::PixelColor; use std::convert::TryInto; +use std::io::Read; use std::ops::Deref; +mod decode_png; +pub use decode_png::*; + /* * The basic idea is to define a Bitmap as a variable mosaic of Sized Tiles. * @@ -53,22 +57,65 @@ impl Bitmap { Self { width: size.x as usize + 1, bound: Rectangle::new(Point::new(0, 0), size), - tile_bits, //: (size.x as usize + 1) * (size.y as usize + 1), + tile_bits, mosaic, } } - pub fn new_resize(image: &Img, width: usize) -> Self { + pub fn from_img(img: &Img, fit: Option) -> Self { + Bitmap::from_iter( + img.iter().cloned(), + img.px_type, + Point::new( + img.width().try_into().unwrap(), + img.height().try_into().unwrap(), + ), + fit, + ) + } + + pub fn from_png(png: &mut DecodePng, fit: Option) -> Self { + // Png Colortypes: 0=Grey, 2=Rgb, 3=Palette, 4=GreyAlpha, 6=Rgba. + let px_type = match (png.color_type(), png.bit_depth()) { + (0, 1 | 2 | 4 | 8) => PixelType::U8, + (0, 16) => PixelType::U16, + (2, 8) => PixelType::U8x3, + (2, 16) => PixelType::U16x3, + (3, 1 | 2 | 4 | 8) => PixelType::U8, + (4, 8) => PixelType::U8x2, + (4, 16) => PixelType::U16x2, + (6, 8) => PixelType::U8x4, + (6, 16) => PixelType::U16x4, + (_, _) => PixelType::U8, // Error + }; + let px_size = Point::new( + png.width().try_into().unwrap(), + png.height().try_into().unwrap(), + ); + Bitmap::from_iter(png, px_type, px_size, fit) + } + + pub fn from_iter>( + bytes: I, + px_type: PixelType, + px_size: Point, + fit: Option, + ) -> Self { let burkes = BURKES.to_vec(); - let words = image - .iter() - .to_grey(image.px_type) - .shrink(image.width, width) - .dither(&burkes, width); + let from_width: usize = px_size.x.try_into().unwrap(); + let (rotate, to_width) = match fit { + Some(fit) => Self::fit(px_size, fit), + None => (false, from_width), + }; + let words = bytes + .to_grey(px_type) + .shrink(from_width, to_width) + .dither(&burkes, to_width); let mut mosaic: Vec = Vec::new(); - let single_line = Point::new((width - 1).try_into().unwrap(), 0); + let to_width:i16 = to_width.try_into().unwrap(); + let single_line = Point::new(to_width - 1, 0); let mut bound = Rectangle::new(Point::new(0, 0), single_line); let mut tile = Tile::new(bound); let mut blank_tile = true; @@ -77,34 +124,58 @@ impl Bitmap { tile.set_word(Point::new(x, y), word); blank_tile = false; x += BITS_PER_WORD as i16; - if x >= width.try_into().unwrap() { + if x >= to_width { (x, y) = (0, y + 1); } if y > tile.max_bound().br.y { mosaic.push(tile); - bound = Rectangle::new( - Point::new(x, y), - Point::new((width - 1).try_into().unwrap(), y), - ); + if y > px_size.y { break; } + bound = Rectangle::new(Point::new(x, y), Point::new(to_width - 1, y)); tile = Tile::new(bound); blank_tile = true; } + } if !blank_tile { - bound.br = Point::new((width - 1).try_into().unwrap(), y - 1); + bound.br = Point::new(to_width - 1, y - 1); tile.crop(bound); mosaic.push(tile); } bound.tl = Point::new(0, 0); let max = tile.max_bound(); - let tile_bits = width as i16 * (max.br.y - max.tl.y + 1); + let tile_bits = to_width * (max.br.y - max.tl.y + 1); - Self { - width, + let mut bm = Self { + width: to_width.try_into().unwrap(), bound, tile_bits: tile_bits.try_into().unwrap(), mosaic, + }; + + if rotate { + bm.rotate90(); + } + bm + } + + fn fit(from: Point, into: Point) -> (bool, usize) { + let (from_x, from_y) = (from.x as f32, from.y as f32); + let (into_x, into_y) = (into.x as f32, into.y as f32); + let portrait_scale = (into_x / from_x).min(into_y / from_y); + let landscape_scale = (into_x / from_y).min(into_y / from_x); + if portrait_scale >= 1.0 { + log::info!("show image as is"); + (false, from.x.try_into().unwrap()) + } else if landscape_scale >= 1.0 { + log::info!("rotate image"); + (true, from.x.try_into().unwrap()) + } else if portrait_scale >= landscape_scale { + log::info!("scale image {}", portrait_scale); + (false, (portrait_scale * from_x) as usize) + } else { + log::info!("scale image {} and rotate", landscape_scale); + (true, (landscape_scale * from_x) as usize) } } @@ -279,7 +350,7 @@ impl From<[Option; 6]> for Bitmap { impl<'a> From<&Img> for Bitmap { fn from(image: &Img) -> Self { - Bitmap::new_resize(image, image.width) + Bitmap::from_img(image, None) } } @@ -288,8 +359,13 @@ impl<'a> From<&Img> for Bitmap { #[derive(Debug, Clone, Copy)] pub enum PixelType { U8, + U8x2, U8x3, U8x4, + U16, + U16x2, + U16x3, + U16x4, } /* @@ -343,13 +419,13 @@ pub struct GreyScale { px_type: PixelType, } -impl<'a, I: Iterator> GreyScale { +impl> GreyScale { fn new(iter: I, px_type: PixelType) -> GreyScale { Self { iter, px_type } } } -impl<'a, I: Iterator> Iterator for GreyScale { +impl> Iterator for GreyScale { type Item = u8; fn next(&mut self) -> Option { @@ -360,7 +436,7 @@ impl<'a, I: Iterator> Iterator for GreyScale { const BLACK: u32 = R + G + B; match self.px_type { PixelType::U8 => match self.iter.next() { - Some(gr) => Some(*gr), + Some(gr) => Some(gr), None => None, }, PixelType::U8x3 => { @@ -368,9 +444,9 @@ impl<'a, I: Iterator> Iterator for GreyScale { let g = self.iter.next(); let b = self.iter.next(); if r.is_some() && g.is_some() && b.is_some() { - let grey_r = R * *r.unwrap() as u32; - let grey_g = G * *g.unwrap() as u32; - let grey_b = B * *b.unwrap() as u32; + let grey_r = R * r.unwrap() as u32; + let grey_g = G * g.unwrap() as u32; + let grey_b = B * b.unwrap() as u32; let grey: u8 = ((grey_r + grey_g + grey_b) / BLACK).try_into().unwrap(); Some(grey) } else { @@ -378,21 +454,21 @@ impl<'a, I: Iterator> Iterator for GreyScale { } } _ => { - log::warn!("unsupported PixelType"); + log::warn!("unsupported PixelType {:?}", self.px_type); None } } } } -pub trait GreyScaleIterator<'a>: Iterator + Sized { +pub trait GreyScaleIterator: Iterator + Sized { /// converts pixels of PixelType to u8 greyscale fn to_grey(self, px_type: PixelType) -> GreyScale { GreyScale::new(self, px_type) } } -impl<'a, I: Iterator> GreyScaleIterator<'a> for I {} +impl> GreyScaleIterator for I {} // ********************************************************************** @@ -524,7 +600,6 @@ pub trait ShrinkIterator: Iterator + Sized { impl> ShrinkIterator for I {} - // ********************************************************************** /* diff --git a/services/gam/src/bitmap/decode_png.rs b/services/gam/src/bitmap/decode_png.rs new file mode 100644 index 000000000..3f13f37bd --- /dev/null +++ b/services/gam/src/bitmap/decode_png.rs @@ -0,0 +1,514 @@ +/* + * This incomplete PNG decoder presents as an Iterator reading u8 bytes directly from a Reader. + * + * Aproaching a png decoder as an Iterator requires significantly less Heap than + * the traditional batch aproach. + * + * On Precursor, this enables PNG bytes to be intercepted at the network interface + * and processed into the much smaller gam::Bitmap format without ever having to + * store the original PNG file. + * + * + * The png image format includes a signature (8 bytes) followed by chunks + * - Each chunk includes the chunk begins with its length (4 bytes) and name (4 bytes) and ends + * with a checksum (4 bytes) + * - The IHDR chunk must be first and contains width, height, bit_depth, color_type, + * compression_method, filter_method, and an interlace flag. + * - The Palette chunck is currently unsupported + * - Consecutive IDAT chunks hold the image data in bytes. + * - The IEND chunk must be last. + * - Other chunk types are ignored in this decoder. + * - The bytes in the IDAT chunks must be concatenated and uncompressed (zlib) + * - The uncompressed bytes are arranged in scanlines, left-right, top-bottom. + * - The first byte in each scan-line representes a filter_type which is used to unfilter + * the remaining bytes in the scan-line. (filters is used to improve compression) + * - The uncompressed, unfiltered bytes now represent pixels in the specified color_type + * (eg RGB, RGBa etc) + * + * This development is gratefully based on PNG Pong - Copyright © 2019-2021 Jeron Aldaron Lau + * + * author: nworbnhoj + */ + +use std::convert::TryInto; +use std::io::{Error, ErrorKind::InvalidData, Read, Result}; + +use miniz_oxide::{inflate::stream::InflateState, DataFormat, MZFlush, MZStatus}; +//use pix::rgb::SRgb8; + +mod consts; +use consts::*; +mod color_type; +use color_type::*; + +// These may be adjusted to tune the heap requirement. +// Probably better for PNG_BUFFER = 2-3x IDAT_BUFFER +// TODO benchmarking speed vs heap +const IDAT_BUFFER_LENGTH: usize = 256; +const PNG_BUFFER_LENGTH: usize = 1024; + +pub struct DecodePng { + reader: R, + // IHDR chunk fields + width: u32, + height: u32, + bit_depth: u8, + color_type: u8, + compression_method: u8, + filter_method: u8, + interlace: bool, + // PLTE chunk fields + palette: Option>, + //palette: Option>, + chksum: u32, + // fields to manage the filter + bytes_per_pixel: usize, + bytes_per_line: usize, + byte_index: usize, + filter_type: u8, + prior_line: Vec, + line_index: usize, + prior_px: Vec, + // fields to buffer bytes read from the idat chunk + idat_remaining: u32, + idat_buffer: Vec, + // state of the miniz oxide inflation + inflate_state: InflateState, + // fields to buffer inflated bytes waiting to be unfiltered + inflated: [u8; PNG_BUFFER_LENGTH], + inflated_length: usize, + inflated_index: usize, +} + +impl Iterator for DecodePng { + type Item = u8; + + fn next(&mut self) -> Option { + self.unfilter() + } +} + +impl DecodePng { + pub fn new(reader: R) -> Result> { + let mut png = Self { + reader: reader, + width: 0, + height: 0, + bit_depth: 0, + color_type: 0, + compression_method: 0, + filter_method: 0, + interlace: false, + palette: None, + chksum: consts::CRC32_INIT, + bytes_per_pixel: 0, + bytes_per_line: 0, + byte_index: 0, + filter_type: 0, + prior_line: vec![0u8, 0], + line_index: 0, + prior_px: vec![0u8, 0], + idat_remaining: 0, + idat_buffer: Vec::with_capacity(IDAT_BUFFER_LENGTH), + inflate_state: InflateState::new(DataFormat::Zlib), + //inflate_state: InflateState::new_boxed(DataFormat::Zlib), + inflated: [0u8; PNG_BUFFER_LENGTH], + inflated_length: 0, + inflated_index: PNG_BUFFER_LENGTH, + }; + png.check_signature()?; + png.parse_header()?; + if png.color_type == 3 { + png.parse_palette()?; + } + png.idat_remaining = png.next_idat(false)?; + png.fill_idat_buffer(IDAT_BUFFER_LENGTH)?; + png.set_filter_type(); + log::info!( + "DecodePng ready: size({},{}) bit-depth={} color_type={} bytes_per_line={}", + png.width, + png.height, + png.bit_depth, + png.color_type, + png.bytes_per_line, + ); + Ok(png) + } + + pub fn width(&self) -> u32 { + self.width + } + pub fn height(&self) -> u32 { + self.height + } + pub fn color_type(&self) -> u8 { + self.color_type + } + pub fn bit_depth(&self) -> u8 { + self.bit_depth + } + + /// Prepare a chunk for reading, capturing name & length, and resetting checksum. + pub(crate) fn prepare_chunk(&mut self) -> Result<([u8; 4], u32)> { + let length = match self.u8() { + Ok(first) => u32::from_be_bytes([first, self.u8()?, self.u8()?, self.u8()?]), + Err(err) => { + log::warn!("failed to decode png chunk: {:?}", err); + 0 + } + }; + self.chksum = consts::CRC32_INIT; + let name = [self.u8()?, self.u8()?, self.u8()?, self.u8()?]; + if length > consts::MAX_CHUNK_SIZE as u32 { + log::warn!("failed to decode png chunk: oversize"); + } + log::trace!( + "found png chunk name={:?} with length={}", + String::from_utf8_lossy(&name), + length + ); + Ok((name, length)) + } + + fn check_signature(&mut self) -> Result<()> { + // Read first 8 bytes (PNG Signature) + let mut buf = [0u8; 8]; + self.reader.read_exact(&mut buf)?; + match buf { + PNG_SIGNATURE => { + log::trace!("png signature matched"); + Ok(()) + } + _ => Err(Error::new(InvalidData, "invalid png signature")), + } + } + + fn parse_header(&mut self) -> Result<()> { + let color_type: ColorType; + match self.prepare_chunk()? { + (IMAGE_HEADER, _) => { + log::trace!("located png header chunk"); + self.width = self.u32()?; + self.height = self.u32()?; + self.bit_depth = self.u8()?; + self.color_type = self.u8()?; + self.compression_method = self.u8()?; + self.filter_method = self.u8()?; + self.interlace = match self.u8()? { + 0 => false, + 1 => true, + _ => return Err(Error::new(InvalidData, "invalid interlace")), + }; + self.check_crc()?; + + color_type = match self.color_type { + 0 => ColorType::Grey, + 2 => ColorType::Rgb, + 3 => ColorType::Palette, + 4 => ColorType::GreyAlpha, + 6 => ColorType::Rgba, + _ => return Err(Error::new(InvalidData, "invalid color-type")), + }; + self.bytes_per_pixel = (color_type.bpp(self.bit_depth) / 8).try_into().unwrap(); + self.bytes_per_line = 1 + self.bytes_per_pixel * self.width as usize; + self.prior_line = vec![0u8; self.bytes_per_line]; + self.prior_px = vec![0u8; self.bytes_per_pixel]; + } + (_, _) => return Err(Error::new(InvalidData, "header chunk not first")), + }; + + if self.width == 0 || self.height == 0 { + return Err(Error::new(InvalidData, "invalid image dimensions")); + } else if self.bit_depth == 0 || self.bit_depth > 16 { + return Err(Error::new(InvalidData, "invalid bit depth")); + } else if self.compression_method != 0 { + return Err(Error::new(InvalidData, "invalid compression method")); + } else if self.filter_method != 0 { + return Err(Error::new(InvalidData, "invalid filter method")); + } else if self.interlace { + return Err(Error::new(InvalidData, "interlace is not supported")); + } else if self.bytes_per_pixel < 1 { + return Err(Error::new( + InvalidData, + "less than 8 bits per pixel is not supported", + )); + } else if self.color_type == 3 { + return Err(Error::new( + InvalidData, + "color_type = 3 palette is not supported", + )); + } else { + color_type.check_png_color_validity(self.bit_depth)?; + }; + Ok(()) + } + + fn parse_palette(&mut self) -> Result<()> { + while self.palette.is_none() { + self.palette = match self.prepare_chunk()? { + (PALETTE, length) => { + log::trace!("located png palette chunk"); + let mut palette = Vec::new(); + for _ in 0..(length / 3) { + let red = self.u8()?; + let green = self.u8()?; + let blue = self.u8()?; + palette.push((red, green, blue)); + //palette.push(SRgb8::new(red, green, blue)); + } + self.check_crc()?; + Some(palette) + } + (IMAGE_DATA, _) => { + return Err(Error::new(InvalidData, "data chunk before palette")) + } + (IMAGE_END, _) => return Err(Error::new(InvalidData, "end chunk before palette")), + (_, length) => { + self.ignore_chunk(length)?; + None + } + }; + } + Ok(()) + } + + fn next_idat(&mut self, consecutive: bool) -> Result { + loop { + match self.prepare_chunk() { + Ok((IMAGE_DATA, length)) => { + log::trace!("located png idat chunk"); + return Ok(length); + } + Ok((IMAGE_END, _)) => { + log::trace!("located png end chunk"); + return Ok(0); + } + Ok((_, length)) => { + if consecutive { + return Err(Error::new(InvalidData, "non-consecutive idat chunk")); + } else { + self.ignore_chunk(length)?; + } + } + Err(err) => return Err(err), + }; + } + } + + /// Read and ignore the entire chunk + checksum. + pub(crate) fn ignore_chunk(&mut self, length: u32) -> Result<()> { + let len = length + 4; // add 4 x u8 for checksum + let mut byte = [0; 1]; + for _ in 0..len { + self.reader.read_exact(&mut byte)?; + } + Ok(()) + } + + /// Get a u8 out of the reader. + pub(crate) fn u8(&mut self) -> Result { + let mut byte = [0; 1]; + self.reader.read_exact(&mut byte).map_err(Error::from)?; + let index: usize = (self.chksum as u8 ^ byte[0]).into(); + self.chksum = consts::CRC32_LOOKUP[index] ^ (self.chksum >> 8); + Ok(byte[0]) + } + + /// Get a u32 out of the reader + pub(crate) fn u32(&mut self) -> Result { + Ok(u32::from_be_bytes([ + self.u8()?, + self.u8()?, + self.u8()?, + self.u8()?, + ])) + } + + /// Check if the CRC matches calculated CRC. + pub(crate) fn check_crc(&mut self) -> Result<()> { + let mut crc32 = [0; 4]; + self.reader.read_exact(&mut crc32)?; + if u32::from_be_bytes(crc32) != (self.chksum ^ consts::CRC32_INIT) { + return Err(Error::new(InvalidData, "checksum failed")); + } + Ok(()) + } + + // Reads u8 bytes from the png idat chunk into the idat_buffer + // If the idat chunk is exhausted then check the checksum and + // move to the next idat chunk and continue. + fn fill_idat_buffer(&mut self, length: usize) -> Result { + let mut read = 0; + for _ in 0..length { + if self.idat_remaining <= 0 { + log::trace!("seeking another png idat"); + self.idat_remaining = match self.next_idat(true) { + Ok(length) => length, + Err(err) => { + log::warn!("png idat find error: {:?}", err); + 0 + } + }; + if self.idat_remaining <= 0 { + break; + } + } + match self.u8() { + Ok(byte) => { + read += 1; + self.idat_buffer.push(byte); + self.idat_remaining -= 1; + if self.idat_remaining <= 0 { + self.check_crc()?; + } + } + Err(err) => { + log::warn!("idat read error: {:?}", err); + break; + } + }; + } + Ok(read) + } + + // Inflates u8 bytes from the idat_buffer into inflated. + // Attempts to refill the idat_buffer ready for the next call. + // Note: this fn() updates buffer, inflated_length & idat_buffer + fn inflate(&mut self) -> usize { + while self.inflated_length <= 0 && self.idat_buffer.len() > 0 { + let miniz = miniz_oxide::inflate::stream::inflate( + &mut self.inflate_state, + self.idat_buffer.as_slice(), + &mut self.inflated, + MZFlush::None, + ); + log::trace!("miniz inflate {:?}", miniz); + self.inflated_length = miniz.bytes_written; + self.idat_buffer.drain(..miniz.bytes_consumed); + match miniz.status { + Ok(MZStatus::Ok) => { + match self.fill_idat_buffer(IDAT_BUFFER_LENGTH - self.idat_buffer.len()) { + Ok(_) => (), + Err(err) => log::warn!("png idat buffer error {:?}", err), + } + } + Ok(MZStatus::StreamEnd) => log::trace!("miniz inflate found StreamEnd"), + Ok(MZStatus::NeedDict) => log::trace!("miniz inflate found NeedDict"), + Err(err) => log::warn!("miniz inflate error: {:?}", err), + } + log::trace!("idat buffer length = {}", self.idat_buffer.len()); + } + self.inflated_length + } + + // Checks that the buffer has bytes available and attempts to refill if not. + // Note: this fn() updates inflated_index, buffer_len & buffer + fn inflated_length(&mut self) -> usize { + if self.inflated_index >= self.inflated_length { + self.inflated_index = 0; + self.inflated_length = 0; + self.inflate(); + } + self.inflated_length + } + + // Takes the next byte in the buffer as the filter type + // Call this fn() at the beginning of each png scan line + // Note: this fn() updates inflated_index, byte_index & filter_type + fn set_filter_type(&mut self) { + self.filter_type = match self.inflated_length() { + 0 => 0, + _ => { + let filter_type = self.inflated[self.inflated_index]; + self.inflated_index += 1; + if filter_type <= 4 { + log::trace!( + "png decode prior_line {} filter type = {}", + self.byte_index / self.bytes_per_line, + filter_type + ); + } else { + log::warn!("png decode: invalid filter_type={}", filter_type); + } + self.byte_index += 1; + filter_type + } + } + } + + // Get an inflated byte from the png idat + // Note: this fn() updates inflated_index, byte_index, line_index & filter_type + fn get_inflated_byte(&mut self) -> Option { + match self.inflated_length() { + 0 => None, + _ => { + let byte = self.inflated[self.inflated_index]; + self.inflated_index += 1; + self.byte_index += 1; + self.line_index = match self.byte_index % self.bytes_per_line { + // capture the filter byte at the beginning of each png scan line + 0 => { + self.set_filter_type(); + 0 + } + i => i - 1, + }; + Some(byte) + } + } + } + + // in the notation from https://www.w3.org/TR/PNG/#9Filters + fn unfilter(&mut self) -> Option { + let filter = self.filter_type; + let index = self.line_index; + let bpp = self.bytes_per_pixel; + let fx = match self.get_inflated_byte() { + Some(byte) => byte, + None => return None, + }; + let (a, b, c) = if index < bpp { + (0, self.prior_line[index], 0) + } else { + ( + self.prior_px[index % bpp], + self.prior_line[index], + self.prior_line[index - bpp], + ) + }; + let x = match filter { + 0 => fx, + 1 => fx.wrapping_add(a), + 2 => fx.wrapping_add(b), + 3 => fx.wrapping_add(average(a, b)), + 4 => fx.wrapping_add(paeth(a, b, c)), + _ => fx, + }; + if index > bpp { + self.prior_line[index - bpp] = a; + } + self.prior_px[index % bpp] = x; + Some(x) + } +} + +// in the notation from https://www.w3.org/TR/PNG/#9Filters +fn average(a: u8, b: u8) -> u8 { + ((a as i16 + b as i16) >> 1) as u8 +} + +// in the notation from https://www.w3.org/TR/PNG/#9Filters +fn paeth(a: u8, b: u8, c: u8) -> u8 { + let (a, b, c): (i16, i16, i16) = (a as i16, b as i16, c as i16); + let p = a + b - c; + let pa = (p - a).abs(); + let pb = (p - b).abs(); + let pc = (p - c).abs(); + if pa <= pb && pa <= pc { + a as u8 + } else if pb <= pc { + b as u8 + } else { + c as u8 + } +} diff --git a/services/gam/src/bitmap/decode_png/color_type.rs b/services/gam/src/bitmap/decode_png/color_type.rs new file mode 100644 index 000000000..790e4ee94 --- /dev/null +++ b/services/gam/src/bitmap/decode_png/color_type.rs @@ -0,0 +1,79 @@ +// PNG Pong +// +// Copyright © 2019-2021 Jeron Aldaron Lau +// +// Licensed under the Apache License, Version 2.0, , or the Zlib License, , at your option. This file may not be +// copied, modified, or distributed except according to those terms. + +// small modifications made in Error handling + +use std::io::{Error, ErrorKind, Result}; + +/// Standard PNG color types. +#[derive(Copy, Clone, Debug, Eq, PartialEq)] +#[repr(u8)] +pub enum ColorType { + /// greyscale: 1, 2, 4, 8, 16 bit + Grey = 0u8, + /// RGB: 8, 16 bit + Rgb = 2, + /// palette: 1, 2, 4, 8 bit + Palette = 3, + /// greyscale with alpha: 8, 16 bit + GreyAlpha = 4, + /// RGB with alpha: 8, 16 bit + Rgba = 6, +} + +impl ColorType { + /// channels * bytes per channel = bytes per pixel + pub(crate) fn channels(self) -> u8 { + match self { + ColorType::Grey | ColorType::Palette => 1, + ColorType::GreyAlpha => 2, + ColorType::Rgb => 3, + ColorType::Rgba => 4, + } + } + + /// get the total amount of bits per pixel, based on colortype and bitdepth + /// in the struct + pub(crate) fn bpp(self, bit_depth: u8) -> u8 { + assert!((1..=16).contains(&bit_depth)); + /*bits per pixel is amount of channels * bits per channel*/ + let ch = self.channels(); + ch * if ch > 1 { + if bit_depth == 8 { + 8 + } else { + 16 + } + } else { + bit_depth + } + } + + /// Error if invalid color type / bit depth combination for PNG. + pub(crate) fn check_png_color_validity(self, bd: u8) -> Result<()> { + match self { + ColorType::Grey => { + if !(bd == 1 || bd == 2 || bd == 4 || bd == 8 || bd == 16) { + return Err(Error::new(ErrorKind::InvalidData, "invalid color mode")); + } + } + ColorType::Palette => { + if !(bd == 1 || bd == 2 || bd == 4 || bd == 8) { + return Err(Error::new(ErrorKind::InvalidData, "invalid color mode")); + } + } + ColorType::Rgb | ColorType::GreyAlpha | ColorType::Rgba => { + if !(bd == 8 || bd == 16) { + return Err(Error::new(ErrorKind::InvalidData, "invalid color mode")); + } + } + } + Ok(()) + } +} diff --git a/services/gam/src/bitmap/decode_png/consts.rs b/services/gam/src/bitmap/decode_png/consts.rs new file mode 100644 index 000000000..752acd168 --- /dev/null +++ b/services/gam/src/bitmap/decode_png/consts.rs @@ -0,0 +1,288 @@ +// PNG Pong +// +// Copyright © 2019-2021 Jeron Aldaron Lau +// +// Licensed under the Apache License, Version 2.0, , or the Zlib License, , at your option. This file may not be +// copied, modified, or distributed except according to those terms. +#![allow(dead_code)] +// Magic bytes to start a PNG file. +pub(super) const PNG_SIGNATURE: [u8; 8] = [137, 80, 78, 71, 13, 10, 26, 10]; + +// Chunk Identifiers +pub(super) const IMAGE_HEADER: [u8; 4] = *b"IHDR"; +pub(super) const IMAGE_DATA: [u8; 4] = *b"IDAT"; +pub(super) const BACKGROUND: [u8; 4] = *b"bKGD"; +pub(super) const TRANSPARENCY: [u8; 4] = *b"tRNS"; +pub(super) const IMAGE_END: [u8; 4] = *b"IEND"; +pub(super) const PALETTE: [u8; 4] = *b"PLTE"; +pub(super) const ITEXT: [u8; 4] = *b"iTXt"; +pub(super) const PHYSICAL: [u8; 4] = *b"pHYs"; +pub(super) const TIME: [u8; 4] = *b"tIME"; +pub(super) const ZTEXT: [u8; 4] = *b"zTXt"; +pub(super) const TEXT: [u8; 4] = *b"tEXt"; + +pub(super) const MAX_CHUNK_SIZE: usize = 1 << 31; // 2³¹ + +// Initial value for CRC32 Checksum +pub(super) const CRC32_INIT: u32 = 4_294_967_295; +// Look-up table for CRC32 Checksum +pub(super) const CRC32_LOOKUP: [u32; 256] = [ + 0, + 1_996_959_894, + 3_993_919_788, + 2_567_524_794, + 124_634_137, + 1_886_057_615, + 3_915_621_685, + 2_657_392_035, + 249_268_274, + 2_044_508_324, + 3_772_115_230, + 2_547_177_864, + 162_941_995, + 2_125_561_021, + 3_887_607_047, + 2_428_444_049, + 498_536_548, + 1_789_927_666, + 4_089_016_648, + 2_227_061_214, + 450_548_861, + 1_843_258_603, + 4_107_580_753, + 2_211_677_639, + 325_883_990, + 1_684_777_152, + 4_251_122_042, + 2_321_926_636, + 335_633_487, + 1_661_365_465, + 4_195_302_755, + 2_366_115_317, + 997_073_096, + 1_281_953_886, + 3_579_855_332, + 2_724_688_242, + 1_006_888_145, + 1_258_607_687, + 3_524_101_629, + 2_768_942_443, + 901_097_722, + 1_119_000_684, + 3_686_517_206, + 2_898_065_728, + 853_044_451, + 1_172_266_101, + 3_705_015_759, + 2_882_616_665, + 651_767_980, + 1_373_503_546, + 3_369_554_304, + 3_218_104_598, + 565_507_253, + 1_454_621_731, + 3_485_111_705, + 3_099_436_303, + 671_266_974, + 1_594_198_024, + 3_322_730_930, + 2_970_347_812, + 795_835_527, + 1_483_230_225, + 3_244_367_275, + 3_060_149_565, + 1_994_146_192, + 31_158_534, + 2_563_907_772, + 4_023_717_930, + 1_907_459_465, + 112_637_215, + 2_680_153_253, + 3_904_427_059, + 2_013_776_290, + 251_722_036, + 2_517_215_374, + 3_775_830_040, + 2_137_656_763, + 141_376_813, + 2_439_277_719, + 3_865_271_297, + 1_802_195_444, + 476_864_866, + 2_238_001_368, + 4_066_508_878, + 1_812_370_925, + 453_092_731, + 2_181_625_025, + 4_111_451_223, + 1_706_088_902, + 314_042_704, + 2_344_532_202, + 4_240_017_532, + 1_658_658_271, + 366_619_977, + 2_362_670_323, + 4_224_994_405, + 1_303_535_960, + 984_961_486, + 2_747_007_092, + 3_569_037_538, + 1_256_170_817, + 1_037_604_311, + 2_765_210_733, + 3_554_079_995, + 1_131_014_506, + 879_679_996, + 2_909_243_462, + 3_663_771_856, + 1_141_124_467, + 855_842_277, + 2_852_801_631, + 3_708_648_649, + 1_342_533_948, + 654_459_306, + 3_188_396_048, + 3_373_015_174, + 1_466_479_909, + 544_179_635, + 3_110_523_913, + 3_462_522_015, + 1_591_671_054, + 702_138_776, + 2_966_460_450, + 3_352_799_412, + 1_504_918_807, + 783_551_873, + 3_082_640_443, + 3_233_442_989, + 3_988_292_384, + 2_596_254_646, + 62_317_068, + 1_957_810_842, + 3_939_845_945, + 2_647_816_111, + 81_470_997, + 1_943_803_523, + 3_814_918_930, + 2_489_596_804, + 225_274_430, + 2_053_790_376, + 3_826_175_755, + 2_466_906_013, + 167_816_743, + 2_097_651_377, + 4_027_552_580, + 2_265_490_386, + 503_444_072, + 1_762_050_814, + 4_150_417_245, + 2_154_129_355, + 426_522_225, + 1_852_507_879, + 4_275_313_526, + 2_312_317_920, + 282_753_626, + 1_742_555_852, + 4_189_708_143, + 2_394_877_945, + 397_917_763, + 1_622_183_637, + 3_604_390_888, + 2_714_866_558, + 953_729_732, + 1_340_076_626, + 3_518_719_985, + 2_797_360_999, + 1_068_828_381, + 1_219_638_859, + 3_624_741_850, + 2_936_675_148, + 906_185_462, + 1_090_812_512, + 3_747_672_003, + 2_825_379_669, + 829_329_135, + 1_181_335_161, + 3_412_177_804, + 3_160_834_842, + 628_085_408, + 1_382_605_366, + 3_423_369_109, + 3_138_078_467, + 570_562_233, + 1_426_400_815, + 3_317_316_542, + 2_998_733_608, + 733_239_954, + 1_555_261_956, + 3_268_935_591, + 3_050_360_625, + 752_459_403, + 1_541_320_221, + 2_607_071_920, + 3_965_973_030, + 1_969_922_972, + 40_735_498, + 2_617_837_225, + 3_943_577_151, + 1_913_087_877, + 83_908_371, + 2_512_341_634, + 3_803_740_692, + 2_075_208_622, + 213_261_112, + 2_463_272_603, + 3_855_990_285, + 2_094_854_071, + 198_958_881, + 2_262_029_012, + 4_057_260_610, + 1_759_359_992, + 534_414_190, + 2_176_718_541, + 4_139_329_115, + 1_873_836_001, + 414_664_567, + 2_282_248_934, + 4_279_200_368, + 1_711_684_554, + 285_281_116, + 2_405_801_727, + 4_167_216_745, + 1_634_467_795, + 376_229_701, + 2_685_067_896, + 3_608_007_406, + 1_308_918_612, + 956_543_938, + 2_808_555_105, + 3_495_958_263, + 1_231_636_301, + 1_047_427_035, + 2_932_959_818, + 3_654_703_836, + 1_088_359_270, + 936_918_000, + 2_847_714_899, + 3_736_837_829, + 1_202_900_863, + 817_233_897, + 3_183_342_108, + 3_401_237_130, + 1_404_277_552, + 615_818_150, + 3_134_207_493, + 3_453_421_203, + 1_423_857_449, + 601_450_431, + 3_009_837_614, + 3_294_710_456, + 1_567_103_746, + 711_928_724, + 3_020_668_471, + 3_272_380_065, + 1_510_334_235, + 755_167_117, +]; diff --git a/services/gam/src/lib.rs b/services/gam/src/lib.rs index 3cd068a10..124349a58 100644 --- a/services/gam/src/lib.rs +++ b/services/gam/src/lib.rs @@ -13,7 +13,7 @@ pub use apps::*; #[cfg(feature="ditherpunk")] pub mod bitmap; #[cfg(feature="ditherpunk")] -pub use bitmap::{Bitmap, Img, PixelType}; +pub use bitmap::{Bitmap, Img, PixelType, DecodePng}; use graphics_server::api::{TextOp, TextView}; use graphics_server::api::{Gid, Line, Circle, RoundedRectangle, TokenClaim};