1mod color;
17mod downscale;
18mod jpeg;
19mod options;
20mod png;
21mod read;
22mod webp;
23
24#[cfg(test)]
25mod tests;
26
27pub use options::{
28 AlphaMode, ColorPolicy, Downscale, HdrPolicy, ImageFormat, ImageOptions, PngCompression,
29 SampleDepth, YuvRange,
30};
31
32use std::{
33 io::{self, Write},
34 marker::PhantomData,
35};
36
37use self::{
38 color::Sample,
39 downscale::{reduced, Downscaler},
40 options::AlphaChannel,
41 read::{Reader, Sink},
42};
43use crate::frames::{PlaneRoles, RgbOrder, VideoPartsExt};
44use crate::{
45 color_info, frames::VideoParts, ColorInfo, ColorPrimaries, Error, PixelFormat, Result,
46 TransferFunction, YuvMatrix,
47};
48
49pub(crate) struct Source<'a> {
51 width: u32,
52 height: u32,
53 format: PixelFormat,
54 planes: PlaneRoles<'a>,
55 aspect: crate::PictureAspectRatio,
56 metadata: color_info::Metadata<'a>,
57}
58
59impl<'a> Source<'a> {
60 pub(crate) fn new<F: VideoParts + ?Sized>(frame: &'a F) -> Self {
61 let layout = frame.layout();
62 Self {
63 width: layout.width(),
64 height: layout.height(),
65 format: layout.pixel_format(),
66 planes: frame.plane_roles(),
67 aspect: frame.header().picture_aspect_ratio(),
68 metadata: frame.color_metadata(),
69 }
70 }
71}
72
73#[derive(Default)]
84pub struct ImageWorkspace {
85 row: Vec<u8>,
86 image: Vec<u8>,
87 sums8: Vec<[u32; 4]>,
88 sums16: Vec<[u64; 4]>,
89 output_hint: Option<OutputHint>,
90}
91
92#[derive(Debug, Clone, Copy)]
93struct OutputHint {
94 format: ImageFormat,
95 length: usize,
96}
97
98impl std::fmt::Debug for ImageWorkspace {
99 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
100 f.debug_struct("ImageWorkspace")
101 .field("retained_bytes", &self.retained_bytes())
102 .field("output_hint", &self.output_hint)
103 .finish()
104 }
105}
106
107impl ImageWorkspace {
108 pub fn new() -> Self {
110 Self::default()
111 }
112
113 pub fn retained_bytes(&self) -> usize {
115 self.row.capacity()
116 + self.image.capacity()
117 + self.sums8.capacity() * std::mem::size_of::<[u32; 4]>()
118 + self.sums16.capacity() * std::mem::size_of::<[u64; 4]>()
119 }
120
121 pub fn release(&mut self) {
123 *self = Self::new();
124 }
125
126 pub fn encode<F: crate::VideoSource + ?Sized>(
131 &mut self,
132 frame: &F,
133 options: &ImageOptions,
134 ) -> Result<Vec<u8>> {
135 self.encode_source(Source::new(frame), options)
136 }
137
138 pub fn encode_to<F: crate::VideoSource + ?Sized, W: Write>(
159 &mut self,
160 frame: &F,
161 options: &ImageOptions,
162 mut out: W,
163 ) -> Result<()> {
164 let source = Source::new(frame);
165 let plan = Plan::new(&source, options)?;
166 write_image(plan, &mut out, self)
167 }
168
169 pub fn encode_data_url<F: crate::VideoSource + ?Sized>(
173 &mut self,
174 frame: &F,
175 options: &ImageOptions,
176 ) -> Result<String> {
177 let image = self.encode(frame, options)?;
178 Ok(data_url(&image, options.format))
179 }
180
181 fn encode_source(&mut self, source: Source<'_>, options: &ImageOptions) -> Result<Vec<u8>> {
182 let plan = Plan::new(&source, options)?;
183 if let Codec::WebpLossy(settings) = plan.codec {
185 return plan.encode_lossy_webp(settings, self);
186 }
187 let shape = plan.shape();
188 let cap = shape
191 .row_bytes
192 .saturating_mul(shape.height as usize)
193 .saturating_mul(2)
194 .saturating_add(1024);
195 let hint = self
196 .output_hint
197 .filter(|hint| hint.format == options.format)
198 .map_or(0, |hint| hint.length.min(cap));
199 let mut image = OutputBuffer {
200 bytes: Vec::new(),
201 hint,
202 };
203 write_image(plan, &mut image, self)?;
204 self.output_hint = Some(OutputHint {
205 format: options.format,
206 length: image.bytes.len(),
207 });
208 Ok(image.bytes)
209 }
210}
211
212struct OutputBuffer {
216 bytes: Vec<u8>,
217 hint: usize,
218}
219impl Write for OutputBuffer {
220 fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
221 if !bytes.is_empty() && self.hint != 0 {
222 self.bytes.reserve_exact(std::mem::take(&mut self.hint));
223 }
224 self.bytes.write(bytes)
225 }
226 fn flush(&mut self) -> io::Result<()> {
227 Ok(())
228 }
229}
230
231pub(crate) fn encode_to(
233 source: Source<'_>,
234 options: &ImageOptions,
235 out: &mut dyn Write,
236) -> Result<()> {
237 let plan = Plan::new(&source, options)?;
238 write_image(plan, out, &mut ImageWorkspace::new())
239}
240
241fn write_image(plan: Plan<'_>, out: &mut dyn Write, workspace: &mut ImageWorkspace) -> Result<()> {
242 let mut out = KeepError { out, error: None };
243 let result = match plan.codec {
244 Codec::Png {
245 shape,
246 compression,
247 cicp,
248 density,
249 } => match shape.depth {
250 SampleDepth::Eight => plan.with_pixels::<u8, _>(&mut workspace.sums8, |pixels| {
251 png::encode(
252 pixels,
253 shape,
254 compression,
255 cicp,
256 density,
257 &mut out,
258 &mut workspace.row,
259 )
260 }),
261 SampleDepth::Sixteen => plan.with_pixels::<u16, _>(&mut workspace.sums16, |pixels| {
262 png::encode(
263 pixels,
264 shape,
265 compression,
266 cicp,
267 density,
268 &mut out,
269 &mut workspace.row,
270 )
271 }),
272 },
273 Codec::Jpeg {
274 quality,
275 dimensions,
276 density,
277 } => plan.with_pixels::<u8, _>(&mut workspace.sums8, |pixels| {
278 jpeg::encode(
279 pixels,
280 quality,
281 dimensions,
282 density,
283 &mut workspace.row,
284 &mut out,
285 )
286 }),
287 Codec::WebpLossless { shape } => plan
288 .with_pixels::<u8, _>(&mut workspace.sums8, |pixels| {
289 webp::encode_lossless(pixels, shape, &mut out, &mut workspace.image)
290 }),
291 Codec::WebpLossy(settings) => plan
292 .encode_lossy_webp(settings, workspace)
293 .and_then(|image| out.write_all(&image).map_err(Error::Io)),
294 };
295 let result = result.and_then(|()| out.flush().map_err(Error::Io));
296 match out.error {
297 Some(error) => Err(Error::Io(error)),
298 None => result,
299 }
300}
301
302struct KeepError<'w> {
304 out: &'w mut dyn Write,
305 error: Option<io::Error>,
306}
307
308impl KeepError<'_> {
309 fn keep(&mut self, error: io::Error) -> io::Error {
310 if error.kind() == io::ErrorKind::Interrupted {
312 return error;
313 }
314 let copy = io::Error::new(error.kind(), error.to_string());
315 self.error.get_or_insert(error);
316 copy
317 }
318}
319
320impl Write for KeepError<'_> {
321 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
322 self.out.write(buf).map_err(|error| self.keep(error))
323 }
324
325 fn flush(&mut self) -> io::Result<()> {
326 self.out.flush().map_err(|error| self.keep(error))
327 }
328}
329
330pub(crate) fn encode(source: Source<'_>, options: &ImageOptions) -> Result<Vec<u8>> {
332 ImageWorkspace::new().encode_source(source, options)
333}
334
335#[cfg(test)]
336std::thread_local! {
337 static FAIL_SCRATCH_RESERVATION: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
338}
339
340fn resize_scratch<T: Default + Clone>(scratch: &mut Vec<T>, len: usize) -> Result<()> {
342 let unavailable = || {
343 crate::error::allocation_failed(
344 crate::AllocationKind::ImageScratch,
345 len.checked_mul(size_of::<T>()),
346 )
347 };
348 #[cfg(test)]
349 if len > scratch.capacity() && FAIL_SCRATCH_RESERVATION.with(|fail| fail.replace(false)) {
350 return Err(unavailable());
351 }
352 scratch
353 .try_reserve_exact(len.saturating_sub(scratch.len()))
354 .map_err(|_| unavailable())?;
355 scratch.resize(len, T::default());
356 Ok(())
357}
358
359pub(crate) fn encode_data_url(source: Source<'_>, options: &ImageOptions) -> Result<String> {
362 let image = encode(source, options)?;
363 Ok(data_url(&image, options.format))
364}
365
366fn data_url(image: &[u8], format: ImageFormat) -> String {
367 use base64::{engine::general_purpose::STANDARD, Engine};
368 let media_type = format.info().media_type;
369 #[expect(
370 clippy::expect_used,
371 reason = "a Vec's length is bounded by isize::MAX, so its padded base64 length fits usize"
372 )]
373 let encoded_len =
374 base64::encoded_len(image.len(), true).expect("the base64 of a Vec's bytes fits in usize");
375 let mut url = String::with_capacity("data:;base64,".len() + media_type.len() + encoded_len);
376 url.push_str("data:");
377 url.push_str(media_type);
378 url.push_str(";base64,");
379 STANDARD.encode_string(image, &mut url);
380 url
381}
382
383struct Plan<'a> {
387 source: &'a Source<'a>,
388 codec: Codec,
389 matrix: YuvMatrix,
390 range: YuvRange,
391 alpha: bool,
392 shift: u32,
393}
394
395#[derive(Debug, Clone, Copy, PartialEq, Eq)]
396enum Channels {
397 Rgb,
398 Rgba,
399}
400
401impl Channels {
402 const fn count(self) -> usize {
403 match self {
404 Self::Rgb => 3,
405 Self::Rgba => 4,
406 }
407 }
408
409 const fn from_alpha(alpha: bool) -> Self {
410 if alpha {
411 Self::Rgba
412 } else {
413 Self::Rgb
414 }
415 }
416}
417
418#[derive(Debug, Clone, Copy, PartialEq, Eq)]
420struct ImageShape {
421 width: u32,
422 height: u32,
423 channels: Channels,
424 depth: SampleDepth,
425 row_bytes: usize,
426}
427
428impl ImageShape {
429 fn new(width: u32, height: u32, channels: Channels, depth: SampleDepth) -> Self {
430 let row_bytes = width as usize * channels.count() * depth.bytes();
433 Self {
434 width,
435 height,
436 channels,
437 depth,
438 row_bytes,
439 }
440 }
441}
442
443#[derive(Debug, Clone, Copy, PartialEq, Eq)]
445struct BufferedImageShape {
446 rows: ImageShape,
447 image_bytes: usize,
448}
449
450impl BufferedImageShape {
451 fn new(limit: usize, width: u32, height: u32, channels: Channels) -> Result<Self> {
452 for (dimension, length) in [
453 (crate::ImageAxisKind::Width, width as usize),
454 (crate::ImageAxisKind::Height, height as usize),
455 ] {
456 if length > limit {
457 return Err(Error::InvalidFrame(crate::FrameDefect::ImageDimension {
458 codec: crate::ImageCodecKind::Webp,
459 dimension,
460 length,
461 maximum: limit,
462 }));
463 }
464 }
465 let rows = ImageShape::new(width, height, channels, SampleDepth::Eight);
466 Ok(Self {
469 rows,
470 image_bytes: rows.row_bytes * height as usize,
471 })
472 }
473}
474
475#[derive(Debug, Clone, Copy, PartialEq, Eq)]
479struct PixelDensity {
480 x: u16,
481 y: u16,
482}
483impl PixelDensity {
484 fn for_source(source: &Source<'_>, width: u32, height: u32) -> Option<Self> {
485 let aspect = f64::from(source.aspect.get());
486 let source_pixel_aspect = aspect * source.height as f64 / source.width as f64;
489 let aspect =
490 if aspect == 0.0 || (source_pixel_aspect - 1.0).abs() <= f64::from(f32::EPSILON) {
491 source.width as f64 / source.height as f64
492 } else {
493 aspect
494 };
495 let pixel_aspect = aspect * height as f64 / width as f64;
499 if (pixel_aspect - 1.0).abs() <= f64::from(f32::EPSILON) {
500 return None;
501 }
502 Some(Self::nearest(pixel_aspect))
503 }
504
505 fn nearest(pixel_aspect: f64) -> Self {
506 const MAX: u32 = u16::MAX as u32;
507 if pixel_aspect >= f64::from(MAX) {
508 return Self { x: 1, y: u16::MAX };
509 }
510 if pixel_aspect <= f64::from(MAX).recip() {
511 return Self { x: u16::MAX, y: 1 };
512 }
513
514 const SCALE: u128 = 1 << (f64::MANTISSA_DIGITS - 1 + u16::BITS);
519 let numerator = (pixel_aspect * SCALE as f64) as u128;
520 let (mut dividend, mut divisor) = (numerator, SCALE);
521 let (mut previous, mut current) = ((1u32, 0u32), (0u32, 1u32));
522 let (x, y) = loop {
523 let term = dividend / divisor;
524 let limit_x = (MAX - previous.0).checked_div(current.0).unwrap_or(MAX);
525 let limit_y = (MAX - previous.1).checked_div(current.1).unwrap_or(MAX);
526 let step = term.min(u128::from(limit_x.min(limit_y))) as u32;
527 let next = (previous.0 + step * current.0, previous.1 + step * current.1);
528 if u128::from(step) < term {
529 let error = |(x, y)| (numerator * u128::from(x)).abs_diff(SCALE * u128::from(y));
534 break if error(next) * u128::from(current.0) < error(current) * u128::from(next.0) {
535 next
536 } else {
537 current
538 };
539 }
540 let remainder = dividend - u128::from(step) * divisor;
541 if remainder == 0 {
542 break next;
543 }
544 (previous, current) = (current, next);
545 (dividend, divisor) = (divisor, remainder);
546 };
547 Self {
548 x: x as u16,
549 y: y as u16,
550 }
551 }
552}
553
554#[derive(Debug, Clone, Copy, PartialEq, Eq)]
556enum Codec {
557 Png {
558 shape: ImageShape,
559 compression: PngCompression,
560 cicp: Option<Cicp>,
562 density: Option<PixelDensity>,
563 },
564 Jpeg {
565 quality: jpeg::JpegQuality,
566 dimensions: jpeg::JpegDimensions,
567 density: Option<PixelDensity>,
568 },
569 WebpLossless { shape: BufferedImageShape },
571 WebpLossy(webp::LossySettings),
573}
574
575enum CodecSettings {
577 Png,
578 Jpeg(jpeg::JpegQuality),
579 WebpLossless,
580 WebpLossy(webp::WebpQuality, webp::WebpEffort),
581}
582impl CodecSettings {
583 fn new(options: &ImageOptions) -> Result<Self> {
584 Ok(match options.format {
585 ImageFormat::Png => Self::Png,
586 ImageFormat::Jpeg(quality) => Self::Jpeg(jpeg::JpegQuality::new(quality)?),
587 ImageFormat::WebpLossless => Self::WebpLossless,
588 ImageFormat::WebpLossy(quality) => Self::WebpLossy(
589 webp::WebpQuality::new(quality)?,
590 webp::WebpEffort::new(options.webp_effort)?,
591 ),
592 })
593 }
594}
595
596impl<'a> Plan<'a> {
597 fn new(source: &'a Source<'a>, options: &ImageOptions) -> Result<Self> {
600 let info = options.format.info();
601 let settings = CodecSettings::new(options)?;
602 let depth = options.depth;
603 if depth == SampleDepth::Sixteen && !info.sixteen_bit {
604 return Err(Error::InvalidInput(
605 crate::InputDefect::SixteenBitNeedsPng { codec: info.codec },
606 ));
607 }
608
609 let color = match options.color {
612 ColorPolicy::Sdk => source.metadata.read()?,
613 ColorPolicy::Override { .. } => source.metadata.read().ok().flatten(),
614 };
615 if let HdrPolicy::Refuse = options.hdr {
616 if let Some(transfer) = color
617 .and_then(|color| color.transfer())
618 .filter(|transfer| transfer.is_hdr())
619 {
620 return Err(Error::InvalidFrame(crate::FrameDefect::HdrRefused {
621 transfer,
622 }));
623 }
624 }
625 let cicp = color.as_ref().and_then(required_color_tag);
626 if let Some(tag) = cicp.filter(|_| !info.carries_color_tag) {
627 return Err(Error::InvalidInput(crate::InputDefect::ColorTagNeedsPng {
628 codec: info.codec,
629 primaries: tag.primaries,
630 transfer: tag.transfer,
631 }));
632 }
633 let (matrix, range) = match options.color {
634 ColorPolicy::Sdk => (
635 color
636 .and_then(|color| color.matrix())
637 .unwrap_or(YuvMatrix::Bt709),
638 YuvRange::Limited,
639 ),
640 ColorPolicy::Override { matrix, range } => (matrix, range),
641 };
642
643 let shift = options.downscale.shift();
644 let (width, height) = (
645 source.width.div_ceil(1 << shift),
646 source.height.div_ceil(1 << shift),
647 );
648 let alpha = info.alpha != AlphaChannel::None
649 && options.alpha.keeps_alpha()
650 && source.format.info().has_alpha();
651 let channels = match info.alpha {
652 AlphaChannel::None | AlphaChannel::Optional => Channels::from_alpha(alpha),
653 AlphaChannel::AlwaysRgba => Channels::Rgba,
654 };
655 let density = info
656 .aspect_tag
657 .then(|| PixelDensity::for_source(source, width, height))
658 .flatten();
659 let codec = match settings {
662 CodecSettings::Png => Codec::Png {
663 shape: ImageShape::new(width, height, channels, depth),
664 compression: options.png_compression,
665 cicp,
666 density,
667 },
668 CodecSettings::Jpeg(quality) => Codec::Jpeg {
669 quality,
670 dimensions: jpeg::JpegDimensions::new(width as usize, height as usize)?,
671 density,
672 },
673 CodecSettings::WebpLossless => Codec::WebpLossless {
674 shape: BufferedImageShape::new(
675 webp::MAX_LOSSLESS_DIMENSION,
676 width,
677 height,
678 channels,
679 )?,
680 },
681 CodecSettings::WebpLossy(quality, effort) => Codec::WebpLossy(webp::LossySettings {
682 shape: BufferedImageShape::new(webp::MAX_LOSSY_DIMENSION, width, height, channels)?,
683 quality,
684 effort,
685 sharp_yuv: options.webp_sharp_yuv,
686 }),
687 };
688 Ok(Self {
689 source,
690 codec,
691 matrix,
692 range,
693 alpha,
694 shift,
695 })
696 }
697
698 fn shape(&self) -> ImageShape {
699 match self.codec {
700 Codec::Png { shape, .. } => shape,
701 Codec::Jpeg { dimensions, .. } => dimensions.shape(),
702 Codec::WebpLossless { shape } => shape.rows,
703 Codec::WebpLossy(settings) => settings.shape.rows,
704 }
705 }
706
707 fn encode_lossy_webp(
708 &self,
709 settings: webp::LossySettings,
710 workspace: &mut ImageWorkspace,
711 ) -> Result<Vec<u8>> {
712 self.with_pixels::<u8, _>(&mut workspace.sums8, |pixels| {
713 webp::encode_lossy(pixels, settings, &mut workspace.image)
714 })
715 }
716
717 #[cfg(test)]
718 fn channels(&self) -> Channels {
719 self.shape().channels
720 }
721
722 fn with_pixels<P: Sample, T>(
726 &self,
727 sums: &mut Vec<[P::Sum; 4]>,
728 encode: impl FnOnce(&mut Pixels<'_, P>) -> Result<T>,
729 ) -> Result<T> {
730 let reader = Reader::new(self.source, self.matrix, self.range, self.alpha);
731 let downscaler = if self.shift > 0 {
732 resize_scratch(sums, reduced(reader.width(), self.shift))?;
733 Some(Downscaler::with_sums(
734 &reader,
735 self.shift,
736 std::mem::take(sums),
737 ))
738 } else {
739 None
740 };
741 let mut pixels = Pixels { reader, downscaler };
742 let result = encode(&mut pixels);
743 if let Some(downscaler) = pixels.downscaler {
744 *sums = downscaler.into_sums();
745 }
746 result
747 }
748
749 #[cfg(test)]
751 fn pixels<P: Sample>(&self) -> Pixels<'a, P> {
752 let reader = Reader::new(self.source, self.matrix, self.range, self.alpha);
753 let downscaler = (self.shift > 0).then(|| Downscaler::new(&reader, self.shift));
754 Pixels { reader, downscaler }
755 }
756}
757
758#[derive(Debug, Clone, Copy, PartialEq, Eq)]
759struct Cicp {
760 primaries: Option<ColorPrimaries>,
761 transfer: Option<TransferFunction>,
762}
763
764impl Cicp {
765 fn bytes(self) -> [u8; 4] {
769 [
770 self.primaries.map_or(2, ColorPrimaries::h273_code),
771 self.transfer.map_or(1, TransferFunction::h273_code),
772 0,
773 1,
774 ]
775 }
776}
777
778fn required_color_tag(color: &ColorInfo) -> Option<Cicp> {
780 let primaries = color.primaries();
781 (primaries == Some(ColorPrimaries::Bt2020) || color.is_hdr()).then_some(Cicp {
782 primaries,
783 transfer: color.transfer(),
784 })
785}
786
787struct Pixels<'a, P: Sample> {
790 reader: Reader<'a, P>,
791 downscaler: Option<Downscaler<P>>,
792}
793
794impl<'a, P: Sample> Pixels<'a, P> {
795 #[cfg(test)]
797 fn shift(&self) -> u32 {
798 self.downscaler.as_ref().map_or(0, Downscaler::shift)
799 }
800
801 #[cfg(test)]
802 fn width(&self) -> usize {
803 reduced(self.reader.width(), self.shift())
804 }
805
806 #[cfg(test)]
807 fn height(&self) -> usize {
808 reduced(self.reader.height(), self.shift())
809 }
810
811 fn direct_rows(&self, need_alpha: bool) -> Option<(&'a [u8], RgbOrder)> {
814 if P::BYTES != 1 || self.downscaler.is_some() {
815 return None;
816 }
817 let (plane, order, alpha) = self.reader.packed_rgb()?;
818 if need_alpha && !alpha {
819 return None;
820 }
821 Some((plane.data()?, order))
822 }
823
824 fn direct_rgba(&self) -> Option<&'a [u8]> {
826 let (bytes, order) = self.direct_rows(true)?;
827 (order == RgbOrder::Rgb).then_some(bytes)
828 }
829
830 fn row(&mut self, y: usize, sink: &mut impl Sink<P>) {
832 match &mut self.downscaler {
833 Some(downscaler) => downscaler.row(&self.reader, y, sink),
834 None => self.reader.row(y, sink),
835 }
836 }
837
838 fn pack_row(&mut self, y: usize, components: Channels, row: &mut [u8]) {
841 match components {
842 Channels::Rgba => self.row(y, &mut Packed::<P, 4>::new(row)),
843 Channels::Rgb => self.row(y, &mut Packed::<P, 3>::new(row)),
844 }
845 }
846}
847
848struct Packed<'r, P, const CH: usize> {
850 row: &'r mut [u8],
851 at: usize,
853 sample: PhantomData<P>,
854}
855
856impl<'r, P: Sample, const CH: usize> Packed<'r, P, CH> {
857 fn new(row: &'r mut [u8]) -> Self {
858 Self {
859 row,
860 at: 0,
861 sample: PhantomData,
862 }
863 }
864}
865
866impl<P: Sample, const CH: usize> Sink<P> for Packed<'_, P, CH> {
867 #[inline]
868 fn put(&mut self, pixels: &[[P; 4]]) {
869 let len = pixels.len() * CH * P::BYTES;
870 P::pack::<CH>(pixels, &mut self.row[self.at..self.at + len]);
871 self.at += len;
872 }
873}