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
|
use std::{
borrow::Cow,
convert::{TryFrom, TryInto},
fs::File,
io::{BufRead, BufReader, Read},
path::Path,
};
use crate::{
block::{
extension::{Application, Extension, GraphicControl},
Block, BlockedImage, ColorTable, ImageDescriptor, ScreenDescriptor, Version,
},
Gif,
};
pub struct GifReader {}
impl GifReader {
pub fn file<P: AsRef<Path>>(path: P) -> Gif {
let mut file = File::open(path).expect("Failed to open file");
let mut reader = SmartReader {
inner: vec![],
position: 0,
};
file.read_to_end(&mut reader.inner)
.expect("Failed to read gif");
let mut gif = Self::read_required(&mut reader);
if gif.screen_descriptor.color_table_present() {
let gct_size = gif.screen_descriptor.color_table_len() * 3;
gif.global_color_table = Some(Self::read_color_table(&mut reader, gct_size));
}
loop {
match Self::read_block(&mut reader) {
Some(block) => {
/*match &block {
Block::IndexedImage(_) => println!("Indexed Image"),
Block::BlockedImage(_) => println!("Blocked Image"),
Block::Extension(ext) => match ext {
Extension::GraphicControl(_) => println!("Graphic Cotrol Extension"),
Extension::Looping(_) => println!("Netscape Extension"),
Extension::Comment(vec) => {
println!("Comment Extension {:X}", vec.len())
}
Extension::Application(_) => todo!(),
},
}*/
gif.blocks.push(block)
}
None => return gif,
}
}
}
fn read_required(reader: &mut SmartReader) -> Gif {
let version = match reader.take_lossy_utf8(6).as_deref() {
Some("GIF87a") => Version::Gif87a,
Some("GIF89a") => Version::Gif89a,
_ => panic!("Version string is unknown"),
};
let mut lsd_buffer: [u8; 7] = [0; 7];
reader
.read_exact(&mut lsd_buffer)
.expect("Failed to read Logical Screen Descriptor from gif");
let lsd = ScreenDescriptor::from(lsd_buffer);
Gif {
header: version,
screen_descriptor: lsd,
global_color_table: None,
blocks: vec![],
}
}
fn read_color_table(reader: &mut SmartReader, size: usize) -> ColorTable {
let buffer = reader
.take(size as usize)
.expect("Failed to read Color Table");
ColorTable::try_from(&buffer[..]).expect("Failed to parse Color Table")
}
fn read_block(reader: &mut SmartReader) -> Option<Block> {
let block_id = reader.u8().expect("File ended early");
match block_id {
0x21 => Some(Self::read_extension(reader)),
0x2C => Some(Self::read_image(reader)),
0x3B => None,
_ => None, /*panic!(
"Unknown block identifier {:X} {:X}",
block_id, reader.position
),*/
}
}
fn read_extension(mut reader: &mut SmartReader) -> Block {
let mut extension_id = reader.u8().expect("File ended early");
match extension_id {
0xF9 => {
reader.skip(1); // Skip block length, we know it
let mut data = [0u8; 4];
reader
.read_exact(&mut data)
.expect("Data ended early in graphics control extension sublock");
reader.skip(1); // Skip block terminator
Block::Extension(Extension::GraphicControl(GraphicControl::from(data)))
}
0xFE => Block::Extension(Extension::Comment(reader.take_and_collapse_subblocks())),
0x01 => todo!(), // plain text extension
0xFF => {
assert_eq!(Some(11), reader.u8());
let identifier = reader.take_lossy_utf8(8).unwrap().to_string();
let authentication_code: [u8; 3] =
TryInto::try_into(reader.take(3).unwrap()).unwrap();
let data = reader.take_and_collapse_subblocks();
Block::Extension(Extension::Application(Application {
identifier,
authentication_code,
data,
}))
}
_ => panic!("Unknown Extension Identifier!"),
}
}
fn read_image(mut reader: &mut SmartReader) -> Block {
let mut buffer = [0u8; 9];
reader
.read_exact(&mut buffer)
.expect("Failed to read Image Descriptor");
let descriptor = ImageDescriptor::from(buffer);
let color_table = if descriptor.color_table_present() {
let size = descriptor.color_table_size() * 3;
Some(Self::read_color_table(&mut reader, size))
} else {
None
};
let lzw_csize = reader.u8().expect("Failed to read LZW Minimum Code Size");
let blocks = reader.take_data_subblocks();
Block::BlockedImage(BlockedImage {
image_descriptor: descriptor,
local_color_table: color_table,
lzw_minimum_code_size: lzw_csize,
blocks,
})
}
}
struct SmartReader {
inner: Vec<u8>,
position: usize,
}
impl SmartReader {
pub fn u8(&mut self) -> Option<u8> {
self.position += 1;
self.inner.get(self.position - 1).map(|b| *b)
}
pub fn u16(&mut self) -> Option<u16> {
self.position += 2;
self.inner
.get(self.position - 2..self.position)
.map(|bytes| u16::from_le_bytes(bytes.try_into().unwrap()))
}
pub fn skip(&mut self, size: usize) {
self.position += size;
}
pub fn take(&mut self, size: usize) -> Option<&[u8]> {
self.position += size;
self.inner.get(self.position - size..self.position)
}
//TODO: Result not Option when buffer len
pub fn read_exact(&mut self, buf: &mut [u8]) -> Option<()> {
if self.position + buf.len() > self.inner.len() {
None
} else {
self.position += buf.len();
buf.copy_from_slice(&self.inner[self.position - buf.len()..self.position]);
Some(())
}
}
pub fn take_vec(&mut self, size: usize) -> Option<Vec<u8>> {
self.position += size;
self.inner
.get(self.position - size..self.position)
.map(|bytes| bytes.to_vec())
}
pub fn take_lossy_utf8(&mut self, size: usize) -> Option<Cow<'_, str>> {
self.take(size).map(|bytes| String::from_utf8_lossy(bytes))
}
pub fn take_data_subblocks(&mut self) -> Vec<Vec<u8>> {
let mut blocks = vec![];
loop {
let block_size = self.u8().expect("Failed to read length of sublock");
if block_size == 0 {
return blocks;
}
let block = self
.take_vec(block_size as usize)
.expect("Failed to read sublock");
blocks.push(block);
}
}
pub fn take_and_collapse_subblocks(&mut self) -> Vec<u8> {
let blocks = self.take_data_subblocks();
let mut ret = vec![];
for block in blocks {
ret.extend_from_slice(&block)
}
ret
}
}
|