Debian Codegraph @

.cargo/vendor/fax/src/decoder.rs

raw
1 use std::convert::Infallible;
2 use std::io::{self, Bytes, Read};
3
4 use crate::{BitReader, ByteReader, Color, Transitions};
5 use crate::maps::{Mode, black, white, mode, EDFB_HALF, EOL};
6
7
8 fn with_markup<D, R>(decoder: D, reader: &mut R) -> Option<u16>
9 where D: Fn(&mut R) -> Option<u16>
10 {
11 let mut sum = 0;
12 while let Some(n) = decoder(reader) {
13 //print!("{} ", n);
14 sum += n;
15 if n < 64 {
16 //debug!("= {}", sum);
17 return Some(sum)
18 }
19 }
20 None
21 }
22
23 fn colored(current: Color, reader: &mut impl BitReader) -> Option<u16> {
24 //debug!("{:?}", current);
25 match current {
26 Color::Black => with_markup(black::decode, reader),
27 Color::White => with_markup(white::decode, reader),
28 }
29 }
30
31 /// Turn a list of color changing position into an iterator of pixel colors
32 ///
33 /// The width of the line/image has to be given in `width`.
34 /// The iterator will produce exactly that many items.
35 pub fn pels(line: &[u16], width: u16) -> impl Iterator<Item=Color> + '_ {
36 use std::iter::repeat;
37 let mut color = Color::White;
38 let mut last = 0;
39 let pad_color = if line.len() & 1 == 1 {
40 !color
41 } else {
42 color
43 };
44 line.iter().flat_map(move |&p| {
45 let c = color;
46 color = !color;
47 let n = p.saturating_sub(last);
48 last = p;
49 repeat(c).take(n as usize)
50 }).chain(repeat(pad_color)).take(width as usize)
51 }
52
53 /// Decode a Group 3 encoded image.
54 ///
55 /// The callback `line_cb` is called for each decoded line.
56 /// The argument is the list of positions of color change, starting with white.
57 ///
58 /// To obtain an iterator over the pixel colors, the `pels` function is provided.
59 pub fn decode_g3(input: impl Iterator<Item=u8>, mut line_cb: impl FnMut(&[u16])) -> Option<()> {
60 let reader = input.map(Result::<u8, Infallible>::Ok);
61 let mut decoder = Group3Decoder::new(reader).ok()?;
62
63 while let Ok(status) = decoder.advance() {
64 if status == DecodeStatus::End {
65 return Some(());
66 }
67 line_cb(decoder.transitions());
68 }
69 None
70 }
71
72 #[derive(PartialEq, Eq, Debug, Copy, Clone)]
73 pub enum DecodeStatus {
74 Incomplete,
75 End,
76 }
77
78 pub struct Group3Decoder<R> {
79 reader: ByteReader<R>,
80 current: Vec<u16>
81 }
82 impl<E: std::fmt::Debug, R: Iterator<Item=Result<u8, E>>> Group3Decoder<R> {
83 pub fn new(reader: R) -> Result<Self, DecodeError<E>> {
84 let mut reader = ByteReader::new(reader).map_err(DecodeError::Reader)?;
85 reader.expect(EOL).map_err(|_| DecodeError::Invalid)?;
86
87 Ok(Group3Decoder { reader, current: vec![] })
88 }
89 pub fn advance(&mut self) -> Result<DecodeStatus, DecodeError<E>> {
90 self.current.clear();
91 let mut a0 = 0;
92 let mut color = Color::White;
93 while let Some(p) = colored(color, &mut self.reader) {
94 a0 += p;
95 self.current.push(a0);
96 color = !color;
97 }
98 self.reader.expect(EOL).map_err(|_| DecodeError::Invalid)?;
99
100 for _ in 0 .. 6 {
101 if self.reader.peek(EOL.len) == Some(EOL.data) {
102 self.reader.consume(EOL.len).map_err(DecodeError::Reader)?;
103 } else {
104 return Ok(DecodeStatus::Incomplete)
105 }
106 }
107
108 Ok(DecodeStatus::End)
109 }
110 pub fn transitions(&self) -> &[u16] {
111 &self.current
112 }
113 }
114
115 /// Decode a Group 4 Image
116 ///
117 /// - `width` is the width of the image.
118 /// - The callback `line_cb` is called for each decoded line.
119 /// The argument is the list of positions of color change, starting with white.
120 ///
121 /// If `height` is specified, at most that many lines will be decoded,
122 /// otherwise data is decoded until the end-of-block marker (or end of data).
123 ///
124 /// To obtain an iterator over the pixel colors, the `pels` function is provided.
125 pub fn decode_g4(input: impl Iterator<Item=u8>, width: u16, height: Option<u16>, mut line_cb: impl FnMut(&[u16])) -> Option<()> {
126 let reader = input.map(Result::<u8, Infallible>::Ok);
127 let mut decoder = Group4Decoder::new(reader, width).ok()?;
128
129 for y in 0 .. height.unwrap_or(u16::MAX) {
130 let status = decoder.advance().ok()?;
131 if status == DecodeStatus::End {
132 return Some(());
133 }
134 line_cb(decoder.transition());
135 }
136 Some(())
137 }
138
139 #[derive(Debug)]
140 pub enum DecodeError<E> {
141 Reader(E),
142 Invalid,
143 Unsupported,
144 }
145 impl<E> std::fmt::Display for DecodeError<E> {
146 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
147 write!(f, "Decode Error")
148 }
149 }
150 impl<E: std::error::Error> std::error::Error for DecodeError<E> {
151 }
152
153 pub struct Group4Decoder<R> {
154 reader: ByteReader<R>,
155 reference: Vec<u16>,
156 current: Vec<u16>,
157 width: u16
158 }
159 impl<E, R: Iterator<Item=Result<u8, E>>> Group4Decoder<R> {
160 pub fn new(reader: R, width: u16) -> Result<Self, E> {
161 Ok(Group4Decoder {
162 reader: ByteReader::new(reader)?,
163 reference: Vec::new(),
164 current: Vec::new(),
165 width
166 })
167 }
168 // when Complete::Complete is returned, there is no useful data in .transitions() or .line()
169 pub fn advance(&mut self) -> Result<DecodeStatus, DecodeError<E>> {
170 let mut transitions = Transitions::new(&self.reference);
171 let mut a0 = 0;
172 let mut color = Color::White;
173 let mut start_of_row = true;
174 //debug!("\n\nline {}", y);
175
176 loop {
177 //reader.print_peek();
178 let mode = match mode::decode(&mut self.reader) {
179 Some(mode) => mode,
180 None => return Err(DecodeError::Invalid),
181 };
182 //debug!(" {:?}, color={:?}, a0={}", mode, color, a0);
183
184 match mode {
185 Mode::Pass => {
186 if start_of_row && color == Color::White {
187 transitions.pos += 1;
188 } else {
189 transitions.next_color(a0, !color, false).ok_or(DecodeError::Invalid)?;
190 }
191 //debug!("b1={}", b1);
192 if let Some(b2) = transitions.next() {
193 //debug!("b2={}", b2);
194 a0 = b2;
195 }
196 }
197 Mode::Vertical(delta) => {
198 let b1 = transitions.next_color(a0, !color, start_of_row).unwrap_or(self.width);
199 let a1 = (b1 as i16 + delta as i16) as u16;
200 if a1 >= self.width {
201 break;
202 }
203 //debug!("transition to {:?} at {}", !color, a1);
204 self.current.push(a1);
205 color = !color;
206 a0 = a1;
207 if delta < 0 {
208 transitions.seek_back(a0);
209 }
210 }
211 Mode::Horizontal => {
212 let a0a1 = colored(color, &mut self.reader).ok_or(DecodeError::Invalid)?;
213 let a1a2 = colored(!color, &mut self.reader).ok_or(DecodeError::Invalid)?;
214 let a1 = a0 + a0a1;
215 let a2 = a1 + a1a2;
216 //debug!("a0a1={}, a1a2={}, a1={}, a2={}", a0a1, a1a2, a1, a2);
217
218 self.current.push(a1);
219 if a2 >= self.width {
220 break;
221 }
222 self.current.push(a2);
223 a0 = a2;
224 }
225 Mode::Extension => {
226 let xxx = self.reader.peek(3).ok_or(DecodeError::Invalid)?;
227 // debug!("extension: {:03b}", xxx);
228 self.reader.consume(3);
229 // debug!("{:?}", current);
230 return Err(DecodeError::Unsupported);
231 }
232 Mode::EOF => return Ok(DecodeStatus::End),
233 }
234 start_of_row = false;
235
236 if a0 >= self.width {
237 break;
238 }
239 }
240 //debug!("{:?}", current);
241
242 std::mem::swap(&mut self.reference, &mut self.current);
243 self.current.clear();
244
245 Ok(DecodeStatus::Incomplete)
246 }
247
248 pub fn transition(&self) -> &[u16] {
249 &self.reference
250 }
251
252 pub fn line(&self) -> Line {
253 Line { transitions: &self.reference, width: self.width }
254 }
255 }
256
257 pub struct Line<'a> {
258 pub transitions: &'a [u16],
259 pub width: u16
260 }
261 impl<'a> Line<'a> {
262 pub fn pels(&self) -> impl Iterator<Item = Color> + 'a {
263 pels(&self.transitions, self.width)
264 }
265 }