1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
|
use std::{any::TypeId, collections::HashMap};
use byte_encode_derive::ByteEncode;
use zlib_rs::{InflateConfig, decompress_slice};
use crate::{byte_encode::ByteEncode, crc::update_crc, image::{RGB, ColorType, Image, ImageBase, PixelArr}, reader::FileReader, zlib::{BitBuffer, zlib_decode}};
#[derive(Default)]
pub struct PNGImage
{
IHDR: Option<IHDR>,
IDAT: Option<IDAT>,
IEND: Option<IEND>,
tEXt: Option<tEXt>,
}
fn paeth_filter(a: u8, b: u8, c: u8) -> u8 {
let p = (a as i32 + b as i32 - c as i32) as u8;
let pa = p.abs_diff(a);
let pb = p.abs_diff(b);
let pc = p.abs_diff(c);
if pa <= pb && pa <= pc
{
a
}
else if pb <= pc
{
b
}
else
{
c
}
}
enum FilterMethod
{
None,
Sub,
Up,
Average,
Paeth
}
impl FilterMethod
{
fn from_byte(x: u8) -> Self {
match x {
0 => Self::None,
1 => Self::Sub,
2 => Self::Up,
3 => Self::Average,
4 => Self::Paeth,
_ => panic!("Filter {x} is invalid!\nOnly 5 filters exist")
}
}
fn apply(&self, a: u8, b: u8, c: u8, x: u8) -> u8 {
match self {
FilterMethod::None => x,
FilterMethod::Sub => x.wrapping_add(a),
FilterMethod::Up => x.wrapping_add(b),
FilterMethod::Average => x.wrapping_add((a + b)/2),
FilterMethod::Paeth => x.wrapping_add(paeth_filter(a, b, c)),
}
}
}
trait Mergable: Sized
{
fn merge(a: Self, b: Self) -> Self;
}
impl<T: Mergable + Sized + Clone> Mergable for Option<T>
{
fn merge(a: Option<T>, b: Option<T>) -> Option<T>
{
if let Some(ref a_content) = a
{
if let Some(b_content) = b
{
Some(T::merge(a_content.clone(), b_content))
}
else
{
a
}
}
else
{
b
}
}
}
trait PNGChunk: Mergable
{
fn read(reader: &mut FileReader, length: usize) -> Self;
const CHUNK_TYPE: [char; 4];
}
#[derive(ByteEncode, Clone)]
struct IHDR
{
pub width: u32,
pub height: u32,
pub bit_depth: u8,
pub color_type: u8,
pub compression_method: u8,
pub filter_method: u8,
pub interlace_method: u8
}
impl PNGChunk for IHDR
{
const CHUNK_TYPE: [char; 4] = ['I', 'H', 'D', 'R'];
fn read(reader: &mut FileReader, _: usize) -> Self {
reader.read()
}
}
impl Mergable for IHDR {
fn merge(a: Self, b: Self) -> Self {
todo!()
}
}
#[derive(ByteEncode, Clone)]
struct IEND
{
}
impl PNGChunk for IEND
{
const CHUNK_TYPE: [char; 4] = ['I', 'E', 'N', 'D'];
fn read(_: &mut FileReader, _: usize) -> Self {
Self {}
}
}
impl Mergable for IEND {
fn merge(a: Self, b: Self) -> Self {
todo!()
}
}
#[derive(Clone)]
struct tEXt
{
keywords: HashMap<String, String>
}
impl PNGChunk for tEXt
{
const CHUNK_TYPE: [char; 4] = ['t', 'E', 'X', 't'];
fn read(reader: &mut FileReader, length: usize) -> Self
{
let mut i = 0;
let mut keyword = String::new();
let mut c: u8 = reader.read();
i += 1;
while c != 0
{
keyword.push(c as char);
c = reader.read::<1, u8>();
i += 1;
}
let mut text_string = String::new();
while i < length
{
text_string.push(reader.read::<1, u8>() as char);
i += 1;
}
let mut keywords = HashMap::new();
keywords.insert(keyword, text_string);
Self
{
keywords
}
}
}
impl Mergable for tEXt {
fn merge(a: Self, b: Self) -> Self {
let mut keywords = HashMap::new();
keywords.extend(a.keywords);
keywords.extend(b.keywords);
Self
{
keywords
}
}
}
#[derive(Clone)]
struct IDAT
{
data: Vec<u8>
}
impl PNGChunk for IDAT
{
fn read(reader: &mut FileReader, length: usize) -> Self {
let data = reader.get_bytes(length);
Self
{
data
}
}
const CHUNK_TYPE: [char; 4] = ['I', 'D', 'A', 'T'];
}
impl Mergable for IDAT
{
fn merge(a: Self, b: Self) -> Self {
let mut data = Vec::new();
data.extend(a.data);
data.extend(b.data);
Self
{
data
}
}
}
trait RGBu8: ColorType {}
impl RGBu8 for RGB<u8> {}
impl<T: RGBu8> Image<T> for PNGImage
where T: 'static
{
fn read_image(reader: &mut FileReader) -> Result<ImageBase<T>, String> {
assert!(
TypeId::of::<T>() == TypeId::of::<RGB<u8>>(),
"PNG only working for rgb u8's currently sorry"
);
let magic: [u8; 8] = reader.read_array();
if magic != [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]
{
return Err("Not a PNG!".to_owned());
}
reader.set_endianness(false);
reader.set_checksum_handler(update_crc, 0xffffffffu32);
let mut p = PNGImage::default();
while p.IEND.is_none()
{
let length: usize = reader.read::<4, u32>() as usize;
reader.reset_checksum();
let chunk_type: [char; 4] = reader.read_array::<1, u8, 4>().map(|x| x as char);
let chunk_flags = chunk_type.map(|x| x.is_lowercase());
println!("type: {chunk_type:?}");
println!("length: {length}");
match chunk_type
{
IHDR::CHUNK_TYPE => { p.IHDR = Option::<IHDR>::merge(p.IHDR, Some(IHDR::read(reader, length))) }
IDAT::CHUNK_TYPE => { p.IDAT = Option::<IDAT>::merge(p.IDAT, Some(IDAT::read(reader, length))) }
IEND::CHUNK_TYPE => { p.IEND = Option::<IEND>::merge(p.IEND, Some(IEND::read(reader, length))) }
tEXt::CHUNK_TYPE => { p.tEXt = Option::<tEXt>::merge(p.tEXt, Some(tEXt::read(reader, length))) }
_ => {
if chunk_flags[0]
{
println!("Skipping ancillary chunk");
println!("{}", if chunk_flags[1] { "Private (can find definition)" } else { "Public" })
}
else
{
println!("Skipping important chunk!!!");
}
reader.skip(length)
}
}
let mut calculated_crc = reader.get_checksum();
let crc: u32 = reader.read();
if crc ^ calculated_crc != 0xffffffffu32 && !chunk_flags[0]
{
calculated_crc ^= 0xffffffffu32;
println!("Bad crc: {crc} {calculated_crc}");
}
}
if let Some(ref tEXt) = p.tEXt
{
for x in tEXt.keywords.iter()
{
println!("{0}: {1}", x.0, x.1);
}
}
if p.IEND.is_none()
{
return Err("IEND not present".to_owned());
}
let Some(IHDR) = p.IHDR else { return Err("IHDR not present".to_owned()); };
let Some(IDAT) = p.IDAT else { return Err("IDAT not present".to_owned()); };
let colors_per_pixel: u8 = if IHDR.color_type == 4 || IHDR.color_type == 6 { 4 } else { 3 };
let bpp: u8 = IHDR.bit_depth * colors_per_pixel;
let width: u32 = IHDR.width;
let height: u32 = IHDR.height;
println!("{bpp}, {width}, {height}");
let compression_method: u8 = IDAT.data[0];
let additional_flags: u8 = IDAT.data[1];
let mut decoded = vec![0u8; 1920*(1080*3 + 1)]; // zlib_decode(BitBuffer::new(&IDAT.data[2..]));
let (decompressed, rc) = decompress_slice(&mut decoded, &IDAT.data, InflateConfig::default());
println!("{rc:?}");
let mut pixels = PixelArr::<T>::new(width, height);
let mut rows: Vec<Vec<u8>> = Vec::new();
let mut i = 0;
for y in 0..(height as usize)
{
// println!("i: {i}");
let filter = FilterMethod::from_byte(decoded[i]);
i += 1;
let mut row: Vec<u8> = Vec::with_capacity(width as usize * 3);
for x in 0..(width as usize * 3)
{
let a: u8 = if x < 3 { 0 } else { row[x - 3] };
let b: u8 = if y < 1 { 0 } else { rows[y - 1][x] };
let c: u8 = if y < 1 || x < 3 { 0 } else { rows[y - 1][x - 3] };
let x = decoded[i];
i += 1;
row.push(filter.apply(a, b, c, x));
}
rows.push(row);
}
for y in 0..(height as usize)
{
for x in 0..(width as usize)
{
let row = &rows[y];
let r = row[x * 3];
let g = row[x * 3 + 1];
let b = row[x * 3 + 2];
pixels[(x, y)] = (RGB { r, g, b}).convert();
}
}
Ok(ImageBase
{
bpp,
pixels
})
}
fn write_image(image: &crate::image::ImageBase<T>, writer: &mut crate::writer::FileWriter)-> () {
todo!()
}
}
|