| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | |
| 11 | |
| 12 | |
| 13 | use std::io::Read; |
| 14 | use std::time::Duration; |
| 15 | |
| 16 | use crate::{DynamicImage, ImageError, ImageFormat, ImageResult, RgbaImage}; |
| 17 | |
| 18 | |
| 19 | |
| 20 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 21 | pub struct Delay { |
| 22 | numer: u32, |
| 23 | denom: u32, |
| 24 | } |
| 25 | |
| 26 | impl Delay { |
| 27 | |
| 28 | pub fn from_numer_denom_ms(numer: u32, denom: u32) -> Delay { |
| 29 | Delay { numer, denom } |
| 30 | } |
| 31 | |
| 32 | |
| 33 | pub fn numer_denom_ms(self) -> (u32, u32) { |
| 34 | (self.numer, self.denom) |
| 35 | } |
| 36 | } |
| 37 | |
| 38 | impl From<Delay> for Duration { |
| 39 | fn from(delay: Delay) -> Duration { |
| 40 | if delay.denom == 0 { |
| 41 | return Duration::ZERO; |
| 42 | } |
| 43 | Duration::from_nanos(u64::from(delay.numer) * 1_000_000 / u64::from(delay.denom)) |
| 44 | } |
| 45 | } |
| 46 | |
| 47 | |
| 48 | |
| 49 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 50 | pub struct Frame { |
| 51 | buffer: RgbaImage, |
| 52 | delay: Delay, |
| 53 | } |
| 54 | |
| 55 | impl Frame { |
| 56 | |
| 57 | |
| 58 | pub fn new(buffer: RgbaImage) -> Frame { |
| 59 | Frame { |
| 60 | buffer, |
| 61 | delay: Delay::from_numer_denom_ms(0, 1), |
| 62 | } |
| 63 | } |
| 64 | |
| 65 | |
| 66 | pub fn from_parts(buffer: RgbaImage, delay: Delay) -> Frame { |
| 67 | Frame { buffer, delay } |
| 68 | } |
| 69 | |
| 70 | |
| 71 | pub fn buffer(&self) -> &RgbaImage { |
| 72 | &self.buffer |
| 73 | } |
| 74 | |
| 75 | |
| 76 | pub fn buffer_mut(&mut self) -> &mut RgbaImage { |
| 77 | &mut self.buffer |
| 78 | } |
| 79 | |
| 80 | |
| 81 | pub fn delay(&self) -> Delay { |
| 82 | self.delay |
| 83 | } |
| 84 | } |
| 85 | |
| 86 | |
| 87 | |
| 88 | |
| 89 | |
| 90 | |
| 91 | pub struct Frames { |
| 92 | frames: std::vec::IntoIter<ImageResult<Frame>>, |
| 93 | } |
| 94 | |
| 95 | impl Iterator for Frames { |
| 96 | type Item = ImageResult<Frame>; |
| 97 | |
| 98 | fn next(&mut self) -> Option<ImageResult<Frame>> { |
| 99 | self.frames.next() |
| 100 | } |
| 101 | } |
| 102 | |
| 103 | impl Frames { |
| 104 | fn of(frames: Vec<ImageResult<Frame>>) -> Frames { |
| 105 | Frames { |
| 106 | frames: frames.into_iter(), |
| 107 | } |
| 108 | } |
| 109 | } |
| 110 | |
| 111 | |
| 112 | pub trait AnimationDecoder { |
| 113 | |
| 114 | fn into_frames(self) -> Frames; |
| 115 | } |
| 116 | |
| 117 | |
| 118 | |
| 119 | pub trait ImageDecoder { |
| 120 | |
| 121 | fn into_image(self) -> ImageResult<DynamicImage>; |
| 122 | } |
| 123 | |
| 124 | impl DynamicImage { |
| 125 | |
| 126 | pub fn from_decoder(decoder: impl ImageDecoder) -> ImageResult<DynamicImage> { |
| 127 | decoder.into_image() |
| 128 | } |
| 129 | |
| 130 | |
| 131 | pub fn into_rgba8(self) -> RgbaImage { |
| 132 | match self { |
| 133 | DynamicImage::ImageRgba8(buffer) => buffer, |
| 134 | other => other.to_rgba8(), |
| 135 | } |
| 136 | } |
| 137 | } |
| 138 | |
| 139 | |
| 140 | |
| 141 | |
| 142 | |
| 143 | pub fn guess_format(data: &[u8]) -> ImageResult<ImageFormat> { |
| 144 | crate::format_of(data).ok_or_else(|| ImageError::Unsupported("unrecognised signature".into())) |
| 145 | } |
| 146 | |
| 147 | |
| 148 | |
| 149 | |
| 150 | |
| 151 | |
| 152 | pub fn load_from_memory_with_format(data: &[u8], format: ImageFormat) -> ImageResult<DynamicImage> { |
| 153 | match crate::format_of(data) { |
| 154 | Some(found) if found == format => crate::load_from_memory(data), |
| 155 | Some(found) => Err(ImageError::Decoding(format!( |
| 156 | "asked for {format:?}, the bytes are {found:?}" |
| 157 | ))), |
| 158 | None => Err(ImageError::Unsupported("unrecognised signature".into())), |
| 159 | } |
| 160 | } |
| 161 | |
| 162 | |
| 163 | |
| 164 | fn slurp(mut reader: impl Read) -> ImageResult<Vec<u8>> { |
| 165 | let mut data = Vec::new(); |
| 166 | reader.read_to_end(&mut data)?; |
| 167 | Ok(data) |
| 168 | } |
| 169 | |
| 170 | |
| 171 | fn frames_of(data: &[u8]) -> Vec<ImageResult<Frame>> { |
| 172 | match ec_image::decode_animation(data) { |
| 173 | Err(e) => vec![Err(e.into())], |
| 174 | Ok(frames) => frames |
| 175 | .into_iter() |
| 176 | .map(|frame| { |
| 177 | let (w, h) = (frame.image.width, frame.image.height); |
| 178 | let buffer = RgbaImage::from_raw(w, h, frame.image.to_rgba8()) |
| 179 | .ok_or_else(|| ImageError::Decoding("frame plane is short".into()))?; |
| 180 | |
| 181 | Ok(Frame::from_parts( |
| 182 | buffer, |
| 183 | Delay::from_numer_denom_ms( |
| 184 | frame.delay_num.saturating_mul(1000), |
| 185 | frame.delay_den.max(1), |
| 186 | ), |
| 187 | )) |
| 188 | }) |
| 189 | .collect(), |
| 190 | } |
| 191 | } |
| 192 | |
| 193 | |
| 194 | pub mod codecs { |
| 195 | |
| 196 | pub mod gif { |
| 197 | use super::super::{AnimationDecoder, Frames, ImageDecoder, frames_of, slurp}; |
| 198 | use crate::{DynamicImage, ImageResult}; |
| 199 | |
| 200 | |
| 201 | pub struct GifDecoder { |
| 202 | data: Vec<u8>, |
| 203 | } |
| 204 | |
| 205 | impl GifDecoder { |
| 206 | |
| 207 | pub fn new(reader: impl std::io::Read) -> ImageResult<GifDecoder> { |
| 208 | Ok(GifDecoder { |
| 209 | data: slurp(reader)?, |
| 210 | }) |
| 211 | } |
| 212 | } |
| 213 | |
| 214 | impl AnimationDecoder for GifDecoder { |
| 215 | fn into_frames(self) -> Frames { |
| 216 | Frames::of(frames_of(&self.data)) |
| 217 | } |
| 218 | } |
| 219 | |
| 220 | impl ImageDecoder for GifDecoder { |
| 221 | fn into_image(self) -> ImageResult<DynamicImage> { |
| 222 | crate::load_from_memory(&self.data) |
| 223 | } |
| 224 | } |
| 225 | } |
| 226 | |
| 227 | |
| 228 | pub mod webp { |
| 229 | use super::super::{AnimationDecoder, Frames, ImageDecoder, frames_of, slurp}; |
| 230 | use crate::{DynamicImage, ImageResult, Rgba}; |
| 231 | |
| 232 | |
| 233 | pub struct WebPDecoder { |
| 234 | data: Vec<u8>, |
| 235 | } |
| 236 | |
| 237 | impl WebPDecoder { |
| 238 | |
| 239 | pub fn new(reader: impl std::io::Read) -> ImageResult<WebPDecoder> { |
| 240 | Ok(WebPDecoder { |
| 241 | data: slurp(reader)?, |
| 242 | }) |
| 243 | } |
| 244 | |
| 245 | |
| 246 | pub fn has_animation(&self) -> bool { |
| 247 | ec_image::webp::is_animated(&self.data) |
| 248 | } |
| 249 | |
| 250 | |
| 251 | |
| 252 | |
| 253 | |
| 254 | |
| 255 | |
| 256 | |
| 257 | pub fn set_background_color(&mut self, colour: Rgba) -> ImageResult<()> { |
| 258 | match colour.0 { |
| 259 | [_, _, _, 0] => Ok(()), |
| 260 | _ => Err(crate::ImageError::Unsupported( |
| 261 | "compositing animation frames onto an opaque background".into(), |
| 262 | )), |
| 263 | } |
| 264 | } |
| 265 | } |
| 266 | |
| 267 | impl AnimationDecoder for WebPDecoder { |
| 268 | fn into_frames(self) -> Frames { |
| 269 | Frames::of(frames_of(&self.data)) |
| 270 | } |
| 271 | } |
| 272 | |
| 273 | impl ImageDecoder for WebPDecoder { |
| 274 | fn into_image(self) -> ImageResult<DynamicImage> { |
| 275 | crate::load_from_memory(&self.data) |
| 276 | } |
| 277 | } |
| 278 | } |
| 279 | } |
| 280 | |
| 281 | #[cfg(test)] |
| 282 | mod tests { |
| 283 | use super::*; |
| 284 | use crate::{ImageBuffer, Rgba}; |
| 285 | use std::io::Cursor; |
| 286 | use std::path::{Path, PathBuf}; |
| 287 | |
| 288 | fn fixtures() -> PathBuf { |
| 289 | Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/stills") |
| 290 | } |
| 291 | |
| 292 | fn bytes(name: &str) -> Option<Vec<u8>> { |
| 293 | let path = fixtures().join(name); |
| 294 | if !path.exists() { |
| 295 | eprintln!("skipped: {name} not generated; run scripts/gen-still-fixtures.sh"); |
| 296 | return None; |
| 297 | } |
| 298 | Some(std::fs::read(path).expect("read fixture")) |
| 299 | } |
| 300 | |
| 301 | |
| 302 | #[test] |
| 303 | fn a_delay_converts_to_the_duration_it_names() { |
| 304 | let tenth = Delay::from_numer_denom_ms(100, 1); |
| 305 | assert_eq!(Duration::from(tenth), Duration::from_millis(100)); |
| 306 | |
| 307 | let tick = Delay::from_numer_denom_ms(10, 1); |
| 308 | assert_eq!(Duration::from(tick), Duration::from_millis(10)); |
| 309 | |
| 310 | |
| 311 | let third = Delay::from_numer_denom_ms(1, 3); |
| 312 | assert_eq!(Duration::from(third), Duration::from_nanos(333_333)); |
| 313 | assert_eq!( |
| 314 | Duration::from(Delay::from_numer_denom_ms(1, 0)), |
| 315 | Duration::ZERO |
| 316 | ); |
| 317 | } |
| 318 | |
| 319 | |
| 320 | |
| 321 | #[test] |
| 322 | fn the_gpui_gif_sequence_works() { |
| 323 | let Some(data) = bytes("animated.gif") else { |
| 324 | return; |
| 325 | }; |
| 326 | assert_eq!( |
| 327 | guess_format(&data).expect("a GIF signature"), |
| 328 | ImageFormat::Gif |
| 329 | ); |
| 330 | |
| 331 | let decoder = codecs::gif::GifDecoder::new(Cursor::new(&data)).expect("decoder"); |
| 332 | let mut frames = Vec::new(); |
| 333 | for frame in decoder.into_frames() { |
| 334 | let mut frame = frame.expect("frame"); |
| 335 | for pixel in frame.buffer_mut().chunks_exact_mut(4) { |
| 336 | pixel.swap(0, 2); |
| 337 | } |
| 338 | frames.push(frame); |
| 339 | } |
| 340 | assert!( |
| 341 | frames.len() > 1, |
| 342 | "an animation decoded to {} frame(s)", |
| 343 | frames.len() |
| 344 | ); |
| 345 | let (width, height) = frames[0].buffer().dimensions(); |
| 346 | for frame in &frames { |
| 347 | assert_eq!( |
| 348 | frame.buffer().dimensions(), |
| 349 | (width, height), |
| 350 | "frames are composited onto one canvas" |
| 351 | ); |
| 352 | assert_eq!( |
| 353 | frame.buffer().as_raw().len(), |
| 354 | (width as usize) * (height as usize) * 4 |
| 355 | ); |
| 356 | assert!( |
| 357 | Duration::from(frame.delay()) > Duration::ZERO, |
| 358 | "a frame with no delay would never advance" |
| 359 | ); |
| 360 | } |
| 361 | } |
| 362 | |
| 363 | |
| 364 | |
| 365 | #[test] |
| 366 | fn the_gpui_webp_sequence_works() { |
| 367 | let Some(still) = bytes("lossless-alpha.webp") else { |
| 368 | return; |
| 369 | }; |
| 370 | let mut decoder = codecs::webp::WebPDecoder::new(Cursor::new(&still)).expect("decoder"); |
| 371 | assert!(!decoder.has_animation()); |
| 372 | assert!(decoder.set_background_color(Rgba([0, 0, 0, 0])).is_ok()); |
| 373 | let mut data = DynamicImage::from_decoder(decoder) |
| 374 | .expect("decode") |
| 375 | .into_rgba8(); |
| 376 | for pixel in data.chunks_exact_mut(4) { |
| 377 | pixel.swap(0, 2); |
| 378 | } |
| 379 | let frames = [Frame::new(data)]; |
| 380 | assert_eq!( |
| 381 | Duration::from(frames[0].delay()), |
| 382 | Duration::ZERO, |
| 383 | "a still has no delay" |
| 384 | ); |
| 385 | |
| 386 | let Some(animated) = bytes("animated.webp") else { |
| 387 | return; |
| 388 | }; |
| 389 | let decoder = codecs::webp::WebPDecoder::new(Cursor::new(&animated)).expect("decoder"); |
| 390 | assert!(decoder.has_animation(), "an ANIM file read as a still"); |
| 391 | let frames: Vec<Frame> = decoder |
| 392 | .into_frames() |
| 393 | .map(|frame| frame.expect("frame")) |
| 394 | .collect(); |
| 395 | assert!( |
| 396 | frames.len() > 1, |
| 397 | "an animation decoded to {} frame(s)", |
| 398 | frames.len() |
| 399 | ); |
| 400 | } |
| 401 | |
| 402 | |
| 403 | |
| 404 | #[test] |
| 405 | fn the_gpui_still_and_svg_paths_work() { |
| 406 | let Some(data) = bytes("rgb8.png") else { |
| 407 | return; |
| 408 | }; |
| 409 | let format = guess_format(&data).expect("a PNG signature"); |
| 410 | assert_eq!(format, ImageFormat::Png); |
| 411 | let picture = load_from_memory_with_format(&data, format) |
| 412 | .expect("decode") |
| 413 | .into_rgba8(); |
| 414 | assert_eq!(picture.dimensions(), (320, 240)); |
| 415 | |
| 416 | |
| 417 | |
| 418 | let mut buffer = ImageBuffer::from_raw(2, 1, vec![1, 2, 3, 4, 5, 6, 7, 8]).expect("buffer"); |
| 419 | for pixel in buffer.chunks_exact_mut(4) { |
| 420 | pixel.swap(0, 2); |
| 421 | } |
| 422 | assert_eq!(buffer.as_raw(), &vec![3, 2, 1, 4, 7, 6, 5, 8]); |
| 423 | let frame = Frame::new(buffer); |
| 424 | assert_eq!(frame.buffer().dimensions(), (2, 1)); |
| 425 | } |
| 426 | |
| 427 | |
| 428 | |
| 429 | #[test] |
| 430 | fn unknown_bytes_are_an_error_so_the_caller_can_fall_through() { |
| 431 | assert!(guess_format(b"<svg xmlns=...>").is_err()); |
| 432 | let Some(data) = bytes("rgb8.png") else { |
| 433 | return; |
| 434 | }; |
| 435 | |
| 436 | assert!(load_from_memory_with_format(&data, ImageFormat::Jpeg).is_err()); |
| 437 | } |
| 438 | } |