-
Notifications
You must be signed in to change notification settings - Fork 0
/
rle_simple.rs
62 lines (48 loc) · 1.45 KB
/
rle_simple.rs
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
use std::{error::Error, io::Write};
use image::GrayImage;
use super::common::{frames_difference, get_size};
fn encode_frame(frame: &GrayImage) -> Result<Vec<u8>, Box<dyn Error>> {
let mut lengths: Vec<u8> = Vec::new();
let mut color = false;
let mut length: u8 = 0;
for pixel in frame.pixels() {
let pixel = pixel.0[0] >= 127;
if pixel == color {
if length == 0xFF {
lengths.push(0xFF);
lengths.push(0);
length = 1;
} else {
length += 1;
}
} else {
lengths.push(length);
color = pixel;
length = 1;
}
}
// Force total length to full image.
if length > 0 {
lengths.push(length);
}
// Force end color to be off.
// if color {
// lengths.push(0);
// }
Ok(lengths)
}
pub fn encode_frames(frames: &Vec<GrayImage>) -> Result<Vec<u8>, Box<dyn Error>> {
let mut buffer: Vec<u8> = Vec::new();
let (width, height) = get_size(frames)?;
for (index, frame) in frames.iter().enumerate() {
let last_frame = if index > 0 {
frames[index - 1].clone()
} else {
GrayImage::new(width, height)
};
let frame_difference = frames_difference(&last_frame, frame)?;
let frame_encoded = encode_frame(&frame_difference)?;
buffer.write(&frame_encoded)?;
}
Ok(buffer)
}