1use std::io::Cursor;
7
8use alpha2_media::{
9 CancelToken, ChromaLocation, DecodeError, DecodeEvent, DecodeRequest, DecodeResult,
10 DecodedVideoFrame, Decoder, Orientation, PixelFormat, Plane, Rect, SampleAspectRatio,
11 StreamInfo, StreamKind, frame_size_supported,
12};
13use alpha2_time::MediaTime;
14
15#[derive(Copy, Clone, Debug, Eq, Hash, PartialEq)]
17pub enum StillFormat {
18 Png,
20 Jpeg,
22 WebP,
24}
25
26impl StillFormat {
27 #[must_use]
29 pub const fn as_str(self) -> &'static str {
30 match self {
31 Self::Png => "PNG",
32 Self::Jpeg => "JPEG",
33 Self::WebP => "WebP",
34 }
35 }
36}
37
38#[must_use]
40pub fn still_format(head: &[u8]) -> Option<StillFormat> {
41 if head.starts_with(&[0xff, 0xd8, 0xff]) {
42 Some(StillFormat::Jpeg)
43 } else if head.starts_with(b"\x89PNG\r\n\x1a\n") {
44 Some(StillFormat::Png)
45 } else if head.len() >= 12 && head.starts_with(b"RIFF") && &head[8..12] == b"WEBP" {
46 Some(StillFormat::WebP)
47 } else {
48 None
49 }
50}
51
52#[derive(Copy, Clone, Debug, Eq, PartialEq)]
54pub struct StillInfo {
55 pub format: StillFormat,
57 pub width: u32,
59 pub height: u32,
61 pub orientation: Orientation,
63}
64
65#[derive(Clone, Debug, Eq, PartialEq)]
67pub struct DecodedStill {
68 pub info: StillInfo,
70 pub rgba: Vec<u8>,
72}
73
74impl DecodedStill {
75 #[must_use]
78 pub fn into_video_frame(self) -> DecodedVideoFrame {
79 let StillInfo {
80 width,
81 height,
82 orientation,
83 ..
84 } = self.info;
85 DecodedVideoFrame {
86 pts: MediaTime::ZERO,
87 dts: None,
88 duration: None,
89 visible_rect: Rect {
90 x: 0,
91 y: 0,
92 width,
93 height,
94 },
95 sample_aspect_ratio: SampleAspectRatio::default(),
96 orientation,
97 pixel_format: PixelFormat::Rgba8,
98 chroma_location: ChromaLocation::Unspecified,
99 color: None,
100 planes: vec![Plane {
101 bytes: self.rgba.into(),
102 stride: width * 4,
103 width,
104 height,
105 }],
106 }
107 }
108}
109
110pub fn probe_still(bytes: &[u8]) -> Result<StillInfo, DecodeError> {
116 let format = still_format(bytes).ok_or_else(not_a_still)?;
117 let (width, height) = contained(format, || match format {
118 StillFormat::Png => Ok(png_decoder(bytes)
119 .read_header_info()
120 .map_err(|error| png_error(&error))?
121 .size()),
122 StillFormat::Jpeg => {
123 let mut decoder = jpeg_decoder(bytes);
124 decoder.decode_headers().map_err(jpeg_error)?;
125 jpeg_size(&decoder)
126 }
127 StillFormat::WebP => Ok(webp_decoder(bytes)?.dimensions()),
128 })?;
129 check_size(format, width, height)?;
130 Ok(StillInfo {
131 format,
132 width,
133 height,
134 orientation: orientation(format, bytes),
135 })
136}
137
138pub fn decode_still(bytes: &[u8]) -> Result<DecodedStill, DecodeError> {
148 let format = still_format(bytes).ok_or_else(not_a_still)?;
149 let (width, height, rgba) = contained(format, || match format {
150 StillFormat::Png => decode_png(bytes),
151 StillFormat::Jpeg => decode_jpeg(bytes),
152 StillFormat::WebP => decode_webp(bytes),
153 })?;
154 Ok(DecodedStill {
155 info: StillInfo {
156 format,
157 width,
158 height,
159 orientation: orientation(format, bytes),
160 },
161 rgba,
162 })
163}
164
165fn contained<T>(
168 format: StillFormat,
169 decode: impl FnOnce() -> Result<T, DecodeError>,
170) -> Result<T, DecodeError> {
171 std::panic::catch_unwind(std::panic::AssertUnwindSafe(decode)).unwrap_or_else(|payload| {
172 Err(DecodeError::Adapter(format!(
173 "{}: the decoder panicked: {}",
174 format.as_str(),
175 crate::panic_text(&*payload)
176 )))
177 })
178}
179
180fn not_a_still() -> DecodeError {
181 DecodeError::Unsupported("not a PNG, JPEG or WebP picture".into())
182}
183
184fn check_size(format: StillFormat, width: u32, height: u32) -> Result<(), DecodeError> {
185 if width == 0 || height == 0 {
186 return Err(DecodeError::Adapter(format!(
187 "{}: a {width}x{height} picture is empty",
188 format.as_str()
189 )));
190 }
191 if frame_size_supported(width, height) {
192 Ok(())
193 } else {
194 Err(DecodeError::Unsupported(format!(
195 "{}: a {width}x{height} picture is larger than {} pixels or {} on a side",
196 format.as_str(),
197 alpha2_media::MAX_FRAME_PIXELS,
198 alpha2_media::MAX_FRAME_DIMENSION
199 )))
200 }
201}
202
203fn rgba_buffer(width: u32, height: u32) -> Vec<u8> {
205 vec![0; width as usize * height as usize * 4]
207}
208
209fn expand_in_place(
214 buffer: &mut [u8],
215 pixels: usize,
216 source_size: usize,
217 to_rgba: impl Fn(&[u8]) -> [u8; 4],
218) {
219 let mut convert = |index: usize| {
220 let mut source = [0; 8];
221 let start = index * source_size;
222 source[..source_size].copy_from_slice(&buffer[start..start + source_size]);
223 buffer[index * 4..index * 4 + 4].copy_from_slice(&to_rgba(&source[..source_size]));
224 };
225 if source_size >= 4 {
226 (0..pixels).for_each(&mut convert);
227 } else {
228 (0..pixels).rev().for_each(&mut convert);
229 }
230}
231
232fn png_decoder(bytes: &[u8]) -> png::Decoder<Cursor<&[u8]>> {
233 let mut decoder = png::Decoder::new(Cursor::new(bytes));
234 decoder.set_ignore_text_chunk(true);
235 decoder.set_ignore_iccp_chunk(true);
236 decoder
237}
238
239fn png_error(error: &png::DecodingError) -> DecodeError {
240 DecodeError::Adapter(format!("PNG: {error}"))
241}
242
243fn decode_png(bytes: &[u8]) -> Result<(u32, u32, Vec<u8>), DecodeError> {
244 let mut decoder = png_decoder(bytes);
245 let (width, height) = decoder
246 .read_header_info()
247 .map_err(|error| png_error(&error))?
248 .size();
249 check_size(StillFormat::Png, width, height)?;
250 decoder.set_transformations(png::Transformations::EXPAND);
251 let mut reader = decoder.read_info().map_err(|error| png_error(&error))?;
252 let (color, depth) = reader.output_color_type();
253 let channels = color.samples();
254 let sample_size = if depth == png::BitDepth::Sixteen {
255 2
256 } else {
257 1
258 };
259 let pixels = width as usize * height as usize;
260 let source_size = channels * sample_size;
261 let mut buffer = vec![0; pixels * source_size.max(4)];
262 let written = reader
263 .output_buffer_size()
264 .and_then(|written| buffer.get_mut(..written))
265 .ok_or_else(|| DecodeError::Adapter("PNG: the decoded size disagrees".into()))?;
266 let frame = reader
267 .next_frame(written)
268 .map_err(|error| png_error(&error))?;
269 if (frame.width, frame.height) != (width, height) {
271 return Err(DecodeError::Adapter(format!(
272 "PNG: a {}x{} picture in a {width}x{height} canvas",
273 frame.width, frame.height
274 )));
275 }
276 let wide = |sample: &[u8]| round_16_to_8(u16::from_be_bytes([sample[0], sample[1]]));
277 match (channels, sample_size) {
278 (4, 1) => {}
279 (3, 1) => expand_in_place(&mut buffer, pixels, 3, |p| [p[0], p[1], p[2], 255]),
280 (2, 1) => expand_in_place(&mut buffer, pixels, 2, |p| [p[0], p[0], p[0], p[1]]),
281 (1, 1) => expand_in_place(&mut buffer, pixels, 1, |p| [p[0], p[0], p[0], 255]),
282 (4, 2) => expand_in_place(&mut buffer, pixels, 8, |p| {
283 [wide(&p[0..]), wide(&p[2..]), wide(&p[4..]), wide(&p[6..])]
284 }),
285 (3, 2) => expand_in_place(&mut buffer, pixels, 6, |p| {
286 [wide(&p[0..]), wide(&p[2..]), wide(&p[4..]), 255]
287 }),
288 (2, 2) => expand_in_place(&mut buffer, pixels, 4, |p| {
289 let gray = wide(p);
290 [gray, gray, gray, wide(&p[2..])]
291 }),
292 (1, 2) => expand_in_place(&mut buffer, pixels, 2, |p| {
293 let gray = wide(p);
294 [gray, gray, gray, 255]
295 }),
296 _ => {
297 return Err(DecodeError::Unsupported(format!(
298 "PNG: {color:?} at {} bits after expansion",
299 depth as u8
300 )));
301 }
302 }
303 buffer.truncate(pixels * 4);
304 if source_size > 4 {
305 buffer.shrink_to_fit();
306 }
307 Ok((width, height, buffer))
308}
309
310fn round_16_to_8(value: u16) -> u8 {
312 u8::try_from((u32::from(value) + 128) >> 8).unwrap_or(u8::MAX)
313}
314
315fn jpeg_decoder(bytes: &[u8]) -> zune_jpeg::JpegDecoder<zune_core::bytestream::ZCursor<&[u8]>> {
316 let options = zune_core::options::DecoderOptions::default()
318 .set_max_width(usize::from(u16::MAX))
319 .set_max_height(usize::from(u16::MAX))
320 .jpeg_set_out_colorspace(zune_core::colorspace::ColorSpace::RGB);
322 zune_jpeg::JpegDecoder::new_with_options(zune_core::bytestream::ZCursor::new(bytes), options)
323}
324
325fn jpeg_error(error: zune_jpeg::errors::DecodeErrors) -> DecodeError {
326 match error {
327 zune_jpeg::errors::DecodeErrors::Unsupported(scheme) => {
328 DecodeError::Unsupported(format!("JPEG: {scheme:?}"))
329 }
330 error => DecodeError::Adapter(format!("JPEG: {error}")),
331 }
332}
333
334fn jpeg_size<T: zune_core::bytestream::ZByteReaderTrait>(
335 decoder: &zune_jpeg::JpegDecoder<T>,
336) -> Result<(u32, u32), DecodeError> {
337 let malformed = || DecodeError::Adapter("JPEG: no frame header".into());
338 let (width, height) = decoder.dimensions().ok_or_else(malformed)?;
339 let side = |value: usize| u32::try_from(value).map_err(|_| malformed());
340 Ok((side(width)?, side(height)?))
341}
342
343fn decode_jpeg(bytes: &[u8]) -> Result<(u32, u32, Vec<u8>), DecodeError> {
344 let mut decoder = jpeg_decoder(bytes);
345 decoder.decode_headers().map_err(jpeg_error)?;
346 let (width, height) = jpeg_size(&decoder)?;
347 check_size(StillFormat::Jpeg, width, height)?;
348 let mut rgba = rgba_buffer(width, height);
349 let pixels = width as usize * height as usize;
350 decoder
351 .decode_into(&mut rgba[..pixels * 3])
352 .map_err(jpeg_error)?;
353 expand_in_place(&mut rgba, pixels, 3, |p| [p[0], p[1], p[2], 255]);
354 Ok((width, height, rgba))
355}
356
357fn webp_error(error: image_webp::DecodingError) -> DecodeError {
358 match error {
359 image_webp::DecodingError::UnsupportedFeature(feature) => {
360 DecodeError::Unsupported(format!("WebP: {feature}"))
361 }
362 error => DecodeError::Adapter(format!("WebP: {error}")),
363 }
364}
365
366fn webp_decoder(bytes: &[u8]) -> Result<image_webp::WebPDecoder<Cursor<&[u8]>>, DecodeError> {
368 let decoder = image_webp::WebPDecoder::new(Cursor::new(bytes)).map_err(webp_error)?;
369 if decoder.is_animated() {
370 return Err(DecodeError::Unsupported(
371 "WebP: an animated picture is not a still".into(),
372 ));
373 }
374 Ok(decoder)
375}
376
377fn decode_webp(bytes: &[u8]) -> Result<(u32, u32, Vec<u8>), DecodeError> {
378 let mut decoder = webp_decoder(bytes)?;
379 let (width, height) = decoder.dimensions();
380 check_size(StillFormat::WebP, width, height)?;
381 let mut rgba = rgba_buffer(width, height);
382 let pixels = width as usize * height as usize;
383 if decoder.has_alpha() {
384 decoder.read_image(&mut rgba).map_err(webp_error)?;
385 } else {
386 decoder
387 .read_image(&mut rgba[..pixels * 3])
388 .map_err(webp_error)?;
389 expand_in_place(&mut rgba, pixels, 3, |p| [p[0], p[1], p[2], 255]);
390 }
391 Ok((width, height, rgba))
392}
393
394fn orientation(format: StillFormat, bytes: &[u8]) -> Orientation {
396 let exif = match format {
397 StillFormat::Jpeg => jpeg_exif(bytes),
398 StillFormat::Png => png_exif(bytes),
399 StillFormat::WebP => webp_exif(bytes),
400 };
401 exif.and_then(exif_orientation)
402 .and_then(Orientation::from_exif)
403 .unwrap_or(Orientation::UPRIGHT)
404}
405
406fn jpeg_exif(bytes: &[u8]) -> Option<&[u8]> {
408 let mut at = 2;
409 loop {
410 while *bytes.get(at)? == 0xff && bytes.get(at + 1) == Some(&0xff) {
412 at += 1;
413 }
414 if *bytes.get(at)? != 0xff {
415 return None;
416 }
417 let marker = *bytes.get(at + 1)?;
418 at += 2;
419 match marker {
420 0xda | 0xd9 => return None,
422 0x01 | 0xd0..=0xd7 => continue,
424 _ => {}
425 }
426 let length = usize::from(u16::from_be_bytes([*bytes.get(at)?, *bytes.get(at + 1)?]));
427 let segment = bytes.get(at + 2..at.checked_add(length)?)?;
428 if marker == 0xe1
429 && let Some(tiff) = segment.strip_prefix(b"Exif\0\0")
430 {
431 return Some(tiff);
432 }
433 at += length;
434 }
435}
436
437fn png_exif(bytes: &[u8]) -> Option<&[u8]> {
439 let mut at = 8;
440 loop {
441 let length =
442 usize::try_from(u32::from_be_bytes(bytes.get(at..at + 4)?.try_into().ok()?)).ok()?;
443 let kind = bytes.get(at + 4..at + 8)?;
444 let data = bytes.get(at + 8..(at + 8).checked_add(length)?)?;
445 match kind {
446 b"eXIf" => return Some(data),
447 b"IEND" => return None,
448 _ => at += 12 + length,
449 }
450 }
451}
452
453fn webp_exif(bytes: &[u8]) -> Option<&[u8]> {
455 let mut at = 12;
456 loop {
457 let kind = bytes.get(at..at + 4)?;
458 let length = usize::try_from(u32::from_le_bytes(
459 bytes.get(at + 4..at + 8)?.try_into().ok()?,
460 ))
461 .ok()?;
462 let data = bytes.get(at + 8..(at + 8).checked_add(length)?)?;
463 if kind == b"EXIF" {
464 return Some(data);
465 }
466 at += 8 + length + (length & 1);
468 }
469}
470
471fn exif_orientation(tiff: &[u8]) -> Option<u16> {
476 let big_endian = match tiff.get(..4)? {
477 b"II*\0" => false,
478 b"MM\0*" => true,
479 _ => return None,
480 };
481 let u16_at = |at: usize| {
482 let bytes = tiff.get(at..at.checked_add(2)?)?.try_into().ok()?;
483 Some(if big_endian {
484 u16::from_be_bytes(bytes)
485 } else {
486 u16::from_le_bytes(bytes)
487 })
488 };
489 let u32_at = |at: usize| {
490 let bytes = tiff.get(at..at.checked_add(4)?)?.try_into().ok()?;
491 Some(if big_endian {
492 u32::from_be_bytes(bytes)
493 } else {
494 u32::from_le_bytes(bytes)
495 })
496 };
497 let ifd = usize::try_from(u32_at(4)?).ok()?;
498 let entries = usize::from(u16_at(ifd)?);
499 (0..entries).find_map(|index| {
500 let entry = ifd.checked_add(2 + index * 12)?;
501 if u16_at(entry)? != 0x0112 || u32_at(entry + 4)? != 1 {
502 return None;
503 }
504 match u16_at(entry + 2)? {
505 3 => u16_at(entry + 8),
507 4 => u16::try_from(u32_at(entry + 8)?).ok(),
509 _ => None,
510 }
511 })
512}
513
514#[derive(Debug)]
517pub struct StillStream {
518 frame: DecodedVideoFrame,
519 info: [StreamInfo; 1],
520 given: bool,
521}
522
523impl StillStream {
524 pub fn open(path: &std::path::Path) -> Result<Self, DecodeError> {
529 let bytes = std::fs::read(path).map_err(|error| DecodeError::Adapter(error.to_string()))?;
530 let still = decode_still(&bytes)?;
531 let info = StreamInfo {
532 index: 0,
533 kind: StreamKind::Video,
534 codec: still.info.format.as_str().to_lowercase(),
535 duration: None,
536 dimensions: Some((still.info.width, still.info.height)),
537 frame_rate: None,
538 sample_rate: None,
539 channels: None,
540 orientation: still.info.orientation,
541 sample_aspect_ratio: SampleAspectRatio::default(),
542 color: None,
543 frame_bytes: None,
544 alpha: None,
545 language: None,
546 title: None,
547 };
548 Ok(Self {
549 frame: still.into_video_frame(),
550 info: [info],
551 given: false,
552 })
553 }
554}
555
556impl Decoder for StillStream {
557 fn streams(&self) -> &[StreamInfo] {
558 &self.info
559 }
560
561 fn flush(&mut self) -> Result<(), DecodeError> {
562 self.given = false;
563 Ok(())
564 }
565
566 fn seek(
567 &mut self,
568 request: DecodeRequest,
569 cancel: &CancelToken,
570 ) -> Result<DecodeResult, DecodeError> {
571 if cancel.is_cancelled() {
572 return Err(DecodeError::Cancelled);
573 }
574 self.given = true;
575 Ok(DecodeResult {
576 request,
577 event: DecodeEvent::Video(self.frame.clone()),
578 })
579 }
580
581 fn decode_next(&mut self, cancel: &CancelToken) -> Result<DecodeEvent, DecodeError> {
582 if cancel.is_cancelled() {
583 return Err(DecodeError::Cancelled);
584 }
585 if std::mem::replace(&mut self.given, true) {
586 return Ok(DecodeEvent::EndOfStream);
587 }
588 Ok(DecodeEvent::Video(self.frame.clone()))
589 }
590}
591
592#[cfg(test)]
593#[path = "stills_tests.rs"]
594mod tests;