Skip to main content

alpha2_render/
yuv.rs

1use crate::hdr::HdrToneMap;
2use crate::{
3    Color, ColorDiagnostic, ColorPolicy, RenderError, RenderSize, RenderedTexture, Renderer,
4    pipeline::{CachedSampledPipeline, CachedYuvPipeline},
5};
6use alpha2_media::{
7    ChromaLocation, ColorMatrix, ColorMetadata, ColorPrimaries, ColorRange, Orientation, Rect,
8    TransferFunction, YuvFormat,
9};
10use alpha2_shaders::{RGBA_PRESENT_WGSL, YUV_TO_LINEAR_WGSL, YUV16_TO_LINEAR_WGSL};
11use std::fmt::Debug;
12use std::sync::atomic::{AtomicBool, Ordering};
13use std::sync::{Arc, Mutex};
14
15use crate::pool::UploadTexture;
16use crate::uniform::UniformArenaLease;
17
18/// A rendered source texture plus presentation work its first consumer's encoder runs.
19#[derive(Debug)]
20pub struct PreparedSourceTexture {
21    texture: RenderedTexture,
22    pending: Option<PendingSourceWork>,
23}
24
25impl PreparedSourceTexture {
26    /// Separates the sampleable output from its one-shot presentation work.
27    #[must_use]
28    pub fn into_parts(self) -> (RenderedTexture, Option<PendingSourceWork>) {
29        (self.texture, self.pending)
30    }
31
32    /// GPU texture bytes held until presentation.
33    #[must_use]
34    pub fn retained_bytes(&self) -> u64 {
35        texture_bytes(self.texture.size, self.texture.format).saturating_add(
36            self.pending
37                .as_ref()
38                .map_or(0, PendingSourceWork::retained_bytes),
39        )
40    }
41}
42
43/// One source-presentation pass waiting to be encoded by its first consumer.
44#[derive(Debug)]
45pub struct PendingSourceWork {
46    state: Mutex<Option<SourceWork>>,
47    retained_bytes: u64,
48    submitted: AtomicBool,
49}
50
51#[derive(Debug)]
52pub(crate) struct SourceWork {
53    pub(crate) label: &'static str,
54    /// Whether the pass converts color into the working space (a plane repack does not).
55    pub(crate) conversion: bool,
56    pub(crate) pipeline: wgpu::RenderPipeline,
57    pub(crate) layout: wgpu::BindGroupLayout,
58    pub(crate) textures: arrayvec::ArrayVec<(u32, wgpu::TextureView), SOURCE_TEXTURES>,
59    pub(crate) uniform_binding: u32,
60    pub(crate) uniform: Vec<u8>,
61    pub(crate) sampler: Option<wgpu::BindGroup>,
62    pub(crate) output_view: wgpu::TextureView,
63    pub(crate) output_size: RenderSize,
64    pub(crate) work: crate::FrameCost,
65    pub(crate) uploads: Vec<UploadTexture>,
66    pub(crate) external_leases: Vec<Arc<dyn ExternalTextureLease>>,
67}
68
69pub(crate) const SOURCE_TEXTURES: usize = 4;
70
71/// Keeps an imported native texture and its decoder surface alive until the submission that
72/// samples it completes.
73pub trait ExternalTextureLease: Debug + Send + Sync + 'static {
74    /// Approximate native allocation bytes retained by this lease.
75    fn retained_bytes(&self) -> u64;
76
77    /// Stages native waits or signals on the renderer's next queue submission.
78    fn prepare_submission(&self) -> bool {
79        true
80    }
81
82    /// Flushes native work staged by `prepare_submission`.
83    ///
84    /// # Errors
85    /// The frame's error, normally [`RenderError::ExternalTextureSync`].
86    fn flush_submission(&self) -> Result<(), RenderError> {
87        Ok(())
88    }
89
90    /// Called right after the command buffer using the resource is submitted.
91    fn submitted(&self) {}
92
93    /// Native signals already staged on the renderer's queue.
94    ///
95    /// Staging is cleared when its submission completes, so a nonzero count when the next frame
96    /// stages means a leaked signal. Read only by a debug assertion.
97    fn staged_signals(&self) -> usize {
98        0
99    }
100}
101
102/// Native leases whose submission has completed, waiting to be dropped outside `wgpu`'s
103/// submit (see [`Renderer::submit`]).
104#[derive(Debug, Default)]
105pub(crate) struct RetiredLeases {
106    state: Mutex<LeaseState>,
107    /// Notified by each completion that parks leases, on whatever thread runs it.
108    pub(crate) parks: crate::settle::CallbackSignal,
109    /// Test-only: delay before parking, from another thread, simulating a foreign poll.
110    #[cfg(test)]
111    pub(crate) park_elsewhere_after: Mutex<Option<std::time::Duration>>,
112}
113
114#[derive(Debug, Default)]
115struct LeaseState {
116    parked: Vec<Arc<dyn ExternalTextureLease>>,
117    awaited: usize,
118}
119
120impl RetiredLeases {
121    fn lock(&self) -> std::sync::MutexGuard<'_, LeaseState> {
122        self.state
123            .lock()
124            .unwrap_or_else(std::sync::PoisonError::into_inner)
125    }
126
127    fn await_completion(&self) {
128        self.lock().awaited += 1;
129    }
130
131    fn park(&self, leases: Vec<Arc<dyn ExternalTextureLease>>) {
132        {
133            let mut state = self.lock();
134            state.parked.extend(leases);
135            state.awaited = state.awaited.saturating_sub(1);
136        }
137        self.parks.notify();
138    }
139
140    #[cfg(not(target_arch = "wasm32"))]
141    pub(crate) fn awaited(&self) -> usize {
142        self.lock().awaited
143    }
144
145    /// Drops every parked lease and returns the count. Never call inside a queue submission.
146    pub(crate) fn drain(&self) -> usize {
147        let leases = std::mem::take(&mut self.lock().parked);
148        let released = leases.len();
149        drop(leases);
150        released
151    }
152}
153
154pub(crate) struct SourceWorkTicket<'a> {
155    owner: &'a PendingSourceWork,
156    work: Option<SourceWork>,
157}
158
159impl PendingSourceWork {
160    pub(crate) fn new(work: SourceWork) -> Self {
161        let retained_bytes = work
162            .uploads
163            .iter()
164            .fold(0_u64, |total, input| {
165                total.saturating_add(input.retained_bytes())
166            })
167            .saturating_add(work.external_leases.iter().fold(0_u64, |total, lease| {
168                total.saturating_add(lease.retained_bytes())
169            }));
170        Self {
171            state: Mutex::new(Some(work)),
172            retained_bytes,
173            submitted: AtomicBool::new(false),
174        }
175    }
176
177    /// Bytes held only until the pending pass is submitted.
178    #[must_use]
179    pub fn retained_bytes(&self) -> u64 {
180        if self.submitted.load(Ordering::Acquire) {
181            0
182        } else {
183            self.retained_bytes
184        }
185    }
186
187    /// Takes the work unless a frame already has; call only under the frame lock (see
188    /// [`crate::graph_submit::begin_source_work`]).
189    pub(crate) fn begin(
190        &self,
191        _frame: &crate::renderer::FrameGuard,
192    ) -> Option<SourceWorkTicket<'_>> {
193        let work = self
194            .state
195            .lock()
196            .unwrap_or_else(std::sync::PoisonError::into_inner)
197            .take()?;
198        Some(SourceWorkTicket {
199            owner: self,
200            work: Some(work),
201        })
202    }
203}
204
205impl SourceWorkTicket<'_> {
206    pub(crate) fn uniform_bytes(&self) -> u64 {
207        let work = self.work.as_ref().expect("live source work ticket");
208        u64::try_from(work.uniform.len()).unwrap_or(u64::MAX)
209    }
210
211    pub(crate) fn output_size(&self) -> RenderSize {
212        self.work
213            .as_ref()
214            .expect("live source work ticket")
215            .output_size
216    }
217
218    pub(crate) fn work(&self) -> crate::FrameCost {
219        self.work.as_ref().expect("live source work ticket").work
220    }
221
222    pub(crate) fn encode(
223        &self,
224        renderer: &Renderer,
225        encoder: &mut impl crate::renderer::PassEncoder,
226        uniforms: &mut UniformArenaLease,
227    ) -> Result<(), RenderError> {
228        let work = self.work.as_ref().expect("live source work ticket");
229        let uniform = uniforms.write(&work.uniform)?;
230        let mut entries = arrayvec::ArrayVec::<_, { SOURCE_TEXTURES + 1 }>::new();
231        entries.extend(
232            work.textures
233                .iter()
234                .map(|(binding, view)| wgpu::BindGroupEntry {
235                    binding: *binding,
236                    resource: wgpu::BindingResource::TextureView(view),
237                }),
238        );
239        entries.push(wgpu::BindGroupEntry {
240            binding: work.uniform_binding,
241            resource: uniforms.dynamic_binding(uniform.size()),
242        });
243        let bind_group = renderer.bind_group(&wgpu::BindGroupDescriptor {
244            label: Some(work.label),
245            layout: &work.layout,
246            entries: &entries,
247        });
248        let offset = uniform.dynamic_offset();
249        encoder.placed_pass(
250            work.work,
251            crate::composite::PixelRect::whole(work.output_size),
252            crate::submission_pilot::PassKind::Conversion.key(work.output_size.pixels()),
253            |encoder, crate::submission_planner::Piece { scissor, first }| {
254                let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
255                    label: Some(work.label),
256                    color_attachments: &[Some(wgpu::RenderPassColorAttachment {
257                        view: &work.output_view,
258                        depth_slice: None,
259                        resolve_target: None,
260                        ops: wgpu::Operations {
261                            load: if first {
262                                wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT)
263                            } else {
264                                wgpu::LoadOp::Load
265                            },
266                            store: wgpu::StoreOp::Store,
267                        },
268                    })],
269                    depth_stencil_attachment: None,
270                    timestamp_writes: None,
271                    occlusion_query_set: None,
272                    multiview_mask: None,
273                });
274                if let Some(scissor) = scissor {
275                    if scissor.area() == 0 {
276                        return;
277                    }
278                    pass.set_scissor_rect(scissor.x, scissor.y, scissor.width, scissor.height);
279                }
280                pass.set_pipeline(&work.pipeline);
281                pass.set_bind_group(0, &bind_group, &[offset]);
282                if let Some(sampler) = &work.sampler {
283                    pass.set_bind_group(crate::bind_group::SAMPLER_GROUP, sampler, &[]);
284                }
285                pass.draw(0..3, 0..1);
286            },
287        );
288        Ok(())
289    }
290
291    pub(crate) fn has_no_staged_signals(&self) -> bool {
292        self.work.as_ref().is_none_or(|work| {
293            work.external_leases
294                .iter()
295                .all(|lease| lease.staged_signals() == 0)
296        })
297    }
298
299    pub(crate) fn prepare_submission(&self) -> bool {
300        let work = self.work.as_ref().expect("live source work ticket");
301        work.external_leases
302            .iter()
303            .all(|lease| lease.prepare_submission())
304    }
305
306    pub(crate) fn flush_submission(&self) -> Result<(), RenderError> {
307        let work = self.work.as_ref().expect("live source work ticket");
308        work.external_leases
309            .iter()
310            .try_for_each(|lease| lease.flush_submission())
311    }
312
313    pub(crate) fn complete(mut self, renderer: &Renderer, standalone_submission: bool) {
314        let work = self.work.take().expect("live source work ticket");
315        let work_conversion = work.conversion;
316        drop(work.uploads);
317        if !work.external_leases.is_empty() {
318            let leases = work.external_leases;
319            for lease in &leases {
320                lease.submitted();
321            }
322            // Runs inside `wgpu`'s submit: only park here, since dropping inverts `FFmpeg`'s lock
323            // order.
324            let retired = Arc::clone(&renderer.retired_leases);
325            retired.await_completion();
326            #[cfg(test)]
327            let elsewhere = *retired
328                .park_elsewhere_after
329                .lock()
330                .unwrap_or_else(std::sync::PoisonError::into_inner);
331            renderer.gpu.on_submitted_work_done(move || {
332                #[cfg(test)]
333                if let Some(delay) = elsewhere {
334                    std::thread::spawn(move || {
335                        std::thread::sleep(delay);
336                        retired.park(leases);
337                    });
338                    return;
339                }
340                retired.park(leases);
341            });
342        }
343        self.owner.submitted.store(true, Ordering::Release);
344        crate::diagnostics::record_source_work(
345            &renderer.diagnostics,
346            1,
347            standalone_submission,
348            work_conversion,
349        );
350    }
351}
352
353impl Drop for SourceWorkTicket<'_> {
354    fn drop(&mut self) {
355        let Some(work) = self.work.take() else {
356            return;
357        };
358        let mut state = self
359            .owner
360            .state
361            .lock()
362            .unwrap_or_else(std::sync::PoisonError::into_inner);
363        debug_assert!(state.is_none());
364        *state = Some(work);
365    }
366}
367
368/// How an RGBA source texture stores color relative to its alpha.
369#[derive(Copy, Clone, Debug, Eq, PartialEq)]
370pub enum SourceAlpha {
371    /// Color independent of alpha, as decoders deliver it. Presentation premultiplies it.
372    Straight,
373    /// Color already multiplied by alpha, as a browser 2D canvas stores it.
374    Premultiplied,
375}
376
377/// How the RGBA presentation pass reads its source texture.
378#[derive(Copy, Clone, Debug, Eq, PartialEq)]
379pub(crate) enum PresentedEncoding {
380    /// sRGB-encoded color, straight or premultiplied.
381    Srgb(SourceAlpha),
382    /// Premultiplied linear BT.709 color, encoded with the sRGB curve extended beyond `[0, 1]`.
383    Linear,
384}
385
386/// GPU presentation transform applied while converting a decoded source.
387#[derive(Copy, Clone, Debug, Eq, PartialEq)]
388pub struct SourcePresentation {
389    /// Destination canvas. Pixels outside the contained source are transparent.
390    pub output_size: RenderSize,
391    /// Visible crop inside the coded source.
392    pub visible_rect: Rect,
393    /// How the source is shown upright: mirrored, then rotated.
394    pub orientation: Orientation,
395    /// Horizontal pixel aspect-ratio numerator and denominator.
396    pub sample_aspect_ratio: (u32, u32),
397    /// Chroma sample position. An unspecified location is sampled as centered.
398    pub chroma_siting: ChromaLocation,
399}
400
401impl SourcePresentation {
402    /// Creates an unrotated, square-pixel full-frame presentation.
403    #[must_use]
404    pub const fn identity(size: RenderSize) -> Self {
405        Self {
406            output_size: size,
407            visible_rect: Rect {
408                x: 0,
409                y: 0,
410                width: size.width,
411                height: size.height,
412            },
413            orientation: Orientation::UPRIGHT,
414            sample_aspect_ratio: (1, 1),
415            chroma_siting: ChromaLocation::Unspecified,
416        }
417    }
418}
419
420/// Borrowed 8-bit planar 4:2:0 source.
421#[derive(Copy, Clone, Debug)]
422pub struct Yuv420Frame<'a> {
423    /// Luma bytes including row padding.
424    pub y: &'a [u8],
425    /// Blue-difference chroma bytes including row padding.
426    pub u: &'a [u8],
427    /// Red-difference chroma bytes including row padding.
428    pub v: &'a [u8],
429    /// Luma row stride.
430    pub y_stride: u32,
431    /// Chroma row stride shared by U and V.
432    pub chroma_stride: u32,
433    /// Coded dimensions.
434    pub size: RenderSize,
435    /// Straight source alpha.
436    pub alpha: f32,
437    /// Optional stream color metadata.
438    pub color: Option<ColorMetadata>,
439}
440
441impl<'a> From<Yuv420Frame<'a>> for YuvFrame<'a> {
442    fn from(frame: Yuv420Frame<'a>) -> Self {
443        Self {
444            format: YuvFormat::I420,
445            planes: [
446                SourcePlane {
447                    bytes: frame.y,
448                    stride: frame.y_stride,
449                },
450                SourcePlane {
451                    bytes: frame.u,
452                    stride: frame.chroma_stride,
453                },
454                SourcePlane {
455                    bytes: frame.v,
456                    stride: frame.chroma_stride,
457                },
458            ],
459            alpha_plane: None,
460            size: frame.size,
461            alpha: frame.alpha,
462            color: frame.color,
463        }
464    }
465}
466
467/// One borrowed source plane: rows `stride` bytes apart.
468#[derive(Copy, Clone, Debug)]
469pub struct SourcePlane<'a> {
470    /// Plane bytes including row padding.
471    pub bytes: &'a [u8],
472    /// Bytes between adjacent rows.
473    pub stride: u32,
474}
475
476/// Borrowed planar or semi-planar YCbCr source of any subsampling and depth
477/// [`YuvFormat::is_supported`] accepts.
478#[derive(Copy, Clone, Debug)]
479pub struct YuvFrame<'a> {
480    /// How the planes store their samples.
481    pub format: YuvFormat,
482    /// Luma, U and V; or luma and interleaved chroma, with the third plane ignored.
483    pub planes: [SourcePlane<'a>; 3],
484    /// Straight full-range alpha at luma size and depth, present exactly when
485    /// [`YuvFormat::alpha`] is set.
486    pub alpha_plane: Option<SourcePlane<'a>>,
487    /// Coded dimensions.
488    pub size: RenderSize,
489    /// Straight source alpha.
490    pub alpha: f32,
491    /// Optional stream color metadata.
492    pub color: Option<ColorMetadata>,
493}
494
495/// How an uploaded plane stores samples on the GPU.
496#[derive(Copy, Clone, Debug, Eq, PartialEq)]
497pub(crate) enum PlaneStorage {
498    /// 8-bit samples as `R8Unorm`/`Rg8Unorm`.
499    Unorm8,
500    /// 16-bit containers as `R16Unorm`/`Rg16Unorm`.
501    Unorm16,
502    /// 16-bit containers as `R16Uint`/`Rg16Uint`, for devices without 16-bit normalized textures
503    /// (browser `WebGPU`). The conversion normalizes them on the GPU.
504    Uint16,
505}
506
507impl PlaneStorage {
508    fn texture_format(self, interleaved: bool) -> wgpu::TextureFormat {
509        match (self, interleaved) {
510            (Self::Unorm8, false) => wgpu::TextureFormat::R8Unorm,
511            (Self::Unorm8, true) => wgpu::TextureFormat::Rg8Unorm,
512            (Self::Unorm16, false) => wgpu::TextureFormat::R16Unorm,
513            (Self::Unorm16, true) => wgpu::TextureFormat::Rg16Unorm,
514            (Self::Uint16, false) => wgpu::TextureFormat::R16Uint,
515            (Self::Uint16, true) => wgpu::TextureFormat::Rg16Uint,
516        }
517    }
518
519    /// Factor that turns a sampled value into `code / (2^depth - 1)`.
520    ///
521    /// A `u16` container samples as `container / 65535`, so a low-aligned 10-bit code peaks at
522    /// `1023 / 65535` and a high-aligned `P010` code at `65472 / 65535`.
523    #[allow(clippy::cast_precision_loss)]
524    pub(crate) fn code_scale(self, format: YuvFormat) -> f32 {
525        match self {
526            Self::Unorm8 => 1.0,
527            Self::Unorm16 | Self::Uint16 => {
528                let maximum = ((1_u32 << format.bit_depth) - 1) as f32;
529                let alignment = if format.msb_aligned {
530                    (1_u32 << (16 - u32::from(format.bit_depth))) as f32
531                } else {
532                    1.0
533                };
534                65535.0 / (maximum * alignment)
535            }
536        }
537    }
538}
539
540/// A straight alpha plane in CPU memory beside [`GpuVideoPlanes`], at the luma's depth and
541/// alignment: `size` samples from the planes' top left, which may stop short of their coded size.
542#[derive(Copy, Clone, Debug)]
543#[cfg_attr(not(feature = "wgpu-interop"), doc(hidden))]
544pub struct CpuAlphaPlane<'a> {
545    /// The samples, rows `stride` bytes apart.
546    pub plane: SourcePlane<'a>,
547    /// Columns and rows of samples.
548    pub size: RenderSize,
549}
550
551/// Borrowed views of a decoded YCbCr frame already resident on the GPU.
552#[derive(Copy, Clone, Debug)]
553#[cfg_attr(not(feature = "wgpu-interop"), doc(hidden))]
554pub struct GpuVideoPlanes<'a> {
555    /// Luma view.
556    pub y: &'a wgpu::TextureView,
557    /// U view, or the interleaved UV view.
558    pub chroma: &'a wgpu::TextureView,
559    /// V view; absent when chroma is interleaved.
560    pub v: Option<&'a wgpu::TextureView>,
561    /// `R8`/`RG8` for 8-bit, `R16`/`RG16` normalized above.
562    pub format: YuvFormat,
563    /// Coded dimensions.
564    pub size: RenderSize,
565    /// Straight source alpha.
566    pub alpha: f32,
567    /// Optional stream color metadata.
568    pub color: Option<ColorMetadata>,
569}
570
571impl Renderer {
572    /// Prepares an uploaded RGBA texture for presentation by its first consumer, without
573    /// submitting.
574    ///
575    /// # Errors
576    /// Returns an image-data error for invalid presentation metadata.
577    pub fn prepare_rgba_presented(
578        &self,
579        source: UploadTexture,
580        source_size: RenderSize,
581        presentation: SourcePresentation,
582        alpha: SourceAlpha,
583    ) -> Result<PreparedSourceTexture, RenderError> {
584        let view = source.view().clone();
585        let prepared = self.prepare_rgba_presented_inner(
586            &view,
587            source_size,
588            presentation,
589            PresentedEncoding::Srgb(alpha),
590            vec![source],
591        )?;
592        Ok(prepared)
593    }
594
595    /// Prepares premultiplied linear BT.709 RGBA ([`Self::upload_linear_rgba16f`]) like
596    /// [`Self::prepare_rgba_presented`].
597    ///
598    /// Filtered in linear light, then stored sRGB-encoded and premultiplied with the curve extended
599    /// beyond `[0, 1]` as far as the intermediate holds. Color under zero alpha is dropped.
600    ///
601    /// # Errors
602    /// Returns an image-data error for invalid presentation metadata.
603    pub fn prepare_linear_presented(
604        &self,
605        source: UploadTexture,
606        source_size: RenderSize,
607        presentation: SourcePresentation,
608    ) -> Result<PreparedSourceTexture, RenderError> {
609        let view = source.view().clone();
610        self.prepare_rgba_presented_inner(
611            &view,
612            source_size,
613            presentation,
614            PresentedEncoding::Linear,
615            vec![source],
616        )
617    }
618
619    /// Uploads an sRGB-encoded RGBA8 plane and prepares it like [`Self::prepare_rgba_presented`].
620    ///
621    /// # Errors
622    /// Returns an image-data error for a short plane or invalid presentation metadata.
623    pub fn prepare_rgba8_presented(
624        &self,
625        pixels: SourcePlane<'_>,
626        size: RenderSize,
627        presentation: SourcePresentation,
628        alpha: SourceAlpha,
629    ) -> Result<PreparedSourceTexture, RenderError> {
630        let texture = self.write_rgba8(size, pixels)?;
631        self.prepare_rgba_presented(texture, size, presentation, alpha)
632    }
633
634    pub(crate) fn prepare_rgba_presented_inner(
635        &self,
636        source_view: &wgpu::TextureView,
637        source_size: RenderSize,
638        presentation: SourcePresentation,
639        encoding: PresentedEncoding,
640        inputs: Vec<UploadTexture>,
641    ) -> Result<PreparedSourceTexture, RenderError> {
642        self.validate_size(source_size)?;
643        self.validate_size(presentation.output_size)?;
644        validate_presentation(source_size, presentation)?;
645        let output_format = self.intermediate_format();
646        let output = self.textures.acquire(
647            self.gpu.device(),
648            presentation.output_size,
649            output_format,
650            "alpha2 RGBA presentation target",
651        );
652        let cached = self.rgba_presentation_pipeline()?;
653        let uniform_bytes = presentation_uniform_bytes(
654            source_size,
655            presentation,
656            encoding,
657            self.presentation_filter_samples(),
658        );
659        let output_view = output.view().clone();
660        Ok(PreparedSourceTexture {
661            texture: RenderedTexture::pooled(presentation.output_size, output_format, output),
662            pending: Some(PendingSourceWork::new(SourceWork {
663                label: "alpha2 RGBA presentation pass",
664                conversion: true,
665                pipeline: cached.pipeline.clone(),
666                layout: cached.bind_group_layout.clone(),
667                textures: [(0, source_view.clone())].into_iter().collect(),
668                uniform_binding: 1,
669                uniform: uniform_bytes,
670                sampler: Some(self.linear_sampler.group.clone()),
671                output_view,
672                output_size: presentation.output_size,
673                work: conversion_work(
674                    presentation,
675                    self.presentation_filter_samples(),
676                    RGBA_SAMPLE_COST,
677                ),
678                uploads: inputs,
679                external_leases: Vec::new(),
680            })),
681        })
682    }
683
684    /// Submits one pending source presentation now.
685    ///
686    /// Returns `false` when another consumer already did, or when staging or submission fails;
687    /// the work then stays pending for a later frame.
688    pub fn submit_pending_source(&self, pending: &PendingSourceWork) -> bool {
689        let frame = self.frame_lock.hold();
690        let Some(ticket) = pending.begin(&frame) else {
691            return false;
692        };
693        let mut encoder = self.command_encoder("alpha2 source presentation encoder");
694        let mut uniforms = self
695            .uniform_buffers
696            .acquire(self.gpu.device(), ticket.uniform_bytes());
697        if ticket.encode(self, &mut encoder, &mut uniforms).is_err() {
698            return false;
699        }
700        uniforms.flush(self.gpu.queue());
701        if !ticket.prepare_submission() || ticket.flush_submission().is_err() {
702            return false;
703        }
704        if self.submit([encoder.finish()]).is_err() {
705            return false;
706        }
707        uniforms.recycle();
708        ticket.complete(self, true);
709        true
710    }
711
712    /// Uploads YUV planes and converts them on the GPU to premultiplied sRGB storage.
713    /// Transfer decoding precedes sRGB encoding and premultiplication.
714    ///
715    /// # Errors
716    /// An image-data error for malformed planes or alpha, and [`RenderError::UnsupportedHdr`] when
717    /// [`ColorPolicy::RejectHdr`] meets an HDR source.
718    #[allow(clippy::too_many_lines)]
719    pub fn render_yuv420p(
720        &self,
721        frame: Yuv420Frame<'_>,
722        policy: ColorPolicy,
723    ) -> Result<(RenderedTexture, Vec<ColorDiagnostic>), RenderError> {
724        self.render_yuv420p_presented(frame, SourcePresentation::identity(frame.size), policy)
725    }
726
727    fn rgba_presentation_pipeline(&self) -> Result<&CachedSampledPipeline, RenderError> {
728        crate::gpu_errors::checked_cell(&self.pipelines.rgba_present, self.gpu.device(), || {
729            let output_format = self.intermediate_format();
730            let bind_group_layout =
731                self.gpu
732                    .device()
733                    .create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
734                        label: Some("alpha2 RGBA presentation layout"),
735                        entries: &[
736                            wgpu::BindGroupLayoutEntry {
737                                binding: 0,
738                                visibility: wgpu::ShaderStages::FRAGMENT,
739                                ty: wgpu::BindingType::Texture {
740                                    sample_type: wgpu::TextureSampleType::Float {
741                                        filterable: true,
742                                    },
743                                    view_dimension: wgpu::TextureViewDimension::D2,
744                                    multisampled: false,
745                                },
746                                count: None,
747                            },
748                            wgpu::BindGroupLayoutEntry {
749                                binding: 1,
750                                visibility: wgpu::ShaderStages::FRAGMENT,
751                                ty: wgpu::BindingType::Buffer {
752                                    ty: wgpu::BufferBindingType::Uniform,
753                                    has_dynamic_offset: true,
754                                    min_binding_size: None,
755                                },
756                                count: None,
757                            },
758                        ],
759                    });
760            let shader = self
761                .gpu
762                .device()
763                .create_shader_module(wgpu::ShaderModuleDescriptor {
764                    label: Some("alpha2 RGBA presentation shader"),
765                    source: wgpu::ShaderSource::Wgsl(RGBA_PRESENT_WGSL.into()),
766                });
767            let layout =
768                self.gpu
769                    .device()
770                    .create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
771                        label: Some("alpha2 RGBA presentation pipeline layout"),
772                        bind_group_layouts: &[
773                            Some(&bind_group_layout),
774                            Some(&self.linear_sampler.layout),
775                        ],
776                        immediate_size: 0,
777                    });
778            let pipeline =
779                self.gpu
780                    .device()
781                    .create_render_pipeline(&wgpu::RenderPipelineDescriptor {
782                        label: Some("alpha2 RGBA presentation pipeline"),
783                        layout: Some(&layout),
784                        vertex: wgpu::VertexState {
785                            module: &shader,
786                            entry_point: Some("vs"),
787                            buffers: &[],
788                            compilation_options: wgpu::PipelineCompilationOptions::default(),
789                        },
790                        fragment: Some(wgpu::FragmentState {
791                            module: &shader,
792                            entry_point: Some("fs"),
793                            targets: &[Some(output_format.into())],
794                            compilation_options: wgpu::PipelineCompilationOptions::default(),
795                        }),
796                        primitive: wgpu::PrimitiveState::default(),
797                        depth_stencil: None,
798                        multisample: wgpu::MultisampleState::default(),
799                        multiview_mask: None,
800                        cache: None,
801                    });
802            CachedSampledPipeline {
803                bind_group_layout,
804                pipeline,
805            }
806        })
807    }
808
809    /// Uploads and converts YUV420P with crop, sample aspect, rotation, scaling (bilinear,
810    /// footprint-averaged when shrinking) and transparent contain placement on the GPU.
811    ///
812    /// # Errors
813    /// An image-data error for malformed planes, metadata or alpha, and
814    /// [`RenderError::UnsupportedHdr`] when [`ColorPolicy::RejectHdr`] meets an HDR source.
815    #[allow(clippy::too_many_lines, clippy::cast_possible_truncation)]
816    pub fn render_yuv420p_presented(
817        &self,
818        frame: Yuv420Frame<'_>,
819        presentation: SourcePresentation,
820        policy: ColorPolicy,
821    ) -> Result<(RenderedTexture, Vec<ColorDiagnostic>), RenderError> {
822        let (prepared, diagnostics) =
823            self.prepare_yuv420p_presented(frame, presentation, policy)?;
824        let (texture, pending) = prepared.into_parts();
825        if let Some(pending) = pending {
826            self.submit_pending_source(&pending);
827        }
828        Ok((texture, diagnostics))
829    }
830
831    /// Uploads YUV420 planes and defers their conversion to the first consuming frame's encoder.
832    ///
833    /// # Errors
834    /// An image-data error for malformed input, and [`RenderError::UnsupportedHdr`] when
835    /// [`ColorPolicy::RejectHdr`] meets an HDR source.
836    #[allow(clippy::too_many_lines, clippy::cast_possible_truncation)]
837    pub fn prepare_yuv420p_presented(
838        &self,
839        frame: Yuv420Frame<'_>,
840        presentation: SourcePresentation,
841        policy: ColorPolicy,
842    ) -> Result<(PreparedSourceTexture, Vec<ColorDiagnostic>), RenderError> {
843        self.prepare_yuv_presented(frame.into(), presentation, policy)
844    }
845
846    /// Uploads planar or semi-planar YCbCr of any supported subsampling and depth, prepared like
847    /// [`Self::prepare_yuv420p_presented`].
848    ///
849    /// Samples above 8 bits upload as 16-bit normalized textures, or as `u16` containers the GPU
850    /// normalizes on devices without them.
851    ///
852    /// # Errors
853    /// An image-data error for an unsupported format or malformed planes, and
854    /// [`RenderError::UnsupportedHdr`] when [`ColorPolicy::RejectHdr`] meets an HDR source.
855    pub fn prepare_yuv_presented(
856        &self,
857        frame: YuvFrame<'_>,
858        presentation: SourcePresentation,
859        policy: ColorPolicy,
860    ) -> Result<(PreparedSourceTexture, Vec<ColorDiagnostic>), RenderError> {
861        let mut diagnostics = Vec::new();
862        let color = frame.color.unwrap_or_else(|| {
863            diagnostics.push(ColorDiagnostic::MissingMetadataFallback);
864            ColorMetadata::UNDECLARED
865        });
866        let tone = match hdr_handling(color, policy, &mut diagnostics)? {
867            HdrHandling::Sdr => None,
868            HdrHandling::ToneMap(tone) => Some(tone),
869            HdrHandling::Skip => {
870                return self
871                    .render_solid(presentation.output_size, Color::rgba(0.0, 0.0, 0.0, 0.0))
872                    .map(|texture| {
873                        (
874                            PreparedSourceTexture {
875                                texture,
876                                pending: None,
877                            },
878                            diagnostics,
879                        )
880                    });
881            }
882        };
883        let format = frame.format;
884        if !frame.alpha.is_finite()
885            || !(0.0..=1.0).contains(&frame.alpha)
886            || !format.is_supported()
887            || format.alpha != frame.alpha_plane.is_some()
888        {
889            return Err(RenderError::InvalidImageData);
890        }
891        self.validate_size(presentation.output_size)?;
892        validate_presentation(frame.size, presentation)?;
893        let storage = if format.bytes_per_sample() == 1 {
894            PlaneStorage::Unorm8
895        } else if self
896            .features
897            .contains(wgpu::Features::TEXTURE_FORMAT_16BIT_NORM)
898        {
899            PlaneStorage::Unorm16
900        } else {
901            PlaneStorage::Uint16
902        };
903        let (chroma_width, chroma_height) = format.chroma_size(frame.size.width, frame.size.height);
904        let pairs = if format.interleaved_chroma { 2 } else { 1 };
905        let plane_specs = [
906            ("alpha2 Y plane", frame.size.width, frame.size.height, 1_u32),
907            ("alpha2 U plane", chroma_width, chroma_height, pairs),
908            ("alpha2 V plane", chroma_width, chroma_height, 1),
909        ];
910        let mut uploads = Vec::with_capacity(format.plane_count());
911        let alpha_spec = ("alpha2 A plane", frame.size.width, frame.size.height, 1_u32);
912        for (plane, (label, width, height, samples)) in frame
913            .planes
914            .iter()
915            .zip(plane_specs)
916            .take(format.color_plane_count())
917            .chain(frame.alpha_plane.iter().map(|plane| (plane, alpha_spec)))
918        {
919            let row_bytes = width
920                .checked_mul(samples)
921                .and_then(|row| row.checked_mul(format.bytes_per_sample()))
922                .ok_or(RenderError::InvalidImageData)?;
923            validate_plane(plane.bytes, plane.stride, row_bytes, height)?;
924            uploads.push(upload_plane(
925                self,
926                label,
927                *plane,
928                (width, height),
929                storage.texture_format(samples == 2),
930            )?);
931        }
932        let mut views = uploads
933            .iter()
934            .map(|upload| upload.view().clone())
935            .collect::<Vec<_>>();
936        let alpha_view = format.alpha.then(|| views.pop()).flatten();
937        let planes = GpuVideoPlanes {
938            y: &views[0],
939            chroma: &views[1],
940            v: views.get(2),
941            format,
942            size: frame.size,
943            alpha: frame.alpha,
944            color: Some(color),
945        };
946        let prepared = self.prepare_gpu_yuv_presented_inner(
947            planes,
948            alpha_view.as_ref(),
949            presentation,
950            tone,
951            storage,
952            uploads,
953            Vec::new(),
954        )?;
955        Ok((prepared, diagnostics))
956    }
957
958    /// Prepares conversion of native GPU video planes without a CPU copy.
959    ///
960    /// The lease is held until queue completion. I420 takes three R8 views; NV12 takes R8 luma and
961    /// RG8 chroma. An `alpha_plane` is uploaded, and `planes.format` must then have
962    /// [`YuvFormat::alpha`].
963    ///
964    /// # Errors
965    /// An image-data error for an invalid plane contract, and [`RenderError::UnsupportedHdr`] when
966    /// [`ColorPolicy::RejectHdr`] meets an HDR source.
967    #[cfg_attr(not(feature = "wgpu-interop"), doc(hidden))]
968    pub fn prepare_gpu_yuv_presented(
969        &self,
970        planes: GpuVideoPlanes<'_>,
971        presentation: SourcePresentation,
972        policy: ColorPolicy,
973        lease: Arc<dyn ExternalTextureLease>,
974        alpha_plane: Option<CpuAlphaPlane<'_>>,
975    ) -> Result<(PreparedSourceTexture, Vec<ColorDiagnostic>), RenderError> {
976        let mut diagnostics = Vec::new();
977        let color = planes.color.unwrap_or_else(|| {
978            diagnostics.push(ColorDiagnostic::MissingMetadataFallback);
979            ColorMetadata::UNDECLARED
980        });
981        let tone = match hdr_handling(color, policy, &mut diagnostics)? {
982            HdrHandling::Sdr => None,
983            HdrHandling::ToneMap(tone) => Some(tone),
984            HdrHandling::Skip => {
985                return self
986                    .render_solid(presentation.output_size, Color::rgba(0.0, 0.0, 0.0, 0.0))
987                    .map(|texture| {
988                        (
989                            PreparedSourceTexture {
990                                texture,
991                                pending: None,
992                            },
993                            diagnostics,
994                        )
995                    });
996            }
997        };
998        let planes = GpuVideoPlanes {
999            color: Some(color),
1000            ..planes
1001        };
1002        let storage = if planes.format.bytes_per_sample() == 1 {
1003            PlaneStorage::Unorm8
1004        } else {
1005            PlaneStorage::Unorm16
1006        };
1007        let alpha_upload = alpha_plane
1008            .map(|alpha| {
1009                let (width, height) = (alpha.size.width, alpha.size.height);
1010                if width > planes.size.width || height > planes.size.height {
1011                    return Err(RenderError::InvalidImageData);
1012                }
1013                let row_bytes = width
1014                    .checked_mul(planes.format.bytes_per_sample())
1015                    .ok_or(RenderError::InvalidImageData)?;
1016                validate_plane(alpha.plane.bytes, alpha.plane.stride, row_bytes, height)?;
1017                upload_plane_region(
1018                    self,
1019                    "alpha2 A plane",
1020                    alpha.plane,
1021                    (width, height),
1022                    (planes.size.width, planes.size.height),
1023                    storage.texture_format(false),
1024                )
1025            })
1026            .transpose()?;
1027        let alpha_view = alpha_upload.as_ref().map(|upload| upload.view().clone());
1028        let prepared = self.prepare_gpu_yuv_presented_inner(
1029            planes,
1030            alpha_view.as_ref(),
1031            presentation,
1032            tone,
1033            storage,
1034            alpha_upload.into_iter().collect(),
1035            vec![lease],
1036        )?;
1037        Ok((prepared, diagnostics))
1038    }
1039
1040    pub(crate) fn prepare_pilot_conversion(
1041        &self,
1042        planes: GpuVideoPlanes<'_>,
1043        size: RenderSize,
1044    ) -> Result<PreparedSourceTexture, RenderError> {
1045        self.prepare_gpu_yuv_presented_inner(
1046            planes,
1047            None,
1048            SourcePresentation::identity(size),
1049            None,
1050            PlaneStorage::Unorm8,
1051            Vec::new(),
1052            Vec::new(),
1053        )
1054    }
1055
1056    #[allow(clippy::too_many_arguments)]
1057    fn prepare_gpu_yuv_presented_inner(
1058        &self,
1059        planes: GpuVideoPlanes<'_>,
1060        alpha_plane: Option<&wgpu::TextureView>,
1061        presentation: SourcePresentation,
1062        tone: Option<HdrToneMap>,
1063        storage: PlaneStorage,
1064        uploads: Vec<UploadTexture>,
1065        external_leases: Vec<Arc<dyn ExternalTextureLease>>,
1066    ) -> Result<PreparedSourceTexture, RenderError> {
1067        if !planes.alpha.is_finite() || !(0.0..=1.0).contains(&planes.alpha) {
1068            return Err(RenderError::InvalidImageData);
1069        }
1070        if !planes.format.is_supported()
1071            || planes.format.interleaved_chroma == planes.v.is_some()
1072            || planes.format.alpha != alpha_plane.is_some()
1073        {
1074            return Err(RenderError::InvalidImageData);
1075        }
1076        self.validate_size(planes.size)?;
1077        self.validate_size(presentation.output_size)?;
1078        validate_presentation(planes.size, presentation)?;
1079        let color = planes.color.unwrap_or_default();
1080        let output_format = self.intermediate_format();
1081        let output = self.textures.acquire(
1082            self.gpu.device(),
1083            presentation.output_size,
1084            output_format,
1085            "alpha2 YUV conversion target",
1086        );
1087        let output_view = output.view().clone();
1088        let cached = self.yuv_pipeline(storage == PlaneStorage::Uint16)?;
1089        let uniform_bytes = uniform_bytes(
1090            color,
1091            tone,
1092            planes.alpha,
1093            planes.size,
1094            presentation,
1095            planes.format,
1096            storage.code_scale(planes.format),
1097            self.presentation_filter_samples(),
1098        );
1099        let textures = [
1100            (0, planes.y),
1101            (1, planes.chroma),
1102            (2, planes.v.unwrap_or(planes.chroma)),
1103            (4, alpha_plane.unwrap_or(planes.y)),
1104        ]
1105        .into_iter()
1106        .map(|(binding, view)| (binding, view.clone()))
1107        .collect();
1108        Ok(PreparedSourceTexture {
1109            texture: RenderedTexture::pooled(presentation.output_size, output_format, output),
1110            pending: Some(PendingSourceWork::new(SourceWork {
1111                label: "alpha2 YUV conversion pass",
1112                conversion: true,
1113                pipeline: cached.pipeline.clone(),
1114                layout: cached.bind_group_layout.clone(),
1115                textures,
1116                uniform_binding: 3,
1117                uniform: uniform_bytes,
1118                sampler: Some(self.linear_sampler.group.clone()),
1119                output_view,
1120                output_size: presentation.output_size,
1121                work: conversion_work(
1122                    presentation,
1123                    self.presentation_filter_samples(),
1124                    yuv_sample_cost(planes.format),
1125                ),
1126                uploads,
1127                external_leases,
1128            })),
1129        })
1130    }
1131}
1132
1133pub(crate) fn validate_plane(
1134    bytes: &[u8],
1135    stride: u32,
1136    width: u32,
1137    height: u32,
1138) -> Result<(), RenderError> {
1139    let required = usize::try_from(stride).ok().and_then(|stride| {
1140        usize::try_from(height)
1141            .ok()
1142            .and_then(|height| stride.checked_mul(height))
1143    });
1144    if stride < width || required != Some(bytes.len()) {
1145        Err(RenderError::InvalidImageData)
1146    } else {
1147        Ok(())
1148    }
1149}
1150
1151fn texture_bytes(size: RenderSize, format: wgpu::TextureFormat) -> u64 {
1152    let block = format.block_copy_size(None).unwrap_or(4);
1153    u64::from(size.width)
1154        .saturating_mul(u64::from(size.height))
1155        .saturating_mul(u64::from(block))
1156}
1157
1158pub(crate) fn upload_plane(
1159    renderer: &Renderer,
1160    label: &'static str,
1161    plane: SourcePlane<'_>,
1162    size: (u32, u32),
1163    texture_format: wgpu::TextureFormat,
1164) -> Result<crate::UploadTexture, RenderError> {
1165    upload_plane_region(renderer, label, plane, size, size, texture_format)
1166}
1167
1168pub(crate) fn upload_plane_region(
1169    renderer: &Renderer,
1170    label: &'static str,
1171    plane: SourcePlane<'_>,
1172    (width, height): (u32, u32),
1173    texture_size: (u32, u32),
1174    texture_format: wgpu::TextureFormat,
1175) -> Result<crate::UploadTexture, RenderError> {
1176    let size = RenderSize::new(texture_size.0, texture_size.1)?;
1177    renderer.validate_size(size)?;
1178    let texture =
1179        renderer
1180            .upload_textures
1181            .acquire(renderer.gpu.device(), size, texture_format, label);
1182    renderer.gpu.queue().write_texture(
1183        wgpu::TexelCopyTextureInfo {
1184            texture: texture.texture(),
1185            mip_level: 0,
1186            origin: wgpu::Origin3d::ZERO,
1187            aspect: wgpu::TextureAspect::All,
1188        },
1189        plane.bytes,
1190        wgpu::TexelCopyBufferLayout {
1191            offset: 0,
1192            bytes_per_row: Some(plane.stride),
1193            rows_per_image: Some(height),
1194        },
1195        wgpu::Extent3d {
1196            width,
1197            height,
1198            depth_or_array_layers: 1,
1199        },
1200    );
1201    Ok(texture)
1202}
1203
1204impl Renderer {
1205    /// Most samples a presentation pass averages per output pixel when shrinking, matching the
1206    /// composite's minification budget (at most 64).
1207    #[allow(clippy::cast_precision_loss)]
1208    fn presentation_filter_samples(&self) -> f32 {
1209        self.quality_controls().max_filter_samples as f32
1210    }
1211
1212    /// Bindings: Y, U or UV, V planes of `sample_type`, the uniform, and the alpha plane.
1213    fn yuv_bind_group_layout(&self, sample_type: wgpu::TextureSampleType) -> wgpu::BindGroupLayout {
1214        let texture = |binding| wgpu::BindGroupLayoutEntry {
1215            binding,
1216            visibility: wgpu::ShaderStages::FRAGMENT,
1217            ty: wgpu::BindingType::Texture {
1218                sample_type,
1219                view_dimension: wgpu::TextureViewDimension::D2,
1220                multisampled: false,
1221            },
1222            count: None,
1223        };
1224        self.gpu
1225            .device()
1226            .create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
1227                label: Some("alpha2 YUV layout"),
1228                entries: &[
1229                    texture(0),
1230                    texture(1),
1231                    texture(2),
1232                    wgpu::BindGroupLayoutEntry {
1233                        binding: 3,
1234                        visibility: wgpu::ShaderStages::FRAGMENT,
1235                        ty: wgpu::BindingType::Buffer {
1236                            ty: wgpu::BufferBindingType::Uniform,
1237                            has_dynamic_offset: true,
1238                            min_binding_size: None,
1239                        },
1240                        count: None,
1241                    },
1242                    texture(4),
1243                ],
1244            })
1245    }
1246
1247    /// With `integer_planes`, the pipeline for 16-bit containers uploaded as unsigned integers.
1248    fn yuv_pipeline(&self, integer_planes: bool) -> Result<&CachedYuvPipeline, RenderError> {
1249        let (cache, source) = if integer_planes {
1250            (&self.pipelines.yuv16, YUV16_TO_LINEAR_WGSL)
1251        } else {
1252            (&self.pipelines.yuv, YUV_TO_LINEAR_WGSL)
1253        };
1254        crate::gpu_errors::checked_cell(cache, self.gpu.device(), || {
1255            let bind_group_layout = self.yuv_bind_group_layout(if integer_planes {
1256                wgpu::TextureSampleType::Uint
1257            } else {
1258                wgpu::TextureSampleType::Float { filterable: true }
1259            });
1260            let shader = self
1261                .gpu
1262                .device()
1263                .create_shader_module(wgpu::ShaderModuleDescriptor {
1264                    label: Some("alpha2 YUV conversion shader"),
1265                    source: wgpu::ShaderSource::Wgsl(source.into()),
1266                });
1267            let pipeline_layout =
1268                self.gpu
1269                    .device()
1270                    .create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
1271                        label: Some("alpha2 YUV pipeline layout"),
1272                        bind_group_layouts: &[
1273                            Some(&bind_group_layout),
1274                            Some(&self.linear_sampler.layout),
1275                        ],
1276                        immediate_size: 0,
1277                    });
1278            let pipeline =
1279                self.gpu
1280                    .device()
1281                    .create_render_pipeline(&wgpu::RenderPipelineDescriptor {
1282                        label: Some("alpha2 YUV pipeline"),
1283                        layout: Some(&pipeline_layout),
1284                        vertex: wgpu::VertexState {
1285                            module: &shader,
1286                            entry_point: Some("vs"),
1287                            buffers: &[],
1288                            compilation_options: wgpu::PipelineCompilationOptions::default(),
1289                        },
1290                        fragment: Some(wgpu::FragmentState {
1291                            module: &shader,
1292                            entry_point: Some("fs_srgb"),
1293                            targets: &[Some(self.intermediate_format().into())],
1294                            compilation_options: wgpu::PipelineCompilationOptions::default(),
1295                        }),
1296                        primitive: wgpu::PrimitiveState::default(),
1297                        depth_stencil: None,
1298                        multisample: wgpu::MultisampleState::default(),
1299                        multiview_mask: None,
1300                        cache: None,
1301                    });
1302            CachedYuvPipeline {
1303                bind_group_layout,
1304                pipeline,
1305            }
1306        })
1307    }
1308}
1309
1310pub(crate) fn validate_presentation(
1311    source: RenderSize,
1312    presentation: SourcePresentation,
1313) -> Result<(), RenderError> {
1314    let visible = presentation.visible_rect;
1315    if visible.width == 0
1316        || visible.height == 0
1317        || presentation.sample_aspect_ratio.0 == 0
1318        || presentation.sample_aspect_ratio.1 == 0
1319        || visible
1320            .x
1321            .checked_add(visible.width)
1322            .is_none_or(|right| right > source.width)
1323        || visible
1324            .y
1325            .checked_add(visible.height)
1326            .is_none_or(|bottom| bottom > source.height)
1327    {
1328        Err(RenderError::InvalidImageData)
1329    } else {
1330        Ok(())
1331    }
1332}
1333
1334pub(crate) enum HdrHandling {
1335    /// An SDR signal, decoded as SDR.
1336    Sdr,
1337    /// An HDR signal tone-mapped into the working space.
1338    ToneMap(HdrToneMap),
1339    /// An HDR signal the policy skips: a transparent picture.
1340    Skip,
1341}
1342
1343/// How `policy` handles `color`; records the diagnostic.
1344pub(crate) fn hdr_handling(
1345    color: ColorMetadata,
1346    policy: ColorPolicy,
1347    diagnostics: &mut Vec<ColorDiagnostic>,
1348) -> Result<HdrHandling, RenderError> {
1349    if !crate::is_hdr(color) {
1350        return Ok(HdrHandling::Sdr);
1351    }
1352    match policy {
1353        ColorPolicy::RejectHdr => {
1354            diagnostics.push(ColorDiagnostic::UnsupportedHdr);
1355            Err(RenderError::UnsupportedHdr)
1356        }
1357        ColorPolicy::WarnHdr => {
1358            diagnostics.push(ColorDiagnostic::UnsupportedHdr);
1359            Ok(HdrHandling::Skip)
1360        }
1361        ColorPolicy::ToneMapHdr(tone) => {
1362            diagnostics.push(ColorDiagnostic::ToneMappedHdr);
1363            Ok(HdrHandling::ToneMap(tone))
1364        }
1365    }
1366}
1367
1368/// Clockwise quarter turns in bits 0-1; bit 2 set when the picture is mirrored first.
1369fn orientation_uniform(orientation: Orientation) -> u32 {
1370    orientation.rotation.quarter_turns() | (u32::from(orientation.mirror) << 2)
1371}
1372
1373fn draw_rect(presentation: SourcePresentation) -> [f64; 4] {
1374    let visible = presentation.visible_rect;
1375    let sar = f64::from(presentation.sample_aspect_ratio.0)
1376        / f64::from(presentation.sample_aspect_ratio.1);
1377    let unrotated_width = f64::from(visible.width) * sar;
1378    let unrotated_height = f64::from(visible.height);
1379    let (display_width, display_height) = if presentation.orientation.rotation.swaps_axes() {
1380        (unrotated_height, unrotated_width)
1381    } else {
1382        (unrotated_width, unrotated_height)
1383    };
1384    let scale = (f64::from(presentation.output_size.width) / display_width)
1385        .min(f64::from(presentation.output_size.height) / display_height);
1386    let draw_width = display_width * scale;
1387    let draw_height = display_height * scale;
1388    let draw_x = (f64::from(presentation.output_size.width) - draw_width) * 0.5;
1389    let draw_y = (f64::from(presentation.output_size.height) - draw_height) * 0.5;
1390    [draw_x, draw_y, draw_width, draw_height]
1391}
1392
1393/// Mirrors `filter_grid` in yuv-to-linear.wesl and rgba-present.wesl.
1394#[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
1395fn filter_samples(presentation: SourcePresentation, max_filter_samples: f32) -> u64 {
1396    let visible = presentation.visible_rect;
1397    let (extent_x, extent_y) = if presentation.orientation.rotation.swaps_axes() {
1398        (visible.height, visible.width)
1399    } else {
1400        (visible.width, visible.height)
1401    };
1402    let [_, _, draw_width, draw_height] = draw_rect(presentation);
1403    let wanted = |extent: u32, drawn: f64| {
1404        let footprint = f64::from(extent) / drawn;
1405        if footprint > 2.0 {
1406            (footprint - 0.0001).ceil().clamp(1.0, 8.0)
1407        } else {
1408            1.0
1409        }
1410    };
1411    let budget = f64::from(max_filter_samples).clamp(1.0, 64.0);
1412    let columns = wanted(extent_x, draw_width).min(budget);
1413    let rows = wanted(extent_y, draw_height).min((budget / columns).floor().max(1.0));
1414    (columns * rows) as u64
1415}
1416
1417const RGBA_SAMPLE_COST: crate::effect_cost::EffectCost =
1418    crate::effect_cost::EffectCost::fixed(1, 3);
1419
1420fn yuv_sample_cost(format: YuvFormat) -> crate::effect_cost::EffectCost {
1421    crate::effect_cost::EffectCost::fixed(
1422        u64::try_from(format.plane_count()).unwrap_or(u64::MAX),
1423        3,
1424    )
1425}
1426
1427pub(crate) fn conversion_work(
1428    presentation: SourcePresentation,
1429    max_filter_samples: f32,
1430    sample: crate::effect_cost::EffectCost,
1431) -> crate::FrameCost {
1432    crate::FrameCost::of(
1433        sample.times(filter_samples(presentation, max_filter_samples)),
1434        presentation.output_size.pixels(),
1435    )
1436}
1437
1438#[allow(clippy::cast_possible_truncation, clippy::cast_precision_loss)]
1439pub(crate) fn presentation_uniform_bytes(
1440    source: RenderSize,
1441    presentation: SourcePresentation,
1442    encoding: PresentedEncoding,
1443    max_filter_samples: f32,
1444) -> Vec<u8> {
1445    let visible = presentation.visible_rect;
1446    let [draw_x, draw_y, draw_width, draw_height] = draw_rect(presentation);
1447    let values = [
1448        presentation.output_size.width as f32,
1449        presentation.output_size.height as f32,
1450        source.width as f32,
1451        source.height as f32,
1452        visible.x as f32,
1453        visible.y as f32,
1454        visible.width as f32,
1455        visible.height as f32,
1456        draw_x as f32,
1457        draw_y as f32,
1458        draw_width as f32,
1459        draw_height as f32,
1460    ];
1461    let mut bytes = Vec::with_capacity(64);
1462    for value in values {
1463        bytes.extend_from_slice(&value.to_ne_bytes());
1464    }
1465    bytes.extend_from_slice(&orientation_uniform(presentation.orientation).to_ne_bytes());
1466    let mode = match encoding {
1467        PresentedEncoding::Srgb(SourceAlpha::Straight) => 0_u32,
1468        PresentedEncoding::Srgb(SourceAlpha::Premultiplied) => 1,
1469        PresentedEncoding::Linear => 2,
1470    };
1471    bytes.extend_from_slice(&mode.to_ne_bytes());
1472    bytes.extend_from_slice(&max_filter_samples.to_ne_bytes());
1473    bytes.extend_from_slice(&[0; 4]);
1474    bytes
1475}
1476
1477#[allow(
1478    clippy::cast_possible_truncation,
1479    clippy::cast_precision_loss,
1480    clippy::too_many_arguments
1481)]
1482pub(crate) fn uniform_bytes(
1483    color: ColorMetadata,
1484    tone: Option<HdrToneMap>,
1485    alpha: f32,
1486    source: RenderSize,
1487    presentation: SourcePresentation,
1488    format: YuvFormat,
1489    code_scale: f32,
1490    max_filter_samples: f32,
1491) -> Vec<u8> {
1492    let mut bytes = color_uniform_bytes(color, tone, alpha, format.bit_depth, code_scale);
1493    // Whether an alpha plane is read, and the scale to full range.
1494    let (alpha_plane, alpha_scale) = if format.alpha {
1495        (1_u32, code_scale)
1496    } else {
1497        (0, 0.0)
1498    };
1499    bytes[88..92].copy_from_slice(&alpha_plane.to_ne_bytes());
1500    bytes[92..96].copy_from_slice(&alpha_scale.to_ne_bytes());
1501    let visible = presentation.visible_rect;
1502    let [draw_x, draw_y, draw_width, draw_height] = draw_rect(presentation);
1503    let (chroma_width, chroma_height) = format.chroma_size(source.width, source.height);
1504    let chroma_size = [chroma_width as f32, chroma_height as f32];
1505    let factor_x = (1_u32 << format.chroma_shift_x) as f32;
1506    let factor_y = (1_u32 << format.chroma_shift_y) as f32;
1507    // A co-sited chroma sample sits `factor / 2 - 0.5` luma samples before its group's centre.
1508    let (cosited_x, cosited_y) = match presentation.chroma_siting.resolved_for(format) {
1509        ChromaLocation::Left => (true, false),
1510        ChromaLocation::TopLeft => (true, true),
1511        ChromaLocation::Unspecified | ChromaLocation::Center => (false, false),
1512    };
1513    let chroma_offset = [
1514        if cosited_x { factor_x * 0.5 - 0.5 } else { 0.0 },
1515        if cosited_y { factor_y * 0.5 - 0.5 } else { 0.0 },
1516    ];
1517    let presentation_values = [
1518        presentation.output_size.width as f32,
1519        presentation.output_size.height as f32,
1520        source.width as f32,
1521        source.height as f32,
1522        visible.x as f32,
1523        visible.y as f32,
1524        visible.width as f32,
1525        visible.height as f32,
1526        draw_x as f32,
1527        draw_y as f32,
1528        draw_width as f32,
1529        draw_height as f32,
1530        chroma_size[0],
1531        chroma_size[1],
1532        chroma_offset[0],
1533        chroma_offset[1],
1534    ];
1535    for value in presentation_values {
1536        bytes.extend_from_slice(&value.to_ne_bytes());
1537    }
1538    bytes.extend_from_slice(&orientation_uniform(presentation.orientation).to_ne_bytes());
1539    let plane_layout = u32::from(format.interleaved_chroma);
1540    bytes.extend_from_slice(&plane_layout.to_ne_bytes());
1541    for scale in [1.0 / factor_x, 1.0 / factor_y] {
1542        bytes.extend_from_slice(&scale.to_ne_bytes());
1543    }
1544    bytes.extend(hdr_uniform_bytes(color, tone));
1545    for bound in chroma_window(visible, format) {
1546        bytes.extend_from_slice(&bound.to_ne_bytes());
1547    }
1548    for value in [max_filter_samples, 0.0, 0.0, 0.0] {
1549        bytes.extend_from_slice(&value.to_ne_bytes());
1550    }
1551    bytes
1552}
1553
1554/// First and last chroma sample centres (`[x0, y0, x1, y1]`) whose luma group reaches into
1555/// `visible`.
1556///
1557/// Chroma sampling is clamped to these so decoder-surface padding never bleeds into the last
1558/// row or column.
1559#[allow(clippy::cast_precision_loss)]
1560fn chroma_window(visible: Rect, format: YuvFormat) -> [f32; 4] {
1561    let first = |origin: u32, shift: u8| (origin >> shift) as f32 + 0.5;
1562    let last =
1563        |origin: u32, length: u32, shift: u8| (origin + length).div_ceil(1 << shift) as f32 - 0.5;
1564    [
1565        first(visible.x, format.chroma_shift_x),
1566        first(visible.y, format.chroma_shift_y),
1567        last(visible.x, visible.width, format.chroma_shift_x),
1568        last(visible.y, visible.height, format.chroma_shift_y),
1569    ]
1570}
1571
1572/// HDR uniform part: primaries matrix to BT.709, tone-map peaks and their PQ codes, HLG system
1573/// gamma.
1574fn hdr_uniform_bytes(color: ColorMetadata, tone: Option<HdrToneMap>) -> Vec<u8> {
1575    let gamut = crate::hdr::gamut_matrix(color.primaries, ColorPrimaries::Bt709);
1576    let tone = tone.unwrap_or_default();
1577    #[allow(clippy::cast_precision_loss)]
1578    let peak = tone.source_peak_nits as f32;
1579    let white = crate::hdr::SDR_WHITE_NITS;
1580    let gamma = 1.2 + 0.42 * libm::log10f(peak / 1_000.0);
1581    let mut bytes = Vec::with_capacity(80);
1582    for value in gamut
1583        .into_iter()
1584        .flat_map(|row| [row[0], row[1], row[2], 0.0])
1585        .chain([
1586            peak,
1587            white,
1588            crate::hdr::pq_inverse_eotf(peak),
1589            crate::hdr::pq_inverse_eotf(white),
1590            gamma,
1591            0.0,
1592            0.0,
1593            0.0,
1594        ])
1595    {
1596        bytes.extend_from_slice(&value.to_ne_bytes());
1597    }
1598    bytes
1599}
1600
1601fn color_uniform_bytes(
1602    color: ColorMetadata,
1603    tone: Option<HdrToneMap>,
1604    alpha: f32,
1605    bit_depth: u8,
1606    code_scale: f32,
1607) -> Vec<u8> {
1608    // 0 = SDR with the sRGB EOTF; 1 = PQ and 2 = HLG via the tone map.
1609    let transfer: u32 = match (tone, color.transfer) {
1610        (Some(_), TransferFunction::Pq) => 1,
1611        (Some(_), TransferFunction::Hlg) => 2,
1612        _ => 0,
1613    };
1614    if color.matrix == ColorMatrix::Rgb {
1615        return identity_rgb_uniform_bytes(alpha, transfer, code_scale);
1616    }
1617    let (kr, kb) = color
1618        .matrix
1619        .luma_weights()
1620        .expect("RGB components are handled above");
1621    let kg = 1.0 - kr - kb;
1622    let rows = [
1623        [1.0, 0.0, 2.0 * (1.0 - kr), 0.0],
1624        [
1625            1.0,
1626            -2.0 * kb * (1.0 - kb) / kg,
1627            -2.0 * kr * (1.0 - kr) / kg,
1628            0.0,
1629        ],
1630        [1.0, 2.0 * (1.0 - kb), 0.0, 0.0],
1631    ];
1632    let (scale, offset) = range_scale_offset(color.range, bit_depth, code_scale);
1633    let mut bytes = Vec::with_capacity(96);
1634    for value in rows.into_iter().flatten().chain(scale).chain(offset) {
1635        bytes.extend_from_slice(&value.to_ne_bytes());
1636    }
1637    bytes.extend_from_slice(&transfer.to_ne_bytes());
1638    bytes.extend_from_slice(&alpha.to_ne_bytes());
1639    bytes.extend_from_slice(&[0; 8]);
1640    bytes
1641}
1642
1643/// Component scale and offset mapping sampled codes to normalized YCbCr.
1644///
1645/// Levels come from [`ColorRange::levels`](alpha2_media::ColorRange::levels), shared with export.
1646/// `code` is [`PlaneStorage::code_scale`].
1647fn range_scale_offset(range: ColorRange, depth: u8, code: f32) -> ([f32; 4], [f32; 4]) {
1648    let levels = range.levels(depth);
1649    let (luma_scale, chroma_scale) = match range {
1650        ColorRange::Full => (code, code),
1651        ColorRange::Limited => (
1652            code * levels.maximum / levels.luma_span,
1653            code * levels.maximum / levels.chroma_span,
1654        ),
1655    };
1656    let chroma_offset = 0.0 - levels.chroma_center / levels.chroma_span;
1657    (
1658        [luma_scale, chroma_scale, chroma_scale, 0.0],
1659        [
1660            0.0 - levels.luma_black / levels.luma_span,
1661            chroma_offset,
1662            chroma_offset,
1663            0.0,
1664        ],
1665    )
1666}
1667
1668/// The identity matrix over RGB codes; `code` is [`PlaneStorage::code_scale`]. The range flag is
1669/// ignored: untagged RGB reads as limited, and RGB codes are always full range.
1670fn identity_rgb_uniform_bytes(alpha: f32, transfer: u32, code: f32) -> Vec<u8> {
1671    let rows = [
1672        [1.0_f32, 0.0, 0.0, 0.0],
1673        [0.0_f32, 1.0, 0.0, 0.0],
1674        [0.0_f32, 0.0, 1.0, 0.0],
1675    ];
1676    let mut bytes = Vec::with_capacity(96);
1677    for value in rows
1678        .into_iter()
1679        .flatten()
1680        .chain([code, code, code, 0.0])
1681        .chain([0.0; 4])
1682    {
1683        bytes.extend_from_slice(&value.to_ne_bytes());
1684    }
1685    bytes.extend_from_slice(&transfer.to_ne_bytes());
1686    bytes.extend_from_slice(&alpha.to_ne_bytes());
1687    bytes.extend_from_slice(&[0; 8]);
1688    bytes
1689}
1690
1691#[cfg(test)]
1692mod tests {
1693    use super::*;
1694    use alpha2_media::{ColorPrimaries, DynamicRange};
1695
1696    #[test]
1697    fn parked_leases_are_dropped_only_when_drained() {
1698        // Runs under the decoder queue lock; dropping an `FFmpeg` frame here would deadlock.
1699        #[derive(Debug)]
1700        struct CountingLease(Arc<std::sync::atomic::AtomicUsize>);
1701
1702        impl Drop for CountingLease {
1703            fn drop(&mut self) {
1704                self.0.fetch_add(1, Ordering::Release);
1705            }
1706        }
1707
1708        impl ExternalTextureLease for CountingLease {
1709            fn retained_bytes(&self) -> u64 {
1710                0
1711            }
1712        }
1713
1714        let drops = Arc::new(std::sync::atomic::AtomicUsize::new(0));
1715        let retired = RetiredLeases::default();
1716        let lease: Arc<dyn ExternalTextureLease> = Arc::new(CountingLease(Arc::clone(&drops)));
1717        retired.park(vec![lease]);
1718        assert_eq!(drops.load(Ordering::Acquire), 0, "parking must not release");
1719        retired.drain();
1720        assert_eq!(drops.load(Ordering::Acquire), 1, "drain must release");
1721        retired.drain();
1722        assert_eq!(drops.load(Ordering::Acquire), 1, "drain must be idempotent");
1723    }
1724
1725    #[test]
1726    fn ten_bit_limited_range_normalizes_the_p010_container() {
1727        let (scale, offset) = range_scale_offset(
1728            ColorRange::Limited,
1729            10,
1730            PlaneStorage::Unorm16.code_scale(YuvFormat::P010),
1731        );
1732        // A limited-range 10-bit black sample is code 64, stored as 64 << 6.
1733        let black = f32::from(64_u16 << 6) / 65535.0;
1734        assert!((black * scale[0] + offset[0]).abs() < 1e-4);
1735        // Nominal white is code 940.
1736        let white = f32::from(940_u16 << 6) / 65535.0;
1737        assert!((white * scale[0] + offset[0] - 1.0).abs() < 1e-4);
1738        // Neutral chroma is code 512.
1739        let neutral = f32::from(512_u16 << 6) / 65535.0;
1740        assert!((neutral * scale[1] + offset[1]).abs() < 1e-4);
1741    }
1742
1743    #[test]
1744    fn integer_containers_take_the_scale_normalized_ones_do() {
1745        // The integer build reads `container / 65535`, as an R16Unorm texture samples it.
1746        for format in [YuvFormat::planar(1, 1, 10), YuvFormat::P010] {
1747            assert_eq!(
1748                PlaneStorage::Uint16.code_scale(format).to_bits(),
1749                PlaneStorage::Unorm16.code_scale(format).to_bits()
1750            );
1751        }
1752        assert_eq!(
1753            PlaneStorage::Uint16.texture_format(false),
1754            wgpu::TextureFormat::R16Uint
1755        );
1756        assert_eq!(
1757            PlaneStorage::Uint16.texture_format(true),
1758            wgpu::TextureFormat::Rg16Uint
1759        );
1760    }
1761
1762    #[test]
1763    fn eight_bit_range_constants_are_unchanged() {
1764        let bits = |values: [f32; 4]| values.map(f32::to_bits);
1765        let (scale, offset) = range_scale_offset(ColorRange::Limited, 8, 1.0);
1766        assert_eq!(
1767            bits(scale),
1768            bits([255.0 / 219.0, 255.0 / 224.0, 255.0 / 224.0, 0.0])
1769        );
1770        assert_eq!(
1771            bits(offset),
1772            bits([-16.0 / 219.0, -128.0 / 224.0, -128.0 / 224.0, 0.0])
1773        );
1774        let (scale, offset) = range_scale_offset(ColorRange::Full, 8, 1.0);
1775        assert_eq!(bits(scale), bits([1.0, 1.0, 1.0, 0.0]));
1776        assert_eq!(
1777            bits(offset),
1778            bits([0.0, -128.0 / 255.0, -128.0 / 255.0, 0.0])
1779        );
1780    }
1781
1782    #[test]
1783    fn rgb_uniform_uses_identity_matrix_without_chroma_offsets() {
1784        let bytes = uniform_bytes(
1785            ColorMetadata {
1786                primaries: ColorPrimaries::Bt709,
1787                transfer: TransferFunction::Srgb,
1788                matrix: ColorMatrix::Rgb,
1789                range: ColorRange::Limited,
1790                dynamic_range: DynamicRange::Sdr,
1791            },
1792            None,
1793            1.0,
1794            RenderSize::new(2, 2).expect("size"),
1795            SourcePresentation::identity(RenderSize::new(2, 2).expect("size")),
1796            YuvFormat::I420,
1797            1.0,
1798            64.0,
1799        );
1800        let floats = bytes[..80]
1801            .as_chunks::<4>()
1802            .0
1803            .iter()
1804            .map(|bytes| f32::from_ne_bytes(*bytes))
1805            .collect::<Vec<_>>();
1806        assert_eq!(
1807            floats.into_iter().map(f32::to_bits).collect::<Vec<_>>(),
1808            vec![
1809                1.0, 0.0, 0.0, 0.0, // matrix row 0
1810                0.0, 1.0, 0.0, 0.0, // matrix row 1
1811                0.0, 0.0, 1.0, 0.0, // matrix row 2
1812                1.0, 1.0, 1.0, 0.0, // component scale
1813                0.0, 0.0, 0.0, 0.0, // component offset
1814            ]
1815            .into_iter()
1816            .map(f32::to_bits)
1817            .collect::<Vec<_>>()
1818        );
1819    }
1820
1821    #[test]
1822    fn an_unspecified_siting_of_horizontally_subsampled_chroma_is_left() {
1823        let size = RenderSize::new(16, 4).expect("size");
1824        let bytes = |format, siting| {
1825            uniform_bytes(
1826                ColorMetadata::EXPORT,
1827                None,
1828                1.0,
1829                size,
1830                SourcePresentation {
1831                    chroma_siting: siting,
1832                    ..SourcePresentation::identity(size)
1833                },
1834                format,
1835                1.0,
1836                64.0,
1837            )
1838        };
1839        for format in [YuvFormat::planar(1, 0, 10), YuvFormat::planar(2, 0, 8)] {
1840            assert_eq!(
1841                bytes(format, ChromaLocation::Unspecified),
1842                bytes(format, ChromaLocation::Left),
1843                "{format:?}"
1844            );
1845        }
1846        assert_eq!(
1847            bytes(YuvFormat::I420, ChromaLocation::Unspecified),
1848            bytes(YuvFormat::I420, ChromaLocation::Center)
1849        );
1850        assert_ne!(
1851            bytes(YuvFormat::I420, ChromaLocation::Unspecified),
1852            bytes(YuvFormat::I420, ChromaLocation::Left)
1853        );
1854    }
1855
1856    #[test]
1857    fn rgb_uniform_scales_ten_bit_codes_to_full_range() {
1858        let code_scale = 65535.0 / 1023.0;
1859        let bytes = uniform_bytes(
1860            ColorMetadata {
1861                primaries: ColorPrimaries::Bt2020,
1862                transfer: TransferFunction::Bt709,
1863                matrix: ColorMatrix::Rgb,
1864                range: ColorRange::Full,
1865                dynamic_range: DynamicRange::Sdr,
1866            },
1867            None,
1868            1.0,
1869            RenderSize::new(2, 2).expect("size"),
1870            SourcePresentation::identity(RenderSize::new(2, 2).expect("size")),
1871            YuvFormat::planar(0, 0, 10),
1872            code_scale,
1873            64.0,
1874        );
1875        let scale = bytes[48..64]
1876            .as_chunks::<4>()
1877            .0
1878            .iter()
1879            .map(|bytes| f32::from_ne_bytes(*bytes).to_bits())
1880            .collect::<Vec<_>>();
1881        assert_eq!(
1882            scale,
1883            [code_scale, code_scale, code_scale, 0.0].map(f32::to_bits)
1884        );
1885    }
1886
1887    #[test]
1888    fn the_chroma_window_is_the_visible_pictures_chroma() {
1889        let window = |x, y, width, height, format| {
1890            chroma_window(
1891                Rect {
1892                    x,
1893                    y,
1894                    width,
1895                    height,
1896                },
1897                format,
1898            )
1899            .map(f32::to_bits)
1900        };
1901        let bits = |bounds: [f32; 4]| bounds.map(f32::to_bits);
1902        // 1080p decoded into 1920 x 1088: chroma rows 540..544 are padding.
1903        assert_eq!(
1904            window(0, 0, 1920, 1080, YuvFormat::I420),
1905            bits([0.5, 0.5, 959.5, 539.5])
1906        );
1907        // 1366 wide in a 1376 surface: the last column's chroma is sample 682.
1908        assert_eq!(
1909            window(0, 0, 1366, 768, YuvFormat::I420),
1910            bits([0.5, 0.5, 682.5, 383.5])
1911        );
1912        // An odd crop keeps the chroma sample its first luma column shares.
1913        assert_eq!(
1914            window(1, 3, 5, 4, YuvFormat::I420),
1915            bits([0.5, 1.5, 2.5, 3.5])
1916        );
1917        assert_eq!(
1918            window(2, 1, 3, 2, YuvFormat::planar(0, 0, 8)),
1919            bits([2.5, 1.5, 4.5, 2.5])
1920        );
1921    }
1922}