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/// Borrowed views of a decoded YCbCr frame already resident on the GPU.
541#[derive(Copy, Clone, Debug)]
542#[cfg_attr(not(feature = "wgpu-interop"), doc(hidden))]
543pub struct GpuVideoPlanes<'a> {
544    /// Luma view.
545    pub y: &'a wgpu::TextureView,
546    /// U view, or the interleaved UV view.
547    pub chroma: &'a wgpu::TextureView,
548    /// V view; absent when chroma is interleaved.
549    pub v: Option<&'a wgpu::TextureView>,
550    /// `R8`/`RG8` for 8-bit, `R16`/`RG16` normalized above.
551    pub format: YuvFormat,
552    /// Coded dimensions.
553    pub size: RenderSize,
554    /// Straight source alpha.
555    pub alpha: f32,
556    /// Optional stream color metadata.
557    pub color: Option<ColorMetadata>,
558}
559
560impl Renderer {
561    /// Prepares an uploaded RGBA texture for presentation by its first consumer, without
562    /// submitting.
563    ///
564    /// # Errors
565    /// Returns an image-data error for invalid presentation metadata.
566    pub fn prepare_rgba_presented(
567        &self,
568        source: UploadTexture,
569        source_size: RenderSize,
570        presentation: SourcePresentation,
571        alpha: SourceAlpha,
572    ) -> Result<PreparedSourceTexture, RenderError> {
573        let view = source.view().clone();
574        let prepared = self.prepare_rgba_presented_inner(
575            &view,
576            source_size,
577            presentation,
578            PresentedEncoding::Srgb(alpha),
579            vec![source],
580        )?;
581        Ok(prepared)
582    }
583
584    /// Prepares premultiplied linear BT.709 RGBA ([`Self::upload_linear_rgba16f`]) like
585    /// [`Self::prepare_rgba_presented`].
586    ///
587    /// Filtered in linear light, then stored sRGB-encoded and premultiplied with the curve extended
588    /// beyond `[0, 1]` as far as the intermediate holds. Color under zero alpha is dropped.
589    ///
590    /// # Errors
591    /// Returns an image-data error for invalid presentation metadata.
592    pub fn prepare_linear_presented(
593        &self,
594        source: UploadTexture,
595        source_size: RenderSize,
596        presentation: SourcePresentation,
597    ) -> Result<PreparedSourceTexture, RenderError> {
598        let view = source.view().clone();
599        self.prepare_rgba_presented_inner(
600            &view,
601            source_size,
602            presentation,
603            PresentedEncoding::Linear,
604            vec![source],
605        )
606    }
607
608    /// Uploads a straight-alpha RGBA8 plane and prepares it like [`Self::prepare_rgba_presented`].
609    ///
610    /// # Errors
611    /// Returns an image-data error for a short plane or invalid presentation metadata.
612    pub fn prepare_rgba8_presented(
613        &self,
614        pixels: SourcePlane<'_>,
615        size: RenderSize,
616        presentation: SourcePresentation,
617    ) -> Result<PreparedSourceTexture, RenderError> {
618        let texture = self.write_rgba8(size, pixels)?;
619        self.prepare_rgba_presented(texture, size, presentation, SourceAlpha::Straight)
620    }
621
622    pub(crate) fn prepare_rgba_presented_inner(
623        &self,
624        source_view: &wgpu::TextureView,
625        source_size: RenderSize,
626        presentation: SourcePresentation,
627        encoding: PresentedEncoding,
628        inputs: Vec<UploadTexture>,
629    ) -> Result<PreparedSourceTexture, RenderError> {
630        self.validate_size(source_size)?;
631        self.validate_size(presentation.output_size)?;
632        validate_presentation(source_size, presentation)?;
633        let output_format = self.intermediate_format();
634        let output = self.textures.acquire(
635            self.gpu.device(),
636            presentation.output_size,
637            output_format,
638            "alpha2 RGBA presentation target",
639        );
640        let cached = self.rgba_presentation_pipeline()?;
641        let uniform_bytes = presentation_uniform_bytes(
642            source_size,
643            presentation,
644            encoding,
645            self.presentation_filter_samples(),
646        );
647        let output_view = output.view().clone();
648        Ok(PreparedSourceTexture {
649            texture: RenderedTexture::pooled(presentation.output_size, output_format, output),
650            pending: Some(PendingSourceWork::new(SourceWork {
651                label: "alpha2 RGBA presentation pass",
652                conversion: true,
653                pipeline: cached.pipeline.clone(),
654                layout: cached.bind_group_layout.clone(),
655                textures: [(0, source_view.clone())].into_iter().collect(),
656                uniform_binding: 1,
657                uniform: uniform_bytes,
658                sampler: Some(self.linear_sampler.group.clone()),
659                output_view,
660                output_size: presentation.output_size,
661                work: conversion_work(
662                    presentation,
663                    self.presentation_filter_samples(),
664                    RGBA_SAMPLE_COST,
665                ),
666                uploads: inputs,
667                external_leases: Vec::new(),
668            })),
669        })
670    }
671
672    /// Submits one pending source presentation now.
673    ///
674    /// Returns `false` when another consumer already did, or when staging or submission fails;
675    /// the work then stays pending for a later frame.
676    pub fn submit_pending_source(&self, pending: &PendingSourceWork) -> bool {
677        let frame = self.frame_lock.hold();
678        let Some(ticket) = pending.begin(&frame) else {
679            return false;
680        };
681        let mut encoder = self.command_encoder("alpha2 source presentation encoder");
682        let mut uniforms = self
683            .uniform_buffers
684            .acquire(self.gpu.device(), ticket.uniform_bytes());
685        if ticket.encode(self, &mut encoder, &mut uniforms).is_err() {
686            return false;
687        }
688        uniforms.flush(self.gpu.queue());
689        if !ticket.prepare_submission() || ticket.flush_submission().is_err() {
690            return false;
691        }
692        if self.submit([encoder.finish()]).is_err() {
693            return false;
694        }
695        uniforms.recycle();
696        ticket.complete(self, true);
697        true
698    }
699
700    /// Uploads YUV planes and converts them on the GPU to premultiplied sRGB storage.
701    /// Transfer decoding precedes sRGB encoding and premultiplication.
702    ///
703    /// # Errors
704    /// An image-data error for malformed planes or alpha, and [`RenderError::UnsupportedHdr`] when
705    /// [`ColorPolicy::RejectHdr`] meets an HDR source.
706    #[allow(clippy::too_many_lines)]
707    pub fn render_yuv420p(
708        &self,
709        frame: Yuv420Frame<'_>,
710        policy: ColorPolicy,
711    ) -> Result<(RenderedTexture, Vec<ColorDiagnostic>), RenderError> {
712        self.render_yuv420p_presented(frame, SourcePresentation::identity(frame.size), policy)
713    }
714
715    fn rgba_presentation_pipeline(&self) -> Result<&CachedSampledPipeline, RenderError> {
716        crate::gpu_errors::checked_cell(&self.pipelines.rgba_present, self.gpu.device(), || {
717            let output_format = self.intermediate_format();
718            let bind_group_layout =
719                self.gpu
720                    .device()
721                    .create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
722                        label: Some("alpha2 RGBA presentation layout"),
723                        entries: &[
724                            wgpu::BindGroupLayoutEntry {
725                                binding: 0,
726                                visibility: wgpu::ShaderStages::FRAGMENT,
727                                ty: wgpu::BindingType::Texture {
728                                    sample_type: wgpu::TextureSampleType::Float {
729                                        filterable: true,
730                                    },
731                                    view_dimension: wgpu::TextureViewDimension::D2,
732                                    multisampled: false,
733                                },
734                                count: None,
735                            },
736                            wgpu::BindGroupLayoutEntry {
737                                binding: 1,
738                                visibility: wgpu::ShaderStages::FRAGMENT,
739                                ty: wgpu::BindingType::Buffer {
740                                    ty: wgpu::BufferBindingType::Uniform,
741                                    has_dynamic_offset: true,
742                                    min_binding_size: None,
743                                },
744                                count: None,
745                            },
746                        ],
747                    });
748            let shader = self
749                .gpu
750                .device()
751                .create_shader_module(wgpu::ShaderModuleDescriptor {
752                    label: Some("alpha2 RGBA presentation shader"),
753                    source: wgpu::ShaderSource::Wgsl(RGBA_PRESENT_WGSL.into()),
754                });
755            let layout =
756                self.gpu
757                    .device()
758                    .create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
759                        label: Some("alpha2 RGBA presentation pipeline layout"),
760                        bind_group_layouts: &[
761                            Some(&bind_group_layout),
762                            Some(&self.linear_sampler.layout),
763                        ],
764                        immediate_size: 0,
765                    });
766            let pipeline =
767                self.gpu
768                    .device()
769                    .create_render_pipeline(&wgpu::RenderPipelineDescriptor {
770                        label: Some("alpha2 RGBA presentation pipeline"),
771                        layout: Some(&layout),
772                        vertex: wgpu::VertexState {
773                            module: &shader,
774                            entry_point: Some("vs"),
775                            buffers: &[],
776                            compilation_options: wgpu::PipelineCompilationOptions::default(),
777                        },
778                        fragment: Some(wgpu::FragmentState {
779                            module: &shader,
780                            entry_point: Some("fs"),
781                            targets: &[Some(output_format.into())],
782                            compilation_options: wgpu::PipelineCompilationOptions::default(),
783                        }),
784                        primitive: wgpu::PrimitiveState::default(),
785                        depth_stencil: None,
786                        multisample: wgpu::MultisampleState::default(),
787                        multiview_mask: None,
788                        cache: None,
789                    });
790            CachedSampledPipeline {
791                bind_group_layout,
792                pipeline,
793            }
794        })
795    }
796
797    /// Uploads and converts YUV420P with crop, sample aspect, rotation, scaling (bilinear,
798    /// footprint-averaged when shrinking) and transparent contain placement on the GPU.
799    ///
800    /// # Errors
801    /// An image-data error for malformed planes, metadata or alpha, and
802    /// [`RenderError::UnsupportedHdr`] when [`ColorPolicy::RejectHdr`] meets an HDR source.
803    #[allow(clippy::too_many_lines, clippy::cast_possible_truncation)]
804    pub fn render_yuv420p_presented(
805        &self,
806        frame: Yuv420Frame<'_>,
807        presentation: SourcePresentation,
808        policy: ColorPolicy,
809    ) -> Result<(RenderedTexture, Vec<ColorDiagnostic>), RenderError> {
810        let (prepared, diagnostics) =
811            self.prepare_yuv420p_presented(frame, presentation, policy)?;
812        let (texture, pending) = prepared.into_parts();
813        if let Some(pending) = pending {
814            self.submit_pending_source(&pending);
815        }
816        Ok((texture, diagnostics))
817    }
818
819    /// Uploads YUV420 planes and defers their conversion to the first consuming frame's encoder.
820    ///
821    /// # Errors
822    /// An image-data error for malformed input, and [`RenderError::UnsupportedHdr`] when
823    /// [`ColorPolicy::RejectHdr`] meets an HDR source.
824    #[allow(clippy::too_many_lines, clippy::cast_possible_truncation)]
825    pub fn prepare_yuv420p_presented(
826        &self,
827        frame: Yuv420Frame<'_>,
828        presentation: SourcePresentation,
829        policy: ColorPolicy,
830    ) -> Result<(PreparedSourceTexture, Vec<ColorDiagnostic>), RenderError> {
831        self.prepare_yuv_presented(frame.into(), presentation, policy)
832    }
833
834    /// Uploads planar or semi-planar YCbCr of any supported subsampling and depth, prepared like
835    /// [`Self::prepare_yuv420p_presented`].
836    ///
837    /// Samples above 8 bits upload as 16-bit normalized textures, or as `u16` containers the GPU
838    /// normalizes on devices without them.
839    ///
840    /// # Errors
841    /// An image-data error for an unsupported format or malformed planes, and
842    /// [`RenderError::UnsupportedHdr`] when [`ColorPolicy::RejectHdr`] meets an HDR source.
843    pub fn prepare_yuv_presented(
844        &self,
845        frame: YuvFrame<'_>,
846        presentation: SourcePresentation,
847        policy: ColorPolicy,
848    ) -> Result<(PreparedSourceTexture, Vec<ColorDiagnostic>), RenderError> {
849        let mut diagnostics = Vec::new();
850        let color = frame.color.unwrap_or_else(|| {
851            diagnostics.push(ColorDiagnostic::MissingMetadataFallback);
852            ColorMetadata::UNDECLARED
853        });
854        let tone = match hdr_handling(color, policy, &mut diagnostics)? {
855            HdrHandling::Sdr => None,
856            HdrHandling::ToneMap(tone) => Some(tone),
857            HdrHandling::Skip => {
858                return self
859                    .render_solid(presentation.output_size, Color::rgba(0.0, 0.0, 0.0, 0.0))
860                    .map(|texture| {
861                        (
862                            PreparedSourceTexture {
863                                texture,
864                                pending: None,
865                            },
866                            diagnostics,
867                        )
868                    });
869            }
870        };
871        let format = frame.format;
872        if !frame.alpha.is_finite()
873            || !(0.0..=1.0).contains(&frame.alpha)
874            || !format.is_supported()
875            || format.alpha != frame.alpha_plane.is_some()
876        {
877            return Err(RenderError::InvalidImageData);
878        }
879        self.validate_size(presentation.output_size)?;
880        validate_presentation(frame.size, presentation)?;
881        let storage = if format.bytes_per_sample() == 1 {
882            PlaneStorage::Unorm8
883        } else if self
884            .features
885            .contains(wgpu::Features::TEXTURE_FORMAT_16BIT_NORM)
886        {
887            PlaneStorage::Unorm16
888        } else {
889            PlaneStorage::Uint16
890        };
891        let (chroma_width, chroma_height) = format.chroma_size(frame.size.width, frame.size.height);
892        let pairs = if format.interleaved_chroma { 2 } else { 1 };
893        let plane_specs = [
894            ("alpha2 Y plane", frame.size.width, frame.size.height, 1_u32),
895            ("alpha2 U plane", chroma_width, chroma_height, pairs),
896            ("alpha2 V plane", chroma_width, chroma_height, 1),
897        ];
898        let mut uploads = Vec::with_capacity(format.plane_count());
899        let alpha_spec = ("alpha2 A plane", frame.size.width, frame.size.height, 1_u32);
900        for (plane, (label, width, height, samples)) in frame
901            .planes
902            .iter()
903            .zip(plane_specs)
904            .take(format.color_plane_count())
905            .chain(frame.alpha_plane.iter().map(|plane| (plane, alpha_spec)))
906        {
907            let row_bytes = width
908                .checked_mul(samples)
909                .and_then(|row| row.checked_mul(format.bytes_per_sample()))
910                .ok_or(RenderError::InvalidImageData)?;
911            validate_plane(plane.bytes, plane.stride, row_bytes, height)?;
912            uploads.push(upload_plane(
913                self,
914                label,
915                *plane,
916                (width, height),
917                storage.texture_format(samples == 2),
918            )?);
919        }
920        let mut views = uploads
921            .iter()
922            .map(|upload| upload.view().clone())
923            .collect::<Vec<_>>();
924        let alpha_view = format.alpha.then(|| views.pop()).flatten();
925        let planes = GpuVideoPlanes {
926            y: &views[0],
927            chroma: &views[1],
928            v: views.get(2),
929            format,
930            size: frame.size,
931            alpha: frame.alpha,
932            color: Some(color),
933        };
934        let prepared = self.prepare_gpu_yuv_presented_inner(
935            planes,
936            alpha_view.as_ref(),
937            presentation,
938            tone,
939            storage,
940            uploads,
941            Vec::new(),
942        )?;
943        Ok((prepared, diagnostics))
944    }
945
946    /// Prepares conversion of native GPU video planes without a CPU copy.
947    ///
948    /// The lease is held until queue completion. I420 takes three R8 views; NV12 takes R8 luma and
949    /// RG8 chroma.
950    ///
951    /// # Errors
952    /// An image-data error for an invalid plane contract, and [`RenderError::UnsupportedHdr`] when
953    /// [`ColorPolicy::RejectHdr`] meets an HDR source.
954    #[cfg_attr(not(feature = "wgpu-interop"), doc(hidden))]
955    pub fn prepare_gpu_yuv_presented(
956        &self,
957        planes: GpuVideoPlanes<'_>,
958        presentation: SourcePresentation,
959        policy: ColorPolicy,
960        lease: Arc<dyn ExternalTextureLease>,
961    ) -> Result<(PreparedSourceTexture, Vec<ColorDiagnostic>), RenderError> {
962        let mut diagnostics = Vec::new();
963        let color = planes.color.unwrap_or_else(|| {
964            diagnostics.push(ColorDiagnostic::MissingMetadataFallback);
965            ColorMetadata::UNDECLARED
966        });
967        let tone = match hdr_handling(color, policy, &mut diagnostics)? {
968            HdrHandling::Sdr => None,
969            HdrHandling::ToneMap(tone) => Some(tone),
970            HdrHandling::Skip => {
971                return self
972                    .render_solid(presentation.output_size, Color::rgba(0.0, 0.0, 0.0, 0.0))
973                    .map(|texture| {
974                        (
975                            PreparedSourceTexture {
976                                texture,
977                                pending: None,
978                            },
979                            diagnostics,
980                        )
981                    });
982            }
983        };
984        let planes = GpuVideoPlanes {
985            color: Some(color),
986            ..planes
987        };
988        let storage = if planes.format.bytes_per_sample() == 1 {
989            PlaneStorage::Unorm8
990        } else {
991            PlaneStorage::Unorm16
992        };
993        let prepared = self.prepare_gpu_yuv_presented_inner(
994            planes,
995            None,
996            presentation,
997            tone,
998            storage,
999            Vec::new(),
1000            vec![lease],
1001        )?;
1002        Ok((prepared, diagnostics))
1003    }
1004
1005    pub(crate) fn prepare_pilot_conversion(
1006        &self,
1007        planes: GpuVideoPlanes<'_>,
1008        size: RenderSize,
1009    ) -> Result<PreparedSourceTexture, RenderError> {
1010        self.prepare_gpu_yuv_presented_inner(
1011            planes,
1012            None,
1013            SourcePresentation::identity(size),
1014            None,
1015            PlaneStorage::Unorm8,
1016            Vec::new(),
1017            Vec::new(),
1018        )
1019    }
1020
1021    #[allow(clippy::too_many_arguments)]
1022    fn prepare_gpu_yuv_presented_inner(
1023        &self,
1024        planes: GpuVideoPlanes<'_>,
1025        alpha_plane: Option<&wgpu::TextureView>,
1026        presentation: SourcePresentation,
1027        tone: Option<HdrToneMap>,
1028        storage: PlaneStorage,
1029        uploads: Vec<UploadTexture>,
1030        external_leases: Vec<Arc<dyn ExternalTextureLease>>,
1031    ) -> Result<PreparedSourceTexture, RenderError> {
1032        if !planes.alpha.is_finite() || !(0.0..=1.0).contains(&planes.alpha) {
1033            return Err(RenderError::InvalidImageData);
1034        }
1035        if !planes.format.is_supported()
1036            || planes.format.interleaved_chroma == planes.v.is_some()
1037            || planes.format.alpha != alpha_plane.is_some()
1038        {
1039            return Err(RenderError::InvalidImageData);
1040        }
1041        self.validate_size(planes.size)?;
1042        self.validate_size(presentation.output_size)?;
1043        validate_presentation(planes.size, presentation)?;
1044        let color = planes.color.unwrap_or_default();
1045        let output_format = self.intermediate_format();
1046        let output = self.textures.acquire(
1047            self.gpu.device(),
1048            presentation.output_size,
1049            output_format,
1050            "alpha2 YUV conversion target",
1051        );
1052        let output_view = output.view().clone();
1053        let cached = self.yuv_pipeline(storage == PlaneStorage::Uint16)?;
1054        let uniform_bytes = uniform_bytes(
1055            color,
1056            tone,
1057            planes.alpha,
1058            planes.size,
1059            presentation,
1060            planes.format,
1061            storage.code_scale(planes.format),
1062            self.presentation_filter_samples(),
1063        );
1064        let textures = [
1065            (0, planes.y),
1066            (1, planes.chroma),
1067            (2, planes.v.unwrap_or(planes.chroma)),
1068            (4, alpha_plane.unwrap_or(planes.y)),
1069        ]
1070        .into_iter()
1071        .map(|(binding, view)| (binding, view.clone()))
1072        .collect();
1073        Ok(PreparedSourceTexture {
1074            texture: RenderedTexture::pooled(presentation.output_size, output_format, output),
1075            pending: Some(PendingSourceWork::new(SourceWork {
1076                label: "alpha2 YUV conversion pass",
1077                conversion: true,
1078                pipeline: cached.pipeline.clone(),
1079                layout: cached.bind_group_layout.clone(),
1080                textures,
1081                uniform_binding: 3,
1082                uniform: uniform_bytes,
1083                sampler: Some(self.linear_sampler.group.clone()),
1084                output_view,
1085                output_size: presentation.output_size,
1086                work: conversion_work(
1087                    presentation,
1088                    self.presentation_filter_samples(),
1089                    yuv_sample_cost(planes.format),
1090                ),
1091                uploads,
1092                external_leases,
1093            })),
1094        })
1095    }
1096}
1097
1098pub(crate) fn validate_plane(
1099    bytes: &[u8],
1100    stride: u32,
1101    width: u32,
1102    height: u32,
1103) -> Result<(), RenderError> {
1104    let required = usize::try_from(stride).ok().and_then(|stride| {
1105        usize::try_from(height)
1106            .ok()
1107            .and_then(|height| stride.checked_mul(height))
1108    });
1109    if stride < width || required != Some(bytes.len()) {
1110        Err(RenderError::InvalidImageData)
1111    } else {
1112        Ok(())
1113    }
1114}
1115
1116fn texture_bytes(size: RenderSize, format: wgpu::TextureFormat) -> u64 {
1117    let block = format.block_copy_size(None).unwrap_or(4);
1118    u64::from(size.width)
1119        .saturating_mul(u64::from(size.height))
1120        .saturating_mul(u64::from(block))
1121}
1122
1123pub(crate) fn upload_plane(
1124    renderer: &Renderer,
1125    label: &'static str,
1126    plane: SourcePlane<'_>,
1127    (width, height): (u32, u32),
1128    texture_format: wgpu::TextureFormat,
1129) -> Result<crate::UploadTexture, RenderError> {
1130    let size = RenderSize::new(width, height)?;
1131    renderer.validate_size(size)?;
1132    let texture =
1133        renderer
1134            .upload_textures
1135            .acquire(renderer.gpu.device(), size, texture_format, label);
1136    renderer.gpu.queue().write_texture(
1137        wgpu::TexelCopyTextureInfo {
1138            texture: texture.texture(),
1139            mip_level: 0,
1140            origin: wgpu::Origin3d::ZERO,
1141            aspect: wgpu::TextureAspect::All,
1142        },
1143        plane.bytes,
1144        wgpu::TexelCopyBufferLayout {
1145            offset: 0,
1146            bytes_per_row: Some(plane.stride),
1147            rows_per_image: Some(height),
1148        },
1149        wgpu::Extent3d {
1150            width,
1151            height,
1152            depth_or_array_layers: 1,
1153        },
1154    );
1155    Ok(texture)
1156}
1157
1158impl Renderer {
1159    /// Most samples a presentation pass averages per output pixel when shrinking, matching the
1160    /// composite's minification budget (at most 64).
1161    #[allow(clippy::cast_precision_loss)]
1162    fn presentation_filter_samples(&self) -> f32 {
1163        self.quality_controls().max_filter_samples as f32
1164    }
1165
1166    /// Bindings: Y, U or UV, V planes of `sample_type`, the uniform, and the alpha plane.
1167    fn yuv_bind_group_layout(&self, sample_type: wgpu::TextureSampleType) -> wgpu::BindGroupLayout {
1168        let texture = |binding| wgpu::BindGroupLayoutEntry {
1169            binding,
1170            visibility: wgpu::ShaderStages::FRAGMENT,
1171            ty: wgpu::BindingType::Texture {
1172                sample_type,
1173                view_dimension: wgpu::TextureViewDimension::D2,
1174                multisampled: false,
1175            },
1176            count: None,
1177        };
1178        self.gpu
1179            .device()
1180            .create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
1181                label: Some("alpha2 YUV layout"),
1182                entries: &[
1183                    texture(0),
1184                    texture(1),
1185                    texture(2),
1186                    wgpu::BindGroupLayoutEntry {
1187                        binding: 3,
1188                        visibility: wgpu::ShaderStages::FRAGMENT,
1189                        ty: wgpu::BindingType::Buffer {
1190                            ty: wgpu::BufferBindingType::Uniform,
1191                            has_dynamic_offset: true,
1192                            min_binding_size: None,
1193                        },
1194                        count: None,
1195                    },
1196                    texture(4),
1197                ],
1198            })
1199    }
1200
1201    /// With `integer_planes`, the pipeline for 16-bit containers uploaded as unsigned integers.
1202    fn yuv_pipeline(&self, integer_planes: bool) -> Result<&CachedYuvPipeline, RenderError> {
1203        let (cache, source) = if integer_planes {
1204            (&self.pipelines.yuv16, YUV16_TO_LINEAR_WGSL)
1205        } else {
1206            (&self.pipelines.yuv, YUV_TO_LINEAR_WGSL)
1207        };
1208        crate::gpu_errors::checked_cell(cache, self.gpu.device(), || {
1209            let bind_group_layout = self.yuv_bind_group_layout(if integer_planes {
1210                wgpu::TextureSampleType::Uint
1211            } else {
1212                wgpu::TextureSampleType::Float { filterable: true }
1213            });
1214            let shader = self
1215                .gpu
1216                .device()
1217                .create_shader_module(wgpu::ShaderModuleDescriptor {
1218                    label: Some("alpha2 YUV conversion shader"),
1219                    source: wgpu::ShaderSource::Wgsl(source.into()),
1220                });
1221            let pipeline_layout =
1222                self.gpu
1223                    .device()
1224                    .create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
1225                        label: Some("alpha2 YUV pipeline layout"),
1226                        bind_group_layouts: &[
1227                            Some(&bind_group_layout),
1228                            Some(&self.linear_sampler.layout),
1229                        ],
1230                        immediate_size: 0,
1231                    });
1232            let pipeline =
1233                self.gpu
1234                    .device()
1235                    .create_render_pipeline(&wgpu::RenderPipelineDescriptor {
1236                        label: Some("alpha2 YUV pipeline"),
1237                        layout: Some(&pipeline_layout),
1238                        vertex: wgpu::VertexState {
1239                            module: &shader,
1240                            entry_point: Some("vs"),
1241                            buffers: &[],
1242                            compilation_options: wgpu::PipelineCompilationOptions::default(),
1243                        },
1244                        fragment: Some(wgpu::FragmentState {
1245                            module: &shader,
1246                            entry_point: Some("fs_srgb"),
1247                            targets: &[Some(self.intermediate_format().into())],
1248                            compilation_options: wgpu::PipelineCompilationOptions::default(),
1249                        }),
1250                        primitive: wgpu::PrimitiveState::default(),
1251                        depth_stencil: None,
1252                        multisample: wgpu::MultisampleState::default(),
1253                        multiview_mask: None,
1254                        cache: None,
1255                    });
1256            CachedYuvPipeline {
1257                bind_group_layout,
1258                pipeline,
1259            }
1260        })
1261    }
1262}
1263
1264pub(crate) fn validate_presentation(
1265    source: RenderSize,
1266    presentation: SourcePresentation,
1267) -> Result<(), RenderError> {
1268    let visible = presentation.visible_rect;
1269    if visible.width == 0
1270        || visible.height == 0
1271        || presentation.sample_aspect_ratio.0 == 0
1272        || presentation.sample_aspect_ratio.1 == 0
1273        || visible
1274            .x
1275            .checked_add(visible.width)
1276            .is_none_or(|right| right > source.width)
1277        || visible
1278            .y
1279            .checked_add(visible.height)
1280            .is_none_or(|bottom| bottom > source.height)
1281    {
1282        Err(RenderError::InvalidImageData)
1283    } else {
1284        Ok(())
1285    }
1286}
1287
1288pub(crate) enum HdrHandling {
1289    /// An SDR signal, decoded as SDR.
1290    Sdr,
1291    /// An HDR signal tone-mapped into the working space.
1292    ToneMap(HdrToneMap),
1293    /// An HDR signal the policy skips: a transparent picture.
1294    Skip,
1295}
1296
1297/// How `policy` handles `color`; records the diagnostic.
1298pub(crate) fn hdr_handling(
1299    color: ColorMetadata,
1300    policy: ColorPolicy,
1301    diagnostics: &mut Vec<ColorDiagnostic>,
1302) -> Result<HdrHandling, RenderError> {
1303    if !crate::is_hdr(color) {
1304        return Ok(HdrHandling::Sdr);
1305    }
1306    match policy {
1307        ColorPolicy::RejectHdr => {
1308            diagnostics.push(ColorDiagnostic::UnsupportedHdr);
1309            Err(RenderError::UnsupportedHdr)
1310        }
1311        ColorPolicy::WarnHdr => {
1312            diagnostics.push(ColorDiagnostic::UnsupportedHdr);
1313            Ok(HdrHandling::Skip)
1314        }
1315        ColorPolicy::ToneMapHdr(tone) => {
1316            diagnostics.push(ColorDiagnostic::ToneMappedHdr);
1317            Ok(HdrHandling::ToneMap(tone))
1318        }
1319    }
1320}
1321
1322/// Clockwise quarter turns in bits 0-1; bit 2 set when the picture is mirrored first.
1323fn orientation_uniform(orientation: Orientation) -> u32 {
1324    orientation.rotation.quarter_turns() | (u32::from(orientation.mirror) << 2)
1325}
1326
1327fn draw_rect(presentation: SourcePresentation) -> [f64; 4] {
1328    let visible = presentation.visible_rect;
1329    let sar = f64::from(presentation.sample_aspect_ratio.0)
1330        / f64::from(presentation.sample_aspect_ratio.1);
1331    let unrotated_width = f64::from(visible.width) * sar;
1332    let unrotated_height = f64::from(visible.height);
1333    let (display_width, display_height) = if presentation.orientation.rotation.swaps_axes() {
1334        (unrotated_height, unrotated_width)
1335    } else {
1336        (unrotated_width, unrotated_height)
1337    };
1338    let scale = (f64::from(presentation.output_size.width) / display_width)
1339        .min(f64::from(presentation.output_size.height) / display_height);
1340    let draw_width = display_width * scale;
1341    let draw_height = display_height * scale;
1342    let draw_x = (f64::from(presentation.output_size.width) - draw_width) * 0.5;
1343    let draw_y = (f64::from(presentation.output_size.height) - draw_height) * 0.5;
1344    [draw_x, draw_y, draw_width, draw_height]
1345}
1346
1347/// Mirrors `filter_grid` in yuv-to-linear.wesl and rgba-present.wesl.
1348#[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
1349fn filter_samples(presentation: SourcePresentation, max_filter_samples: f32) -> u64 {
1350    let visible = presentation.visible_rect;
1351    let (extent_x, extent_y) = if presentation.orientation.rotation.swaps_axes() {
1352        (visible.height, visible.width)
1353    } else {
1354        (visible.width, visible.height)
1355    };
1356    let [_, _, draw_width, draw_height] = draw_rect(presentation);
1357    let wanted = |extent: u32, drawn: f64| {
1358        let footprint = f64::from(extent) / drawn;
1359        if footprint > 2.0 {
1360            (footprint - 0.0001).ceil().clamp(1.0, 8.0)
1361        } else {
1362            1.0
1363        }
1364    };
1365    let budget = f64::from(max_filter_samples).clamp(1.0, 64.0);
1366    let columns = wanted(extent_x, draw_width).min(budget);
1367    let rows = wanted(extent_y, draw_height).min((budget / columns).floor().max(1.0));
1368    (columns * rows) as u64
1369}
1370
1371const RGBA_SAMPLE_COST: crate::effect_cost::EffectCost =
1372    crate::effect_cost::EffectCost::fixed(1, 3);
1373
1374fn yuv_sample_cost(format: YuvFormat) -> crate::effect_cost::EffectCost {
1375    crate::effect_cost::EffectCost::fixed(
1376        u64::try_from(format.plane_count()).unwrap_or(u64::MAX),
1377        3,
1378    )
1379}
1380
1381pub(crate) fn conversion_work(
1382    presentation: SourcePresentation,
1383    max_filter_samples: f32,
1384    sample: crate::effect_cost::EffectCost,
1385) -> crate::FrameCost {
1386    crate::FrameCost::of(
1387        sample.times(filter_samples(presentation, max_filter_samples)),
1388        presentation.output_size.pixels(),
1389    )
1390}
1391
1392#[allow(clippy::cast_possible_truncation, clippy::cast_precision_loss)]
1393pub(crate) fn presentation_uniform_bytes(
1394    source: RenderSize,
1395    presentation: SourcePresentation,
1396    encoding: PresentedEncoding,
1397    max_filter_samples: f32,
1398) -> Vec<u8> {
1399    let visible = presentation.visible_rect;
1400    let [draw_x, draw_y, draw_width, draw_height] = draw_rect(presentation);
1401    let values = [
1402        presentation.output_size.width as f32,
1403        presentation.output_size.height as f32,
1404        source.width as f32,
1405        source.height as f32,
1406        visible.x as f32,
1407        visible.y as f32,
1408        visible.width as f32,
1409        visible.height as f32,
1410        draw_x as f32,
1411        draw_y as f32,
1412        draw_width as f32,
1413        draw_height as f32,
1414    ];
1415    let mut bytes = Vec::with_capacity(64);
1416    for value in values {
1417        bytes.extend_from_slice(&value.to_ne_bytes());
1418    }
1419    bytes.extend_from_slice(&orientation_uniform(presentation.orientation).to_ne_bytes());
1420    let mode = match encoding {
1421        PresentedEncoding::Srgb(SourceAlpha::Straight) => 0_u32,
1422        PresentedEncoding::Srgb(SourceAlpha::Premultiplied) => 1,
1423        PresentedEncoding::Linear => 2,
1424    };
1425    bytes.extend_from_slice(&mode.to_ne_bytes());
1426    bytes.extend_from_slice(&max_filter_samples.to_ne_bytes());
1427    bytes.extend_from_slice(&[0; 4]);
1428    bytes
1429}
1430
1431#[allow(
1432    clippy::cast_possible_truncation,
1433    clippy::cast_precision_loss,
1434    clippy::too_many_arguments
1435)]
1436pub(crate) fn uniform_bytes(
1437    color: ColorMetadata,
1438    tone: Option<HdrToneMap>,
1439    alpha: f32,
1440    source: RenderSize,
1441    presentation: SourcePresentation,
1442    format: YuvFormat,
1443    code_scale: f32,
1444    max_filter_samples: f32,
1445) -> Vec<u8> {
1446    let mut bytes = color_uniform_bytes(color, tone, alpha, format.bit_depth, code_scale);
1447    // Whether an alpha plane is read, and the scale to full range.
1448    let (alpha_plane, alpha_scale) = if format.alpha {
1449        (1_u32, code_scale)
1450    } else {
1451        (0, 0.0)
1452    };
1453    bytes[88..92].copy_from_slice(&alpha_plane.to_ne_bytes());
1454    bytes[92..96].copy_from_slice(&alpha_scale.to_ne_bytes());
1455    let visible = presentation.visible_rect;
1456    let [draw_x, draw_y, draw_width, draw_height] = draw_rect(presentation);
1457    let (chroma_width, chroma_height) = format.chroma_size(source.width, source.height);
1458    let chroma_size = [chroma_width as f32, chroma_height as f32];
1459    let factor_x = (1_u32 << format.chroma_shift_x) as f32;
1460    let factor_y = (1_u32 << format.chroma_shift_y) as f32;
1461    // A co-sited chroma sample sits `factor / 2 - 0.5` luma samples before its group's centre.
1462    let (cosited_x, cosited_y) = match presentation.chroma_siting.resolved_for(format) {
1463        ChromaLocation::Left => (true, false),
1464        ChromaLocation::TopLeft => (true, true),
1465        ChromaLocation::Unspecified | ChromaLocation::Center => (false, false),
1466    };
1467    let chroma_offset = [
1468        if cosited_x { factor_x * 0.5 - 0.5 } else { 0.0 },
1469        if cosited_y { factor_y * 0.5 - 0.5 } else { 0.0 },
1470    ];
1471    let presentation_values = [
1472        presentation.output_size.width as f32,
1473        presentation.output_size.height as f32,
1474        source.width as f32,
1475        source.height as f32,
1476        visible.x as f32,
1477        visible.y as f32,
1478        visible.width as f32,
1479        visible.height as f32,
1480        draw_x as f32,
1481        draw_y as f32,
1482        draw_width as f32,
1483        draw_height as f32,
1484        chroma_size[0],
1485        chroma_size[1],
1486        chroma_offset[0],
1487        chroma_offset[1],
1488    ];
1489    for value in presentation_values {
1490        bytes.extend_from_slice(&value.to_ne_bytes());
1491    }
1492    bytes.extend_from_slice(&orientation_uniform(presentation.orientation).to_ne_bytes());
1493    let plane_layout = u32::from(format.interleaved_chroma);
1494    bytes.extend_from_slice(&plane_layout.to_ne_bytes());
1495    for scale in [1.0 / factor_x, 1.0 / factor_y] {
1496        bytes.extend_from_slice(&scale.to_ne_bytes());
1497    }
1498    bytes.extend(hdr_uniform_bytes(color, tone));
1499    for bound in chroma_window(visible, format) {
1500        bytes.extend_from_slice(&bound.to_ne_bytes());
1501    }
1502    for value in [max_filter_samples, 0.0, 0.0, 0.0] {
1503        bytes.extend_from_slice(&value.to_ne_bytes());
1504    }
1505    bytes
1506}
1507
1508/// First and last chroma sample centres (`[x0, y0, x1, y1]`) whose luma group reaches into
1509/// `visible`.
1510///
1511/// Chroma sampling is clamped to these so decoder-surface padding never bleeds into the last
1512/// row or column.
1513#[allow(clippy::cast_precision_loss)]
1514fn chroma_window(visible: Rect, format: YuvFormat) -> [f32; 4] {
1515    let first = |origin: u32, shift: u8| (origin >> shift) as f32 + 0.5;
1516    let last =
1517        |origin: u32, length: u32, shift: u8| (origin + length).div_ceil(1 << shift) as f32 - 0.5;
1518    [
1519        first(visible.x, format.chroma_shift_x),
1520        first(visible.y, format.chroma_shift_y),
1521        last(visible.x, visible.width, format.chroma_shift_x),
1522        last(visible.y, visible.height, format.chroma_shift_y),
1523    ]
1524}
1525
1526/// HDR uniform part: primaries matrix to BT.709, tone-map peaks and their PQ codes, HLG system
1527/// gamma.
1528fn hdr_uniform_bytes(color: ColorMetadata, tone: Option<HdrToneMap>) -> Vec<u8> {
1529    let gamut = crate::hdr::gamut_matrix(color.primaries, ColorPrimaries::Bt709);
1530    let tone = tone.unwrap_or_default();
1531    #[allow(clippy::cast_precision_loss)]
1532    let peak = tone.source_peak_nits as f32;
1533    let white = crate::hdr::SDR_WHITE_NITS;
1534    let gamma = 1.2 + 0.42 * libm::log10f(peak / 1_000.0);
1535    let mut bytes = Vec::with_capacity(80);
1536    for value in gamut
1537        .into_iter()
1538        .flat_map(|row| [row[0], row[1], row[2], 0.0])
1539        .chain([
1540            peak,
1541            white,
1542            crate::hdr::pq_inverse_eotf(peak),
1543            crate::hdr::pq_inverse_eotf(white),
1544            gamma,
1545            0.0,
1546            0.0,
1547            0.0,
1548        ])
1549    {
1550        bytes.extend_from_slice(&value.to_ne_bytes());
1551    }
1552    bytes
1553}
1554
1555fn color_uniform_bytes(
1556    color: ColorMetadata,
1557    tone: Option<HdrToneMap>,
1558    alpha: f32,
1559    bit_depth: u8,
1560    code_scale: f32,
1561) -> Vec<u8> {
1562    // 0 = SDR with the sRGB EOTF; 1 = PQ and 2 = HLG via the tone map.
1563    let transfer: u32 = match (tone, color.transfer) {
1564        (Some(_), TransferFunction::Pq) => 1,
1565        (Some(_), TransferFunction::Hlg) => 2,
1566        _ => 0,
1567    };
1568    if color.matrix == ColorMatrix::Rgb {
1569        return identity_rgb_uniform_bytes(alpha, transfer, code_scale);
1570    }
1571    let (kr, kb) = color
1572        .matrix
1573        .luma_weights()
1574        .expect("RGB components are handled above");
1575    let kg = 1.0 - kr - kb;
1576    let rows = [
1577        [1.0, 0.0, 2.0 * (1.0 - kr), 0.0],
1578        [
1579            1.0,
1580            -2.0 * kb * (1.0 - kb) / kg,
1581            -2.0 * kr * (1.0 - kr) / kg,
1582            0.0,
1583        ],
1584        [1.0, 2.0 * (1.0 - kb), 0.0, 0.0],
1585    ];
1586    let (scale, offset) = range_scale_offset(color.range, bit_depth, code_scale);
1587    let mut bytes = Vec::with_capacity(96);
1588    for value in rows.into_iter().flatten().chain(scale).chain(offset) {
1589        bytes.extend_from_slice(&value.to_ne_bytes());
1590    }
1591    bytes.extend_from_slice(&transfer.to_ne_bytes());
1592    bytes.extend_from_slice(&alpha.to_ne_bytes());
1593    bytes.extend_from_slice(&[0; 8]);
1594    bytes
1595}
1596
1597/// Component scale and offset mapping sampled codes to normalized YCbCr.
1598///
1599/// Levels come from [`ColorRange::levels`](alpha2_media::ColorRange::levels), shared with export.
1600/// `code` is [`PlaneStorage::code_scale`].
1601fn range_scale_offset(range: ColorRange, depth: u8, code: f32) -> ([f32; 4], [f32; 4]) {
1602    let levels = range.levels(depth);
1603    let (luma_scale, chroma_scale) = match range {
1604        ColorRange::Full => (code, code),
1605        ColorRange::Limited => (
1606            code * levels.maximum / levels.luma_span,
1607            code * levels.maximum / levels.chroma_span,
1608        ),
1609    };
1610    let chroma_offset = 0.0 - levels.chroma_center / levels.chroma_span;
1611    (
1612        [luma_scale, chroma_scale, chroma_scale, 0.0],
1613        [
1614            0.0 - levels.luma_black / levels.luma_span,
1615            chroma_offset,
1616            chroma_offset,
1617            0.0,
1618        ],
1619    )
1620}
1621
1622/// The identity matrix over RGB codes; `code` is [`PlaneStorage::code_scale`]. The range flag is
1623/// ignored: untagged RGB reads as limited, and RGB codes are always full range.
1624fn identity_rgb_uniform_bytes(alpha: f32, transfer: u32, code: f32) -> Vec<u8> {
1625    let rows = [
1626        [1.0_f32, 0.0, 0.0, 0.0],
1627        [0.0_f32, 1.0, 0.0, 0.0],
1628        [0.0_f32, 0.0, 1.0, 0.0],
1629    ];
1630    let mut bytes = Vec::with_capacity(96);
1631    for value in rows
1632        .into_iter()
1633        .flatten()
1634        .chain([code, code, code, 0.0])
1635        .chain([0.0; 4])
1636    {
1637        bytes.extend_from_slice(&value.to_ne_bytes());
1638    }
1639    bytes.extend_from_slice(&transfer.to_ne_bytes());
1640    bytes.extend_from_slice(&alpha.to_ne_bytes());
1641    bytes.extend_from_slice(&[0; 8]);
1642    bytes
1643}
1644
1645#[cfg(test)]
1646mod tests {
1647    use super::*;
1648    use alpha2_media::{ColorPrimaries, DynamicRange};
1649
1650    #[test]
1651    fn parked_leases_are_dropped_only_when_drained() {
1652        // Runs under the decoder queue lock; dropping an `FFmpeg` frame here would deadlock.
1653        #[derive(Debug)]
1654        struct CountingLease(Arc<std::sync::atomic::AtomicUsize>);
1655
1656        impl Drop for CountingLease {
1657            fn drop(&mut self) {
1658                self.0.fetch_add(1, Ordering::Release);
1659            }
1660        }
1661
1662        impl ExternalTextureLease for CountingLease {
1663            fn retained_bytes(&self) -> u64 {
1664                0
1665            }
1666        }
1667
1668        let drops = Arc::new(std::sync::atomic::AtomicUsize::new(0));
1669        let retired = RetiredLeases::default();
1670        let lease: Arc<dyn ExternalTextureLease> = Arc::new(CountingLease(Arc::clone(&drops)));
1671        retired.park(vec![lease]);
1672        assert_eq!(drops.load(Ordering::Acquire), 0, "parking must not release");
1673        retired.drain();
1674        assert_eq!(drops.load(Ordering::Acquire), 1, "drain must release");
1675        retired.drain();
1676        assert_eq!(drops.load(Ordering::Acquire), 1, "drain must be idempotent");
1677    }
1678
1679    #[test]
1680    fn ten_bit_limited_range_normalizes_the_p010_container() {
1681        let (scale, offset) = range_scale_offset(
1682            ColorRange::Limited,
1683            10,
1684            PlaneStorage::Unorm16.code_scale(YuvFormat::P010),
1685        );
1686        // A limited-range 10-bit black sample is code 64, stored as 64 << 6.
1687        let black = f32::from(64_u16 << 6) / 65535.0;
1688        assert!((black * scale[0] + offset[0]).abs() < 1e-4);
1689        // Nominal white is code 940.
1690        let white = f32::from(940_u16 << 6) / 65535.0;
1691        assert!((white * scale[0] + offset[0] - 1.0).abs() < 1e-4);
1692        // Neutral chroma is code 512.
1693        let neutral = f32::from(512_u16 << 6) / 65535.0;
1694        assert!((neutral * scale[1] + offset[1]).abs() < 1e-4);
1695    }
1696
1697    #[test]
1698    fn integer_containers_take_the_scale_normalized_ones_do() {
1699        // The integer build reads `container / 65535`, as an R16Unorm texture samples it.
1700        for format in [YuvFormat::planar(1, 1, 10), YuvFormat::P010] {
1701            assert_eq!(
1702                PlaneStorage::Uint16.code_scale(format).to_bits(),
1703                PlaneStorage::Unorm16.code_scale(format).to_bits()
1704            );
1705        }
1706        assert_eq!(
1707            PlaneStorage::Uint16.texture_format(false),
1708            wgpu::TextureFormat::R16Uint
1709        );
1710        assert_eq!(
1711            PlaneStorage::Uint16.texture_format(true),
1712            wgpu::TextureFormat::Rg16Uint
1713        );
1714    }
1715
1716    #[test]
1717    fn eight_bit_range_constants_are_unchanged() {
1718        let bits = |values: [f32; 4]| values.map(f32::to_bits);
1719        let (scale, offset) = range_scale_offset(ColorRange::Limited, 8, 1.0);
1720        assert_eq!(
1721            bits(scale),
1722            bits([255.0 / 219.0, 255.0 / 224.0, 255.0 / 224.0, 0.0])
1723        );
1724        assert_eq!(
1725            bits(offset),
1726            bits([-16.0 / 219.0, -128.0 / 224.0, -128.0 / 224.0, 0.0])
1727        );
1728        let (scale, offset) = range_scale_offset(ColorRange::Full, 8, 1.0);
1729        assert_eq!(bits(scale), bits([1.0, 1.0, 1.0, 0.0]));
1730        assert_eq!(
1731            bits(offset),
1732            bits([0.0, -128.0 / 255.0, -128.0 / 255.0, 0.0])
1733        );
1734    }
1735
1736    #[test]
1737    fn rgb_uniform_uses_identity_matrix_without_chroma_offsets() {
1738        let bytes = uniform_bytes(
1739            ColorMetadata {
1740                primaries: ColorPrimaries::Bt709,
1741                transfer: TransferFunction::Srgb,
1742                matrix: ColorMatrix::Rgb,
1743                range: ColorRange::Limited,
1744                dynamic_range: DynamicRange::Sdr,
1745            },
1746            None,
1747            1.0,
1748            RenderSize::new(2, 2).expect("size"),
1749            SourcePresentation::identity(RenderSize::new(2, 2).expect("size")),
1750            YuvFormat::I420,
1751            1.0,
1752            64.0,
1753        );
1754        let floats = bytes[..80]
1755            .as_chunks::<4>()
1756            .0
1757            .iter()
1758            .map(|bytes| f32::from_ne_bytes(*bytes))
1759            .collect::<Vec<_>>();
1760        assert_eq!(
1761            floats.into_iter().map(f32::to_bits).collect::<Vec<_>>(),
1762            vec![
1763                1.0, 0.0, 0.0, 0.0, // matrix row 0
1764                0.0, 1.0, 0.0, 0.0, // matrix row 1
1765                0.0, 0.0, 1.0, 0.0, // matrix row 2
1766                1.0, 1.0, 1.0, 0.0, // component scale
1767                0.0, 0.0, 0.0, 0.0, // component offset
1768            ]
1769            .into_iter()
1770            .map(f32::to_bits)
1771            .collect::<Vec<_>>()
1772        );
1773    }
1774
1775    #[test]
1776    fn an_unspecified_siting_of_horizontally_subsampled_chroma_is_left() {
1777        let size = RenderSize::new(16, 4).expect("size");
1778        let bytes = |format, siting| {
1779            uniform_bytes(
1780                ColorMetadata::EXPORT,
1781                None,
1782                1.0,
1783                size,
1784                SourcePresentation {
1785                    chroma_siting: siting,
1786                    ..SourcePresentation::identity(size)
1787                },
1788                format,
1789                1.0,
1790                64.0,
1791            )
1792        };
1793        for format in [YuvFormat::planar(1, 0, 10), YuvFormat::planar(2, 0, 8)] {
1794            assert_eq!(
1795                bytes(format, ChromaLocation::Unspecified),
1796                bytes(format, ChromaLocation::Left),
1797                "{format:?}"
1798            );
1799        }
1800        assert_eq!(
1801            bytes(YuvFormat::I420, ChromaLocation::Unspecified),
1802            bytes(YuvFormat::I420, ChromaLocation::Center)
1803        );
1804        assert_ne!(
1805            bytes(YuvFormat::I420, ChromaLocation::Unspecified),
1806            bytes(YuvFormat::I420, ChromaLocation::Left)
1807        );
1808    }
1809
1810    #[test]
1811    fn rgb_uniform_scales_ten_bit_codes_to_full_range() {
1812        let code_scale = 65535.0 / 1023.0;
1813        let bytes = uniform_bytes(
1814            ColorMetadata {
1815                primaries: ColorPrimaries::Bt2020,
1816                transfer: TransferFunction::Bt709,
1817                matrix: ColorMatrix::Rgb,
1818                range: ColorRange::Full,
1819                dynamic_range: DynamicRange::Sdr,
1820            },
1821            None,
1822            1.0,
1823            RenderSize::new(2, 2).expect("size"),
1824            SourcePresentation::identity(RenderSize::new(2, 2).expect("size")),
1825            YuvFormat::planar(0, 0, 10),
1826            code_scale,
1827            64.0,
1828        );
1829        let scale = bytes[48..64]
1830            .as_chunks::<4>()
1831            .0
1832            .iter()
1833            .map(|bytes| f32::from_ne_bytes(*bytes).to_bits())
1834            .collect::<Vec<_>>();
1835        assert_eq!(
1836            scale,
1837            [code_scale, code_scale, code_scale, 0.0].map(f32::to_bits)
1838        );
1839    }
1840
1841    #[test]
1842    fn the_chroma_window_is_the_visible_pictures_chroma() {
1843        let window = |x, y, width, height, format| {
1844            chroma_window(
1845                Rect {
1846                    x,
1847                    y,
1848                    width,
1849                    height,
1850                },
1851                format,
1852            )
1853            .map(f32::to_bits)
1854        };
1855        let bits = |bounds: [f32; 4]| bounds.map(f32::to_bits);
1856        // 1080p decoded into 1920 x 1088: chroma rows 540..544 are padding.
1857        assert_eq!(
1858            window(0, 0, 1920, 1080, YuvFormat::I420),
1859            bits([0.5, 0.5, 959.5, 539.5])
1860        );
1861        // 1366 wide in a 1376 surface: the last column's chroma is sample 682.
1862        assert_eq!(
1863            window(0, 0, 1366, 768, YuvFormat::I420),
1864            bits([0.5, 0.5, 682.5, 383.5])
1865        );
1866        // An odd crop keeps the chroma sample its first luma column shares.
1867        assert_eq!(
1868            window(1, 3, 5, 4, YuvFormat::I420),
1869            bits([0.5, 1.5, 2.5, 3.5])
1870        );
1871        assert_eq!(
1872            window(2, 1, 3, 2, YuvFormat::planar(0, 0, 8)),
1873            bits([2.5, 1.5, 4.5, 2.5])
1874        );
1875    }
1876}