Mutable scanline iterator

This commit is contained in:
Kornel Lesiński 2018-11-24 22:41:13 +00:00
parent ba8c0b4d2f
commit da9afbd5b5
2 changed files with 112 additions and 42 deletions

View file

@ -29,7 +29,7 @@ const STD_FILTERS: [u8; 2] = [0, 5];
mod scan_lines; mod scan_lines;
use self::scan_lines::{ScanLine, ScanLines}; use self::scan_lines::{ScanLine, ScanLines, ScanLinesMut};
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
/// Contains all data relevant to a PNG image /// Contains all data relevant to a PNG image
@ -227,6 +227,12 @@ impl PngData {
ScanLines::new(self) ScanLines::new(self)
} }
/// Return an iterator over the scanlines of the image
#[inline]
pub fn scan_lines_mut(&mut self) -> ScanLinesMut {
ScanLinesMut::new(self)
}
/// Reverse all filters applied on the image, returning an unfiltered IDAT bytestream /// Reverse all filters applied on the image, returning an unfiltered IDAT bytestream
pub fn unfilter_image(&self) -> Vec<u8> { pub fn unfilter_image(&self) -> Vec<u8> {
let mut unfiltered = Vec::with_capacity(self.raw_data.len()); let mut unfiltered = Vec::with_capacity(self.raw_data.len());
@ -410,7 +416,6 @@ impl PngData {
} }
fn do_palette_reduction(&mut self, palette_map: &[u8; 256], used: &[bool; 256]) { fn do_palette_reduction(&mut self, palette_map: &[u8; 256], used: &[bool; 256]) {
let mut new_data = Vec::with_capacity(self.raw_data.len());
let mut byte_map = *palette_map; let mut byte_map = *palette_map;
// low bit-depths can be pre-computed for every byte value // low bit-depths can be pre-computed for every byte value
@ -429,14 +434,12 @@ impl PngData {
} }
// Reassign data bytes to new indices // Reassign data bytes to new indices
for line in self.scan_lines() { for line in self.scan_lines_mut() {
new_data.push(line.filter); for byte in line.data {
for &byte in line.data { *byte = byte_map[*byte as usize];
new_data.push(byte_map[byte as usize])
} }
} }
self.raw_data = new_data;
self.transparency_pixel = None; self.transparency_pixel = None;
if let Some(palette) = self.palette.take() { if let Some(palette) = self.palette.take() {
let max_index = palette_map.iter().max().cloned().unwrap_or(0) as usize; let max_index = palette_map.iter().max().cloned().unwrap_or(0) as usize;

View file

@ -3,35 +3,102 @@ use super::PngData;
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
/// An iterator over the scan lines of a PNG image /// An iterator over the scan lines of a PNG image
pub struct ScanLines<'a> { pub struct ScanLines<'a> {
iter: ScanLineRanges,
/// A reference to the PNG image being iterated upon /// A reference to the PNG image being iterated upon
start: usize,
/// Current pass number, and 0-indexed row within the pass
pass: Option<(u8, u32)>,
bits_per_pixel: u8,
width: u32,
height: u32,
raw_data: &'a [u8], raw_data: &'a [u8],
} }
impl<'a> ScanLines<'a> { impl<'a> ScanLines<'a> {
pub fn new(png: &'a PngData) -> Self { pub fn new(png: &'a PngData) -> Self {
Self { Self {
bits_per_pixel: png.ihdr_data.bit_depth.as_u8() * png.channels_per_pixel(), iter: ScanLineRanges::new(png),
width: png.ihdr_data.width,
height: png.ihdr_data.height,
raw_data: &png.raw_data, raw_data: &png.raw_data,
start: 0,
pass: if png.ihdr_data.interlaced == 1 {Some((1, 0))} else {None},
} }
} }
} }
impl<'a> Iterator for ScanLines<'a> { impl<'a> Iterator for ScanLines<'a> {
type Item = ScanLine<'a>; type Item = ScanLine<'a>;
#[inline]
fn next(&mut self) -> Option<Self::Item> { fn next(&mut self) -> Option<Self::Item> {
if self.start >= self.raw_data.len() { self.iter.next().map(|(len, pass)| {
None let (data, rest) = self.raw_data.split_at(len);
} else if let Some(ref mut pass) = self.pass { self.raw_data = rest;
let (&filter, data) = data.split_first().unwrap();
ScanLine {
filter,
data,
pass,
}
})
}
}
#[derive(Debug)]
/// An iterator over the scan lines of a PNG image
pub struct ScanLinesMut<'a> {
iter: ScanLineRanges,
/// A reference to the PNG image being iterated upon
raw_data: Option<&'a mut [u8]>,
}
impl<'a> ScanLinesMut<'a> {
pub fn new(png: &'a mut PngData) -> Self {
Self {
iter: ScanLineRanges::new(png),
raw_data: Some(&mut png.raw_data),
}
}
}
impl<'a> Iterator for ScanLinesMut<'a> {
type Item = ScanLineMut<'a>;
#[inline]
fn next(&mut self) -> Option<Self::Item> {
self.iter.next().map(|(len, pass)| {
let tmp = self.raw_data.take().unwrap();
let (data, rest) = tmp.split_at_mut(len);
self.raw_data = Some(rest);
let (&mut filter, data) = data.split_first_mut().unwrap();
ScanLineMut {
filter,
data,
pass,
}
})
}
}
#[derive(Debug, Clone)]
/// An iterator over the scan line locations of a PNG image
struct ScanLineRanges {
/// Current pass number, and 0-indexed row within the pass
pass: Option<(u8, u32)>,
bits_per_pixel: u8,
width: u32,
height: u32,
left: usize,
}
impl ScanLineRanges {
pub fn new(png: &PngData) -> Self {
Self {
bits_per_pixel: png.ihdr_data.bit_depth.as_u8() * png.channels_per_pixel(),
width: png.ihdr_data.width,
height: png.ihdr_data.height,
left: png.raw_data.len(),
pass: if png.ihdr_data.interlaced == 1 {Some((1, 0))} else {None},
}
}
}
impl Iterator for ScanLineRanges {
type Item = (usize, Option<u8>);
fn next(&mut self) -> Option<Self::Item> {
if self.left == 0 {
return None;
}
let (pixels_per_line, current_pass) = if let Some(ref mut pass) = self.pass {
// Scanlines for interlaced PNG files // Scanlines for interlaced PNG files
// Handle edge cases for images smaller than 5 pixels in either direction // Handle edge cases for images smaller than 5 pixels in either direction
if self.width < 5 && pass.0 == 2 { if self.width < 5 && pass.0 == 2 {
@ -71,7 +138,6 @@ impl<'a> Iterator for ScanLines<'a> {
_ => (), _ => (),
}; };
let current_pass = Some(pass.0); let current_pass = Some(pass.0);
let bytes_per_line = ((pixels_per_line * self.bits_per_pixel as u32 + 7) / 8) as usize;
if pass.1 + y_steps >= self.height { if pass.1 + y_steps >= self.height {
pass.0 += 1; pass.0 += 1;
pass.1 = match pass.0 { pass.1 = match pass.0 {
@ -83,27 +149,16 @@ impl<'a> Iterator for ScanLines<'a> {
} else { } else {
pass.1 += y_steps; pass.1 += y_steps;
} }
let start = self.start; (pixels_per_line, current_pass)
let len = bytes_per_line + 1;
self.start += len;
Some(ScanLine {
filter: self.raw_data[start],
data: &self.raw_data[(start + 1)..(start + len)],
pass: current_pass,
})
} else { } else {
// Standard, non-interlaced PNG scanlines // Standard, non-interlaced PNG scanlines
let bits_per_line = self.width * self.bits_per_pixel as u32; (self.width, None)
};
let bits_per_line = pixels_per_line * self.bits_per_pixel as u32;
let bytes_per_line = ((bits_per_line + 7) / 8) as usize; let bytes_per_line = ((bits_per_line + 7) / 8) as usize;
let start = self.start;
let len = bytes_per_line + 1; let len = bytes_per_line + 1;
self.start += len; self.left -= len;
Some(ScanLine { Some((len, current_pass))
filter: self.raw_data[start],
data: &self.raw_data[(start + 1)..(start + len)],
pass: None,
})
}
} }
} }
@ -117,3 +172,15 @@ pub struct ScanLine<'a> {
/// The current pass if the image is interlaced /// The current pass if the image is interlaced
pub pass: Option<u8>, pub pass: Option<u8>,
} }
#[derive(Debug)]
/// A scan line in a PNG image
pub struct ScanLineMut<'a> {
/// The filter type used to encode the current scan line (0-4)
pub filter: u8,
/// The byte data for the current scan line, encoded with the filter specified in the `filter` field
pub data: &'a mut [u8],
/// The current pass if the image is interlaced
pub pass: Option<u8>,
}