1use std::io::Cursor;
20use std::path::Path;
21
22use viva_pfnc::convert::{self, ConvertError, Pixels};
23
24use crate::Frame;
25
26#[derive(Debug, Clone, Copy, PartialEq, Eq)]
28#[non_exhaustive]
29pub enum ImageFormat {
30 Png,
32 Tiff,
34}
35
36impl ImageFormat {
37 pub fn from_path(path: &Path) -> Option<Self> {
40 let extension = path.extension()?.to_str()?.to_ascii_lowercase();
41 match extension.as_str() {
42 "png" => Some(ImageFormat::Png),
43 "tif" | "tiff" => Some(ImageFormat::Tiff),
44 _ => None,
45 }
46 }
47
48 pub fn extension(self) -> &'static str {
50 match self {
51 ImageFormat::Png => "png",
52 ImageFormat::Tiff => "tiff",
53 }
54 }
55}
56
57#[derive(Debug, thiserror::Error)]
59#[non_exhaustive]
60pub enum ImageIoError {
61 #[error(transparent)]
63 Convert(#[from] ConvertError),
64 #[error("{samples} samples for a {width}×{height} image with {channels} channel(s)")]
66 Size {
67 samples: usize,
69 width: u32,
71 height: u32,
73 channels: usize,
75 },
76 #[error("cannot encode this pixel layout")]
78 Layout,
79 #[error("{0} does not end in .png, .tif or .tiff")]
82 Extension(std::path::PathBuf),
83 #[error("cannot encode image: {0}")]
86 Encode(#[source] Box<dyn std::error::Error + Send + Sync + 'static>),
87 #[error(transparent)]
89 Io(#[from] std::io::Error),
90}
91
92pub fn encode_frame(frame: &Frame, format: ImageFormat) -> Result<Vec<u8>, ImageIoError> {
95 let pixels = convert::full_depth(
96 frame.pixel_format,
97 frame.width,
98 frame.height,
99 frame.row_stride(),
100 &frame.payload,
101 )?;
102 encode(&pixels, frame.width, frame.height, format)
103}
104
105pub fn save_frame(frame: &Frame, path: &Path) -> Result<(), ImageIoError> {
107 let format =
108 ImageFormat::from_path(path).ok_or_else(|| ImageIoError::Extension(path.to_path_buf()))?;
109 std::fs::write(path, encode_frame(frame, format)?)?;
110 Ok(())
111}
112
113pub fn encode(
115 pixels: &Pixels,
116 width: u32,
117 height: u32,
118 format: ImageFormat,
119) -> Result<Vec<u8>, ImageIoError> {
120 let image = Image::of(pixels, width, height)?;
121 match format {
122 ImageFormat::Png => image.png(),
123 ImageFormat::Tiff => image.tiff(),
124 }
125}
126
127struct Image<'a> {
129 width: u32,
130 height: u32,
131 rgb: bool,
132 samples: Samples<'a>,
133 significant: Option<u8>,
135}
136
137enum Samples<'a> {
138 Eight(&'a [u8]),
139 Sixteen(Vec<u16>),
140}
141
142impl<'a> Image<'a> {
143 fn of(pixels: &'a Pixels, width: u32, height: u32) -> Result<Self, ImageIoError> {
144 let (rgb, samples, bits) = match pixels {
145 Pixels::Gray8(v) => (false, Samples::Eight(v), 8),
146 Pixels::Rgb8(v) => (true, Samples::Eight(v), 8),
147 Pixels::Gray16 { samples, bits } => {
148 (false, Samples::Sixteen(scale(samples, *bits)), *bits)
149 }
150 Pixels::Rgb16 { samples, bits } => {
151 (true, Samples::Sixteen(scale(samples, *bits)), *bits)
152 }
153 _ => return Err(ImageIoError::Layout),
154 };
155 let channels = if rgb { 3 } else { 1 };
156 let expected = (width as usize)
157 .checked_mul(height as usize)
158 .and_then(|n| n.checked_mul(channels));
159 let actual = match &samples {
160 Samples::Eight(v) => v.len(),
161 Samples::Sixteen(v) => v.len(),
162 };
163 if expected != Some(actual) {
164 return Err(ImageIoError::Size {
165 samples: actual,
166 width,
167 height,
168 channels,
169 });
170 }
171 Ok(Image {
172 width,
173 height,
174 rgb,
175 samples,
176 significant: (8 < bits && bits < 16).then_some(bits),
177 })
178 }
179
180 fn png(&self) -> Result<Vec<u8>, ImageIoError> {
181 let failed = |e: png::EncodingError| ImageIoError::Encode(Box::new(e));
182 let mut file = Vec::new();
183 let mut encoder = png::Encoder::new(&mut file, self.width, self.height);
184 encoder.set_color(if self.rgb {
185 png::ColorType::Rgb
186 } else {
187 png::ColorType::Grayscale
188 });
189 let data: Vec<u8> = match &self.samples {
190 Samples::Eight(v) => {
191 encoder.set_depth(png::BitDepth::Eight);
192 v.to_vec()
193 }
194 Samples::Sixteen(v) => {
195 encoder.set_depth(png::BitDepth::Sixteen);
196 v.iter().flat_map(|s| s.to_be_bytes()).collect()
198 }
199 };
200 let mut writer = encoder.write_header().map_err(failed)?;
201 if let Some(bits) = self.significant {
202 let channels = if self.rgb { 3 } else { 1 };
204 writer
205 .write_chunk(png::chunk::sBIT, &[bits; 3][..channels])
206 .map_err(failed)?;
207 }
208 writer.write_image_data(&data).map_err(failed)?;
209 writer.finish().map_err(failed)?;
210 Ok(file)
211 }
212
213 fn tiff(&self) -> Result<Vec<u8>, ImageIoError> {
214 use tiff::encoder::{TiffEncoder, colortype};
215 let failed = |e: tiff::TiffError| ImageIoError::Encode(Box::new(e));
216 let mut file = Cursor::new(Vec::new());
217 let mut encoder = TiffEncoder::new(&mut file).map_err(failed)?;
218 let (w, h) = (self.width, self.height);
219 match (&self.samples, self.rgb) {
220 (Samples::Eight(v), false) => encoder.write_image::<colortype::Gray8>(w, h, v),
221 (Samples::Eight(v), true) => encoder.write_image::<colortype::RGB8>(w, h, v),
222 (Samples::Sixteen(v), false) => encoder.write_image::<colortype::Gray16>(w, h, v),
223 (Samples::Sixteen(v), true) => encoder.write_image::<colortype::RGB16>(w, h, v),
224 }
225 .map_err(failed)?;
226 Ok(file.into_inner())
227 }
228}
229
230fn scale(samples: &[u16], bits: u8) -> Vec<u16> {
233 if bits >= 16 {
234 return samples.to_vec();
235 }
236 let open = 16 - u32::from(bits);
237 samples
238 .iter()
239 .map(|&v| (v << open) | (v >> (u32::from(bits) - open)))
240 .collect()
241}
242
243#[cfg(test)]
244mod tests {
245 use std::io::Cursor;
246
247 use bytes::Bytes;
248 use viva_pfnc::PixelFormat;
249
250 use super::*;
251
252 fn frame(format: PixelFormat, width: u32, height: u32, payload: &[u8]) -> Frame {
253 Frame::new(Bytes::copy_from_slice(payload), width, height, format)
254 }
255
256 fn read_png(file: &[u8]) -> (png::ColorType, png::BitDepth, Option<Vec<u8>>, Vec<u8>) {
258 let mut reader = png::Decoder::new(Cursor::new(file)).read_info().unwrap();
259 let info = reader.info();
260 let (colour, depth) = (info.color_type, info.bit_depth);
261 let sbit = info.sbit.as_ref().map(|s| s.to_vec());
262 let mut buf = vec![0; reader.output_buffer_size().unwrap()];
263 let out = reader.next_frame(&mut buf).unwrap();
264 buf.truncate(out.buffer_size());
265 (colour, depth, sbit, buf)
266 }
267
268 #[test]
273 fn mono12_is_a_16_bit_grey_png_with_its_depth_in_sbit() {
274 let file = encode_frame(
275 &frame(PixelFormat::Mono12p, 2, 1, &[0xBC, 0x3A, 0x12]),
276 ImageFormat::Png,
277 )
278 .unwrap();
279 let (colour, depth, sbit, samples) = read_png(&file);
280 assert_eq!(
281 (colour, depth),
282 (png::ColorType::Grayscale, png::BitDepth::Sixteen)
283 );
284 assert_eq!(sbit, Some(vec![12]));
285 assert_eq!(samples, [0xAB, 0xCA, 0x12, 0x31]);
286 }
287
288 #[test]
290 fn bayer12_is_a_16_bit_rgb_png() {
291 let mut payload = Vec::new();
293 for y in 0..4 {
294 for x in 0..4 {
295 let v: u16 = match (x % 2, y % 2) {
296 (0, 0) => 0xC8F,
297 (1, 1) => 0x323,
298 _ => 0x64A,
299 };
300 payload.extend_from_slice(&v.to_le_bytes());
301 }
302 }
303 let file = encode_frame(
304 &frame(PixelFormat::BayerRG12, 4, 4, &payload),
305 ImageFormat::Png,
306 )
307 .unwrap();
308 let (colour, depth, sbit, samples) = read_png(&file);
309 assert_eq!(
310 (colour, depth),
311 (png::ColorType::Rgb, png::BitDepth::Sixteen)
312 );
313 assert_eq!(sbit, Some(vec![12, 12, 12]));
314 let at = (4 + 1) * 3 * 2;
318 assert_eq!(&samples[at..at + 6], [0xC8, 0xFC, 0x64, 0xA6, 0x32, 0x33]);
319 }
320
321 #[test]
323 fn whole_byte_depths_are_written_as_they_are() {
324 let file = encode_frame(
325 &frame(PixelFormat::Mono8, 2, 1, &[7, 250]),
326 ImageFormat::Png,
327 )
328 .unwrap();
329 assert_eq!(
330 read_png(&file),
331 (
332 png::ColorType::Grayscale,
333 png::BitDepth::Eight,
334 None,
335 vec![7, 250]
336 )
337 );
338 let file = encode_frame(
339 &frame(PixelFormat::Mono16, 1, 1, &[0x34, 0x12]),
340 ImageFormat::Png,
341 )
342 .unwrap();
343 assert_eq!(
344 read_png(&file),
345 (
346 png::ColorType::Grayscale,
347 png::BitDepth::Sixteen,
348 None,
349 vec![0x12, 0x34]
350 )
351 );
352 let file = encode_frame(
353 &frame(PixelFormat::BGR8Packed, 1, 1, &[1, 2, 3]),
354 ImageFormat::Png,
355 )
356 .unwrap();
357 assert_eq!(
358 read_png(&file),
359 (
360 png::ColorType::Rgb,
361 png::BitDepth::Eight,
362 None,
363 vec![3, 2, 1]
364 )
365 );
366 }
367
368 #[test]
369 fn colour_can_be_asked_for() {
370 let pixels = viva_pfnc::convert::full_depth(PixelFormat::Mono8, 1, 1, None, &[9]).unwrap();
371 let file = encode(&pixels.into_rgb(), 1, 1, ImageFormat::Png).unwrap();
372 assert_eq!(
373 read_png(&file),
374 (
375 png::ColorType::Rgb,
376 png::BitDepth::Eight,
377 None,
378 vec![9, 9, 9]
379 )
380 );
381 }
382
383 #[test]
385 fn mono12_is_a_16_bit_grey_tiff() {
386 let file = encode_frame(
387 &frame(PixelFormat::Mono12p, 2, 1, &[0xBC, 0x3A, 0x12]),
388 ImageFormat::Tiff,
389 )
390 .unwrap();
391 let mut decoder = tiff::decoder::Decoder::new(Cursor::new(file)).unwrap();
392 assert_eq!(decoder.dimensions().unwrap(), (2, 1));
393 assert_eq!(decoder.colortype().unwrap(), tiff::ColorType::Gray(16));
394 let mut image = tiff::decoder::DecodingResult::U16(Vec::new());
395 decoder.read_image_to_buffer(&mut image).unwrap();
396 let tiff::decoder::DecodingResult::U16(samples) = image else {
397 panic!("16-bit samples expected");
398 };
399 assert_eq!(samples, [0xABCA, 0x1231]);
400 }
401
402 #[test]
403 fn rgb_is_an_8_bit_rgb_tiff() {
404 let file = encode_frame(
405 &frame(PixelFormat::BGR8Packed, 1, 1, &[1, 2, 3]),
406 ImageFormat::Tiff,
407 )
408 .unwrap();
409 let mut decoder = tiff::decoder::Decoder::new(Cursor::new(file)).unwrap();
410 assert_eq!(decoder.colortype().unwrap(), tiff::ColorType::RGB(8));
411 let mut image = tiff::decoder::DecodingResult::U8(Vec::new());
412 decoder.read_image_to_buffer(&mut image).unwrap();
413 assert!(matches!(image, tiff::decoder::DecodingResult::U8(v) if v == [3, 2, 1]));
414 }
415
416 #[test]
417 fn the_format_comes_from_the_extension() {
418 for (path, format) in [
419 ("a.png", Some(ImageFormat::Png)),
420 ("dir/b.PNG", Some(ImageFormat::Png)),
421 ("c.tif", Some(ImageFormat::Tiff)),
422 ("d.tiff", Some(ImageFormat::Tiff)),
423 ("e.pgm", None),
424 ("f", None),
425 ] {
426 assert_eq!(ImageFormat::from_path(Path::new(path)), format, "{path}");
427 }
428 }
429
430 #[test]
431 fn an_unconvertible_frame_is_an_error() {
432 assert!(matches!(
433 encode_frame(
434 &frame(PixelFormat::Coord3DC32f, 1, 1, &[0; 4]),
435 ImageFormat::Png
436 ),
437 Err(ImageIoError::Convert(_))
438 ));
439 }
440}