grafton_ndi/image/options.rs
1//! What to encode and how: [`ImageOptions`] and the settings it holds.
2
3use std::ops::RangeInclusive;
4
5use super::{jpeg::JpegQuality, webp::WebpQuality};
6use crate::{Error, ImageCodecKind, ImageSettingKind, InputDefect, Result, YuvMatrix};
7
8/// The image format a video frame is encoded to.
9///
10/// # Examples
11///
12/// ```
13/// use grafton_ndi::image_encoding::ImageFormat;
14///
15/// // PNG: lossless, any bit depth, carries an HDR tag.
16/// let png = ImageFormat::Png;
17///
18/// // JPEG at quality 85: lossy, without alpha.
19/// let jpeg = ImageFormat::Jpeg(85);
20///
21/// // Lossless WebP: 8-bit color with optional alpha.
22/// let webp = ImageFormat::WebpLossless;
23///
24/// // Lossy WebP at quality 80, preserving alpha exactly.
25/// let preview = ImageFormat::WebpLossy(80);
26/// ```
27///
28/// This enum is marked `#[non_exhaustive]` so that encoders
29/// can be added without a breaking change. Match arms should
30/// include a wildcard `_` pattern.
31#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
32#[non_exhaustive]
33pub enum ImageFormat {
34 /// PNG: lossless, 8 or 16 bits a channel, with or without alpha.
35 Png,
36 /// JPEG at a quality from 1, the lowest, to 100, the highest; 8 bits a
37 /// channel and no alpha. Below 90 chroma is halved in both directions
38 /// (4:2:0). From 90 it is kept whole (4:4:4). Frames that need a color
39 /// tag require PNG. See [`HdrPolicy`].
40 Jpeg(u8),
41 /// Lossless WebP: 8 bits a channel, with or without alpha. Frames that
42 /// need a color tag require PNG. See [`HdrPolicy`].
43 WebpLossless,
44 /// Lossy WebP at a quality from 0, the lowest, to 100, the highest;
45 /// 8 bits a channel, with or without alpha. Alpha is preserved exactly.
46 /// Color uses 4:2:0 chroma sampling and, by default, SharpYUV conversion;
47 /// even quality 100 can change RGB values. Use [`Self::WebpLossless`]
48 /// for exact pixels. Frames that need a color tag require PNG. See
49 /// [`HdrPolicy`].
50 WebpLossy(u8),
51}
52
53/// Fixed codec capabilities, stated exhaustively for every format.
54#[derive(Debug, Clone, PartialEq, Eq)]
55pub(super) struct ImageFormatInfo {
56 pub(super) codec: crate::ImageCodecKind,
57 pub(super) media_type: &'static str,
58 pub(super) alpha: AlphaChannel,
59 pub(super) sixteen_bit: bool,
60 pub(super) carries_color_tag: bool,
61 pub(super) aspect_tag: bool,
62}
63
64#[derive(Debug, Clone, Copy, PartialEq, Eq)]
65pub(super) enum AlphaChannel {
66 None,
67 Optional,
68 AlwaysRgba,
69}
70
71impl ImageFormat {
72 pub(super) const fn info(self) -> ImageFormatInfo {
73 match self {
74 Self::Png => ImageFormatInfo {
75 codec: crate::ImageCodecKind::Png,
76 media_type: "image/png",
77 alpha: AlphaChannel::Optional,
78 sixteen_bit: true,
79 carries_color_tag: true,
80 aspect_tag: true,
81 },
82 Self::Jpeg(_) => ImageFormatInfo {
83 codec: crate::ImageCodecKind::Jpeg,
84 media_type: "image/jpeg",
85 alpha: AlphaChannel::None,
86 sixteen_bit: false,
87 carries_color_tag: false,
88 aspect_tag: true,
89 },
90 Self::WebpLossless => ImageFormatInfo {
91 codec: crate::ImageCodecKind::Webp,
92 media_type: "image/webp",
93 alpha: AlphaChannel::Optional,
94 sixteen_bit: false,
95 carries_color_tag: false,
96 aspect_tag: false,
97 },
98 Self::WebpLossy(_) => ImageFormatInfo {
99 codec: crate::ImageCodecKind::Webp,
100 media_type: "image/webp",
101 alpha: AlphaChannel::AlwaysRgba,
102 sixteen_bit: false,
103 carries_color_tag: false,
104 aspect_tag: false,
105 },
106 }
107 }
108
109 pub(super) fn quality(self) -> Option<(u8, RangeInclusive<u8>)> {
110 match self {
111 Self::Png | Self::WebpLossless => None,
112 Self::Jpeg(value) => Some((value, JpegQuality::RANGE)),
113 Self::WebpLossy(value) => Some((value, WebpQuality::RANGE)),
114 }
115 }
116
117 pub(super) fn validate_quality(self) -> Result<()> {
118 if let Some((value, bounds)) = self.quality() {
119 check_image_setting(self.info().codec, ImageSettingKind::Quality, value, bounds)?;
120 }
121 Ok(())
122 }
123}
124
125pub(super) fn check_image_setting(
126 codec: ImageCodecKind,
127 setting: ImageSettingKind,
128 value: u8,
129 bounds: RangeInclusive<u8>,
130) -> Result<()> {
131 if !bounds.contains(&value) {
132 return Err(Error::InvalidInput(InputDefect::ImageSetting {
133 codec,
134 setting,
135 value,
136 minimum: *bounds.start(),
137 maximum: *bounds.end(),
138 }));
139 }
140 Ok(())
141}
142
143// One list supplies representative formats and an exhaustive coverage check,
144// just as decoded_variants does for pixel formats.
145#[cfg(test)]
146macro_rules! image_format_variants {
147 ($($variant:ident $(($argument:pat))? => $sample:expr),+ $(,)?) => {
148 impl ImageFormat {
149 pub(super) const ALL: [Self; [$(stringify!($variant)),+].len()] = {
150 let variants = [$($sample),+];
151 let mut index = 0;
152 while index < variants.len() {
153 assert!(variants[index].variant_index() == index);
154 index += 1;
155 }
156 variants
157 };
158
159 const fn variant_index(self) -> usize {
160 enum Index { $($variant),+ }
161 match self { $(Self::$variant $(($argument))? => Index::$variant as usize),+ }
162 }
163 }
164 };
165}
166#[cfg(test)]
167image_format_variants!(
168 Png => ImageFormat::Png,
169 Jpeg(_) => ImageFormat::Jpeg(85),
170 WebpLossless => ImageFormat::WebpLossless,
171 WebpLossy(_) => ImageFormat::WebpLossy(75),
172);
173
174/// How a video frame is encoded as a still image: its format, color
175/// handling, bit depth, alpha, HDR policy, size and codec effort.
176///
177/// Every video frame type encodes with it, whether owned, captured or
178/// borrowed for sending, through `encode_image`, `encode_image_to` and
179/// `encode_image_data_url`, for example [`VideoFrame::encode_image`].
180/// Construct these settings with `ImageOptions::new(format)`.
181///
182/// ```
183/// use grafton_ndi::{PixelFormat, VideoFrame, YuvMatrix, image_encoding::{ColorPolicy, Downscale, ImageFormat, ImageOptions, YuvRange}};
184///
185/// let frame = VideoFrame::builder()
186/// .resolution(64, 36)
187/// .pixel_format(PixelFormat::Uyvy)
188/// .data([128, 16, 128, 16].repeat(64 * 36 / 2))
189/// .build()?;
190///
191/// // A quarter-size JPEG thumbnail.
192/// let thumbnail = ImageOptions::new(ImageFormat::Jpeg(85)).downscale(Downscale::Quarter);
193/// let jpeg = frame.encode_image(&thumbnail)?;
194///
195/// // A source known to label its color wrongly.
196/// let options = ImageOptions::new(ImageFormat::Png)
197/// .color(ColorPolicy::Override { matrix: YuvMatrix::Bt601, range: YuvRange::Limited });
198/// let png = frame.encode_image(&options)?;
199/// # assert!(jpeg.starts_with(&[0xFF, 0xD8]) && png.starts_with(b"\x89PNG"));
200/// # Ok::<(), grafton_ndi::Error>(())
201/// ```
202///
203/// PNG and JPEG preserve picture aspect in relative pixel-density tags (PNG
204/// pHYs and JPEG JFIF) whenever the output needs non-square pixels. This includes
205/// square-pixel sources whose partial downscale blocks change the stored
206/// width/height ratio. Pixel dimensions and samples are unchanged. Outputs
207/// needing square pixels retain their default density behavior; equivalent
208/// implicit and explicit square-pixel sources produce identical bytes. Viewers
209/// may ignore these tags. WebP carries no pixel-shape tag. PNG and JPEG choose
210/// the positive `u16` density pair whose vertical-to-horizontal ratio is closest
211/// to the required pixel aspect.
212///
213/// # Formats
214///
215/// Every uncompressed [`PixelFormat`](crate::PixelFormat) encodes: the four
216/// 8-bit RGB formats, and the YUV formats UYVY, UYVA, P216, PA16, NV12, I420,
217/// YV12, NA48, NB48, NA4G and NB4G, which are converted to RGB. Rows are read
218/// in place, skipping any row padding.
219///
220/// | Output | Channels | Bits a channel |
221/// |---|---|---|
222/// | PNG, [`AlphaMode::Keep`] | RGBA if the source has alpha, otherwise RGB | 8 or 16 |
223/// | PNG, [`AlphaMode::Discard`] | RGB | 8 or 16 |
224/// | JPEG | YCbCr; alpha is dropped | 8 |
225/// | Lossless WebP | RGBA if the source has alpha and it is kept, otherwise RGB | 8 |
226/// | Lossy WebP | Lossy color, exact alpha unless discarded | 8 |
227///
228/// # Color
229///
230/// By default, YUV frames use limited range and repeated chroma, with the
231/// matrix in readable `ndi_color_info` metadata ([`ColorInfo`](crate::ColorInfo)),
232/// or BT.709 when untagged. [`ColorPolicy::Override`] replaces the matrix and
233/// range. See [`ColorPolicy`] for malformed metadata handling.
234///
235/// The SDK's own YUV-to-RGB conversion always uses BT.709 limited range,
236/// whatever the tag says. RGB-received frames already carry that conversion:
237/// encoding keeps their RGB pixels, so the tag's matrix can no longer be
238/// applied. Readable tags still govern color admission and the PNG `cICP` chunk.
239/// [`ReceiverColorFormat::UyvyBgra`](crate::ReceiverColorFormat::UyvyBgra) and
240/// [`UyvyRgba`](crate::ReceiverColorFormat::UyvyRgba) keep opaque sources in
241/// YUV, but deliver BGRA or RGBA for sources with alpha. When a tagged source
242/// may carry alpha, use
243/// [`ReceiverColorFormat::Fastest`](crate::ReceiverColorFormat::Fastest) for
244/// UYVA or [`Best`](crate::ReceiverColorFormat::Best) for UYVA or PA16. `Best`
245/// also retains high bit depth and HDR code values. Both deliver individual
246/// fields even with [`allow_video_fields(false)`](crate::ReceiverOptions::allow_video_fields),
247/// so interlaced snapshots may need field assembly.
248///
249/// # HDR
250///
251/// A frame tagged with the PQ or HLG transfer function is refused unless
252/// [`HdrPolicy::CodeValues`] asks for its code values, which only PNG can
253/// carry, tagged so that an HDR-aware viewer shows them correctly. Nothing is
254/// tone-mapped. Receive YUV with
255/// [`ReceiverColorFormat::Best`](crate::ReceiverColorFormat::Best) to retain
256/// high bit depth and HDR code values: an RGB-received frame already holds
257/// the SDK's BT.709 limited-range conversion, which encoding at 16 bits cannot
258/// undo. The passed-through tag still governs color admission and the PNG
259/// `cICP` chunk. Frames with BT.2020 primaries also require tagged PNG output.
260/// See [`HdrPolicy`].
261///
262/// # Performance
263///
264/// Encoding is synchronous CPU work. Compare formats, PNG compression and
265/// lossy WebP effort on representative content at acceptable visual quality.
266/// Lower [`Self::webp_effort`] and disable [`Self::webp_sharp_yuv`] when
267/// prioritizing latency independently of quality; measure the result and bound
268/// concurrent encoding jobs. Neither setting provides a time or memory limit.
269///
270/// Async code runs the encoder on a blocking thread, with an owned frame:
271///
272/// ```no_run
273/// # async fn snapshot(frame: grafton_ndi::VideoFrame) -> Result<Vec<u8>, Box<dyn std::error::Error>> {
274/// use grafton_ndi::{image_encoding::{ImageFormat, ImageOptions}};
275///
276/// let options = ImageOptions::new(ImageFormat::WebpLossless);
277/// let webp = tokio::task::spawn_blocking(move || frame.encode_image(&options)).await??;
278/// # Ok(webp)
279/// # }
280/// ```
281///
282/// # Memory
283///
284/// PNG and JPEG convert one output row at a time, so conversion scratch
285/// does not grow with frame height. PNG borrows contiguous full-size 8-bit
286/// RGBA rows or
287/// retains one row; JPEG converts into the codec's rows and retains its
288/// final component row to avoid converting padding requests again.
289/// WebP encodes from one buffer, so it holds the whole converted
290/// image, unless full-size contiguous RGBA can be borrowed with alpha kept.
291/// Lossless WebP uses three channels when the source has no alpha or alpha is
292/// discarded. Lossy WebP uses four channels, with opaque alpha in those cases.
293/// Both WebP formats buffer the complete encoded
294/// image before writing it. Codec state and encoded output take memory besides.
295/// Each concurrent encode owns its own buffers, so worker and queue limits
296/// matter alongside compressed image size.
297///
298/// # Errors
299///
300/// Setters never fail; the encoding methods check the options with the
301/// frame, before anything is written.
302///
303/// | Problem | Error |
304/// |---|---|
305/// | A JPEG quality outside 1 to 100 | [`Error::InvalidInput`] |
306/// | A lossy WebP quality outside 0 to 100 | [`Error::InvalidInput`] |
307/// | A lossy WebP effort outside 0 to 6 | [`Error::InvalidInput`] |
308/// | JPEG or WebP with [`SampleDepth::Sixteen`] | [`Error::InvalidInput`] |
309/// | JPEG or WebP for a frame that needs a color tag (BT.2020 primaries, or PQ or HLG with [`HdrPolicy::CodeValues`]) | [`Error::InvalidInput`] |
310/// | A PQ or HLG frame with [`HdrPolicy::Refuse`] | [`Error::InvalidFrame`] |
311/// | Unreadable `ndi_color_info` with [`ColorPolicy::Sdk`] | [`Error::InvalidFrame`] |
312/// | An image wider or taller than JPEG's 65,535, lossless WebP's 16,384 or lossy WebP's 16,383 pixels | [`Error::InvalidFrame`] |
313/// | Writing or flushing the writer given to `encode_image_to` fails | [`Error::Io`] |
314/// | Conversion scratch cannot be allocated | [`Error::AllocationFailed`] |
315/// | The lossy WebP encoder cannot allocate its working storage | [`Error::InvalidFrame`] (`crate::FrameDefect::EncodingFailed`) |
316/// | The codec fails for another reason | [`Error::InvalidFrame`] |
317///
318/// `ImageOptions` holds settings only, no buffers, so one value serves any
319/// number of threads.
320///
321/// [`VideoFrame::encode_image`]: crate::VideoFrame::encode_image
322/// [`Error::InvalidInput`]: crate::Error::InvalidInput
323/// [`Error::AllocationFailed`]: crate::Error::AllocationFailed
324/// [`Error::InvalidFrame`]: crate::Error::InvalidFrame
325/// [`Error::Io`]: crate::Error::Io
326#[derive(Debug, Clone, PartialEq, Eq, Hash)]
327pub struct ImageOptions {
328 pub(super) format: ImageFormat,
329 pub(super) color: ColorPolicy,
330 pub(super) depth: SampleDepth,
331 pub(super) alpha: AlphaMode,
332 pub(super) hdr: HdrPolicy,
333 pub(super) downscale: Downscale,
334 pub(super) png_compression: PngCompression,
335 pub(super) webp_effort: u8,
336 pub(super) webp_sharp_yuv: bool,
337}
338
339impl ImageOptions {
340 /// Replace the output format, preserving every other encoding setting.
341 #[must_use]
342 pub fn format(mut self, format: ImageFormat) -> Self {
343 self.format = format;
344 self
345 }
346
347 /// Requested encoded image format.
348 #[must_use]
349 pub fn configured_format(&self) -> ImageFormat {
350 self.format
351 }
352
353 /// Requested color conversion policy.
354 #[must_use]
355 pub fn configured_color(&self) -> ColorPolicy {
356 self.color
357 }
358
359 /// Requested bits per channel.
360 #[must_use]
361 pub fn configured_depth(&self) -> SampleDepth {
362 self.depth
363 }
364
365 /// Requested alpha handling.
366 #[must_use]
367 pub fn configured_alpha(&self) -> AlphaMode {
368 self.alpha
369 }
370
371 /// Requested HDR handling.
372 #[must_use]
373 pub fn configured_hdr(&self) -> HdrPolicy {
374 self.hdr
375 }
376
377 /// Requested image downscale factor.
378 #[must_use]
379 pub fn configured_downscale(&self) -> Downscale {
380 self.downscale
381 }
382
383 /// Requested PNG compression level.
384 #[must_use]
385 pub fn configured_png_compression(&self) -> PngCompression {
386 self.png_compression
387 }
388
389 /// Requested lossy WebP compression effort (default 4).
390 #[must_use]
391 pub fn configured_webp_effort(&self) -> u8 {
392 self.webp_effort
393 }
394
395 /// Whether lossy WebP uses SharpYUV color conversion (default true).
396 #[must_use]
397 pub fn configured_webp_sharp_yuv(&self) -> bool {
398 self.webp_sharp_yuv
399 }
400
401 /// Options for `format`, with every other setting at its default:
402 /// [`ColorPolicy::Sdk`], [`SampleDepth::Eight`], [`AlphaMode::Keep`],
403 /// [`HdrPolicy::Refuse`], [`Downscale::Off`],
404 /// [`PngCompression::Balanced`], lossy WebP effort 4 and SharpYUV enabled.
405 #[must_use]
406 pub fn new(format: ImageFormat) -> Self {
407 Self {
408 format,
409 color: ColorPolicy::default(),
410 depth: SampleDepth::default(),
411 alpha: AlphaMode::default(),
412 hdr: HdrPolicy::default(),
413 downscale: Downscale::default(),
414 png_compression: PngCompression::default(),
415 webp_effort: 4,
416 webp_sharp_yuv: true,
417 }
418 }
419
420 /// Choose how YUV frames are converted to RGB. The default is
421 /// [`ColorPolicy::Sdk`].
422 #[must_use]
423 pub fn color(mut self, policy: ColorPolicy) -> Self {
424 self.color = policy;
425 self
426 }
427
428 /// Choose the bits a channel of the image: [`SampleDepth::Sixteen`]
429 /// needs [`ImageFormat::Png`]. The default is [`SampleDepth::Eight`].
430 #[must_use]
431 pub fn depth(mut self, depth: SampleDepth) -> Self {
432 self.depth = depth;
433 self
434 }
435
436 /// Choose whether a PNG or WebP image has an alpha channel. JPEG never
437 /// has one. The default is [`AlphaMode::Keep`].
438 #[must_use]
439 pub fn alpha(mut self, alpha: AlphaMode) -> Self {
440 self.alpha = alpha;
441 self
442 }
443
444 /// Choose what happens to a frame tagged PQ or HLG. The default is
445 /// [`HdrPolicy::Refuse`].
446 #[must_use]
447 pub fn hdr(mut self, hdr: HdrPolicy) -> Self {
448 self.hdr = hdr;
449 self
450 }
451
452 /// Reduce the image by 2, 4 or 8 in each direction. The default is
453 /// [`Downscale::Off`].
454 #[must_use]
455 pub fn downscale(mut self, by: Downscale) -> Self {
456 self.downscale = by;
457 self
458 }
459
460 /// Choose how hard PNG compresses. It has no effect on JPEG or WebP. The
461 /// default is [`PngCompression::Balanced`].
462 #[must_use]
463 pub fn png_compression(mut self, level: PngCompression) -> Self {
464 self.png_compression = level;
465 self
466 }
467
468 /// Choose lossy WebP's compression effort, independently of color quality:
469 /// 0 is fastest, 6 spends the most effort, and the default is 4. Higher
470 /// effort generally trades CPU time for smaller output; measure your content.
471 /// Alpha remains exact at every effort.
472 ///
473 /// Values outside 0 to 6 return [`Error::InvalidInput`](crate::Error::InvalidInput)
474 /// when encoding lossy WebP, before anything is written. This setting has
475 /// no effect on PNG, JPEG or lossless WebP.
476 #[must_use]
477 pub fn webp_effort(mut self, effort: u8) -> Self {
478 self.webp_effort = effort;
479 self
480 }
481
482 /// Choose lossy WebP's RGB-to-YUV conversion. The default, true, uses
483 /// SharpYUV for sharper chroma edges at an additional CPU cost. False
484 /// uses the faster standard conversion; alpha remains exact.
485 ///
486 /// Combine `webp_effort(0)` and `webp_sharp_yuv(false)` when prioritizing
487 /// encoding latency. Neither setting imposes a time or memory limit.
488 /// This setting has no effect on PNG, JPEG or lossless WebP.
489 #[must_use]
490 pub fn webp_sharp_yuv(mut self, enabled: bool) -> Self {
491 self.webp_sharp_yuv = enabled;
492 self
493 }
494}
495
496/// How YUV frames are converted to RGB.
497///
498/// RGB frames are encoded as they are; the policy still decides whether
499/// their `ndi_color_info` must be readable. RGB-received frames already carry
500/// the SDK's BT.709 limited-range YUV conversion, whatever that tag says.
501///
502/// This enum is marked `#[non_exhaustive]` so that policies can be added
503/// without a breaking change.
504#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
505#[non_exhaustive]
506pub enum ColorPolicy {
507 /// Convert with BT.709 and limited range, unless the frame's
508 /// `ndi_color_info` metadata names another matrix, which is then used.
509 /// An untagged source with different color encoding needs
510 /// [`ColorPolicy::Override`].
511 ///
512 /// RGB-received frames already hold the SDK's BT.709 limited-range
513 /// conversion, which ignores the tag; this policy cannot apply its matrix
514 /// afterward. Tags still govern color admission and the PNG `cICP` chunk.
515 /// See [the color guidance](ImageOptions#color) for receiving YUV when the
516 /// tag's matrix matters, including sources with alpha.
517 ///
518 /// A frame whose `ndi_color_info` cannot be read, including received
519 /// metadata withheld as non-UTF-8 or unterminated text, is refused with
520 /// [`Error::InvalidFrame`](crate::Error::InvalidFrame), so the encoder
521 /// never guesses at a frame that says something it cannot read.
522 #[default]
523 Sdk,
524 /// Convert with this matrix and range, whatever the frame says.
525 ///
526 /// The caller takes responsibility for the frame's color: unreadable
527 /// `ndi_color_info` and withheld received metadata are ignored, and the
528 /// frame then counts as SDR with
529 /// unknown primaries. Readable metadata still decides the HDR check and
530 /// a PNG's color tag.
531 Override {
532 /// The matrix that relates the frame's YCbCr to RGB.
533 matrix: YuvMatrix,
534 /// The range of the frame's code values.
535 range: YuvRange,
536 },
537}
538
539/// The range of a YUV frame's code values.
540///
541/// This enum is marked `#[non_exhaustive]` so that ranges can be added
542/// without a breaking change.
543#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
544#[non_exhaustive]
545pub enum YuvRange {
546 /// Limited, or video, range: at 8 bits, luma 16 to 235 and chroma 16 to
547 /// 240; at 16 bits, those values times 256. NDI video uses it.
548 Limited,
549 /// Full range: every code value.
550 Full,
551}
552
553/// The bits a channel of an encoded image.
554///
555/// This enum is marked `#[non_exhaustive]` so that depths can be added
556/// without a breaking change.
557#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
558#[non_exhaustive]
559pub enum SampleDepth {
560 /// 8 bits a channel, rounded from any source. Every format writes it.
561 #[default]
562 Eight,
563 /// 16 bits a channel, for PNG only. P216, PA16, NA4G and NB4G frames
564 /// keep their precision. Eight-bit RGB and alpha samples scale exactly
565 /// by 257; YUV sources are converted at 16-bit precision.
566 /// Receivers set to [`ReceiverColorFormat::Best`] or
567 /// [`ReceiverColorFormat::Best444`] get such frames from a
568 /// high-bit-depth source.
569 ///
570 /// [`ReceiverColorFormat::Best`]: crate::ReceiverColorFormat::Best
571 /// [`ReceiverColorFormat::Best444`]: crate::ReceiverColorFormat::Best444
572 Sixteen,
573}
574
575impl SampleDepth {
576 pub(super) const fn bytes(self) -> usize {
577 match self {
578 Self::Eight => 1,
579 Self::Sixteen => 2,
580 }
581 }
582}
583
584/// Whether a PNG or WebP image has an alpha channel.
585///
586/// This enum is marked `#[non_exhaustive]` so that modes can be added without
587/// a breaking change.
588#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
589#[non_exhaustive]
590pub enum AlphaMode {
591 /// Keep the source's alpha, converted to the image's depth. PNG and
592 /// lossless WebP use RGBA for a source with alpha and RGB otherwise.
593 /// Lossy WebP's encoder takes RGBA, using opaque alpha for an opaque source.
594 /// Colors are treated as straight (not premultiplied by alpha), and PNG
595 /// and WebP store straight alpha. The [SDK frame-type reference] documents
596 /// this for BGRA and RGBA. It does not specify the convention for UYVA,
597 /// PA16, NB48 or NB4G; this encoder assumes straight color for them too.
598 ///
599 /// [SDK frame-type reference]: https://docs.ndi.video/all/developing-with-ndi/sdk/frame-types
600 #[default]
601 Keep,
602 /// Write RGB, dropping any alpha.
603 Discard,
604}
605
606impl AlphaMode {
607 pub(super) const fn keeps_alpha(self) -> bool {
608 match self {
609 Self::Keep => true,
610 Self::Discard => false,
611 }
612 }
613}
614
615/// What happens to a frame whose `ndi_color_info` gives the PQ or HLG
616/// transfer function. Frames with BT.2020 primaries or either HDR transfer
617/// need a color tag, which the encoder can write only in PNG.
618///
619/// | The frame's primaries | The frame's transfer | [`HdrPolicy::Refuse`] | [`HdrPolicy::CodeValues`] |
620/// |---|---|---|---|
621/// | Unspecified, BT.601 or BT.709 | Unspecified or SDR | Every format, untagged | Every format, untagged |
622/// | BT.2020 | Unspecified or SDR | PNG, tagged | PNG, tagged |
623/// | Any | PQ or HLG | [`Error::InvalidFrame`] | PNG of the code values, tagged |
624///
625/// When PNG is required, JPEG and WebP return [`Error::InvalidInput`]
626/// with [`InputDefect::ColorTagNeedsPng`](crate::InputDefect::ColorTagNeedsPng).
627///
628/// The check applies to every pixel format, RGB as well as YUV. The encoder
629/// does not tone-map. A program that wants an SDR rendering of HDR video
630/// makes it itself, from a 16-bit PNG or from the frame, and
631/// [`color_info`](crate::VideoFrame::color_info) lets it check a frame before
632/// encoding it.
633///
634/// This enum is marked `#[non_exhaustive]` so that policies can be added
635/// without a breaking change.
636///
637/// [`Error::InvalidFrame`]: crate::Error::InvalidFrame
638/// [`Error::InvalidInput`]: crate::Error::InvalidInput
639#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
640#[non_exhaustive]
641pub enum HdrPolicy {
642 /// Refuse a PQ or HLG frame with
643 /// [`Error::InvalidFrame`](crate::Error::InvalidFrame).
644 #[default]
645 Refuse,
646 /// Write a PQ or HLG frame's non-linear code values to a PNG, tagged with
647 /// a `cICP` chunk that tells an HDR-aware viewer their primaries and
648 /// transfer function. Use [`SampleDepth::Sixteen`] to keep a
649 /// high-bit-depth frame's precision.
650 ///
651 /// RGB-received frames already contain the SDK's BT.709 limited-range
652 /// conversion, whatever `ndi_color_info` says; 16-bit output cannot recover
653 /// their original HDR code values. Receive YUV with
654 /// [`ReceiverColorFormat::Best`](crate::ReceiverColorFormat::Best) to keep
655 /// them. The tag still decides HDR refusal and the PNG `cICP` chunk.
656 ///
657 /// JPEG and WebP refuse such a frame with [`Error::InvalidInput`](crate::Error::InvalidInput).
658 CodeValues,
659}
660
661/// How much an image is reduced in each direction.
662///
663/// Reduction averages blocks of converted pixels inside the row loop, so a
664/// thumbnail of a full-size frame never holds a full-size image. The image
665/// is ceil(width / f) by ceil(height / f), where f is 2, 4 or 8; a block at
666/// the right or bottom edge averages only the pixels it has. Averages are
667/// taken on code values, as previews usually are, and round half up. With
668/// alpha kept, color is weighted by alpha, so transparent pixels do not
669/// darken edges; a block that is transparent throughout takes the plain mean.
670/// Color channels are treated as straight (not premultiplied by alpha), as
671/// the [NDI SDK](https://docs.ndi.video/all/developing-with-ndi/sdk/frame-types)
672/// documents for BGRA and RGBA. This is an encoder assumption for UYVA, PA16,
673/// NB48 and NB4G; see [`AlphaMode::Keep`].
674///
675/// It serves frames that arrive full size: from a FrameSync, from receivers
676/// with [`ReceiverOptions::high_quality_preset`], and frames being sent. A
677/// [`ReceiverOptions::snapshot_preset`] receiver already gets the source's
678/// smaller preview stream.
679///
680/// This enum is marked `#[non_exhaustive]` so that factors can be added
681/// without a breaking change.
682///
683/// [`ReceiverOptions::high_quality_preset`]: crate::ReceiverOptions::high_quality_preset
684/// [`ReceiverOptions::snapshot_preset`]: crate::ReceiverOptions::snapshot_preset
685#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
686#[non_exhaustive]
687pub enum Downscale {
688 /// Full size.
689 #[default]
690 Off,
691 /// Half the width and height: 2×2 blocks.
692 Half,
693 /// A quarter of the width and height: 4×4 blocks.
694 Quarter,
695 /// An eighth of the width and height: 8×8 blocks.
696 Eighth,
697}
698
699crate::media::decoded_variants!(Downscale: Off, Half, Quarter, Eighth);
700
701impl Downscale {
702 pub(super) const MAX_SHIFT: u32 = {
703 let mut max = 0;
704 let mut index = 0;
705 while index < Self::ALL.len() {
706 let shift = Self::ALL[index].shift();
707 if shift > max {
708 max = shift;
709 }
710 index += 1;
711 }
712 max
713 };
714
715 /// log2 of the factor.
716 pub(super) const fn shift(self) -> u32 {
717 match self {
718 Self::Off => 0,
719 Self::Half => 1,
720 Self::Quarter => 2,
721 Self::Eighth => 3,
722 }
723 }
724}
725
726/// How hard PNG compresses.
727///
728/// Every level is lossless. The level selects the `png` crate's compression
729/// setting; compare encoded size and CPU cost on representative content.
730/// `Balanced` is the default. No setting imposes a latency or memory limit.
731///
732/// This enum is marked `#[non_exhaustive]` so that levels can be added
733/// without a breaking change.
734#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
735#[non_exhaustive]
736pub enum PngCompression {
737 /// The `png` crate's `Fast` compression setting.
738 Fast,
739 /// The `png` crate's `Balanced` compression setting.
740 #[default]
741 Balanced,
742 /// The `png` crate's `High` compression setting.
743 High,
744}