Skip to main content

alpha2_render/
readback.rs

1use std::sync::atomic::{AtomicBool, Ordering};
2#[cfg(not(target_arch = "wasm32"))]
3use std::sync::mpsc;
4
5use crate::bind_group::OffsetBindGroup;
6use crate::canary::{CANARY_BYTES, Canary};
7use crate::composite::PixelRect;
8use crate::renderer::PassEncoder;
9use crate::submission_planner::Piece;
10use crate::{
11    ReadbackFailure, RenderError, RenderSize, RenderedTexture, Renderer,
12    pipeline::{
13        CachedLayoutPackPipeline, CachedPipeline, CachedYuvReadbackPipeline, LayoutPackPass,
14    },
15    pool::{ReadbackBufferLease, TextureLease},
16    uniform::UniformArenaLease,
17};
18use alpha2_gpu::GpuContext;
19use alpha2_media::{ChromaLocation, ColorMatrix, PixelLayout, YuvEncoding};
20use alpha2_shaders::{LAYOUT_PACK_WGSL, READBACK_PACK_WGSL, RGB_TO_YUV420_WGSL};
21
22const RGBA8_BYTES_PER_PIXEL: u32 = 4;
23const RGBA16F_BYTES_PER_PIXEL: u32 = 8;
24const YUV420_PLANE_COUNT: u64 = 3;
25const LAYOUT_PACK_PASSES: u64 = 2;
26
27/// D3D12 texture-to-buffer copies must start on this; wgpu's DX12 workaround for an unaligned
28/// start pads rows and overwrites whatever follows.
29const PLANE_PLACEMENT_ALIGNMENT: u64 = 512;
30
31/// Where each plane of one GPU-packed readback sits in its staging buffer, in storage order.
32///
33/// Each plane starts on [`PLANE_PLACEMENT_ALIGNMENT`] so DX12's padded-copy workaround cannot
34/// overwrite the next plane.
35#[derive(Clone, Debug, Eq, PartialEq)]
36pub(crate) struct StagingLayout {
37    planes: Vec<StagedPlane>,
38    bytes: u64,
39}
40
41#[derive(Copy, Clone, Debug, Eq, PartialEq)]
42struct StagedPlane {
43    offset: u64,
44    pitch: u32,
45    row_bytes: u32,
46    rows: u32,
47}
48
49impl StagingLayout {
50    /// Planes of `(row_bytes, rows)`, in order.
51    fn new(planes: impl IntoIterator<Item = (u32, u32)>) -> Result<Self, RenderError> {
52        let overflow = || RenderError::TextureReadback(ReadbackFailure::Layout);
53        let mut staged = Vec::new();
54        let mut end = 0_u64;
55        for (row_bytes, rows) in planes {
56            let pitch = aligned_copy_row(row_bytes)?;
57            let offset = end
58                .checked_next_multiple_of(PLANE_PLACEMENT_ALIGNMENT)
59                .ok_or_else(overflow)?;
60            end = u64::from(pitch)
61                .checked_mul(u64::from(rows))
62                .and_then(|region| region.checked_add(offset))
63                .ok_or_else(overflow)?;
64            staged.push(StagedPlane {
65                offset,
66                pitch,
67                row_bytes,
68                rows,
69            });
70        }
71        Ok(Self {
72            planes: staged,
73            bytes: end,
74        })
75    }
76
77    pub(crate) fn yuv420(size: RenderSize) -> Result<Self, RenderError> {
78        let (chroma_width, chroma_rows) = (size.width / 2, size.height / 2);
79        Self::new([
80            (size.width, size.height),
81            (chroma_width, chroma_rows),
82            (chroma_width, chroma_rows),
83        ])
84    }
85
86    pub(crate) fn of_layout(layout: PixelLayout, size: RenderSize) -> Result<Self, RenderError> {
87        let planes = layout
88            .planes(size.width, size.height)
89            .into_iter()
90            .map(|(width, rows, bytes)| {
91                width
92                    .checked_mul(bytes)
93                    .map(|row_bytes| (row_bytes, rows))
94                    .ok_or(RenderError::TextureReadback(ReadbackFailure::Layout))
95            })
96            .collect::<Result<Vec<_>, _>>()?;
97        Self::new(planes)
98    }
99
100    fn packed_bytes(&self) -> u64 {
101        self.planes.iter().fold(0_u64, |bytes, plane| {
102            bytes.saturating_add(u64::from(plane.row_bytes) * u64::from(plane.rows))
103        })
104    }
105}
106
107/// Staging bytes of one planar YUV420 readback of `size`, including row padding, plane
108/// alignment and the 16-byte canary. A budget must reserve this per in-flight readback.
109///
110/// # Errors
111/// Returns [`RenderError::TextureReadback`] when the layout overflows.
112pub fn yuv420p_staging_bytes(size: RenderSize) -> Result<u64, RenderError> {
113    StagingLayout::yuv420(size).map(|layout| layout.bytes + CANARY_BYTES)
114}
115
116/// The mapped buffer a readback of a `size` frame packed into `layout` takes
117/// ([`Renderer::begin_layout_readback`]), canary included: each plane's rows padded to the copy
118/// alignment.
119///
120/// # Errors
121/// [`RenderError::TextureReadback`] when the layout overflows.
122pub fn layout_staging_bytes(size: RenderSize, layout: PixelLayout) -> Result<u64, RenderError> {
123    StagingLayout::of_layout(layout, size).map(|staging| staging.bytes + CANARY_BYTES)
124}
125
126fn check_layout_target(target: &RenderedTexture, layout: PixelLayout) -> Result<(), RenderError> {
127    let (step_x, step_y) = layout.chroma.subsampling();
128    let readable = match target.format {
129        wgpu::TextureFormat::Rgba16Float => true,
130        wgpu::TextureFormat::Rgba8Unorm => layout.bit_depth == alpha2_media::BitDepth::Eight,
131        _ => false,
132    };
133    if readable
134        && target.size.width.is_multiple_of(step_x)
135        && target.size.height.is_multiple_of(step_y)
136    {
137        Ok(())
138    } else {
139        Err(RenderError::TextureReadback(
140            ReadbackFailure::UnsupportedTarget,
141        ))
142    }
143}
144
145fn plane_rows(
146    mapped: &[u8],
147    plane: StagedPlane,
148) -> Result<std::iter::Take<std::slice::ChunksExact<'_, u8>>, RenderError> {
149    let offset = usize::try_from(plane.offset)
150        .map_err(|_| RenderError::TextureReadback(ReadbackFailure::Layout))?;
151    let pitch = usize::try_from(plane.pitch)
152        .map_err(|_| RenderError::TextureReadback(ReadbackFailure::Layout))?;
153    let width = usize::try_from(plane.row_bytes)
154        .map_err(|_| RenderError::TextureReadback(ReadbackFailure::Layout))?;
155    let rows = usize::try_from(plane.rows)
156        .map_err(|_| RenderError::TextureReadback(ReadbackFailure::Layout))?;
157    let region = pitch
158        .checked_mul(rows)
159        .and_then(|length| length.checked_add(offset))
160        .and_then(|end| mapped.get(offset..end))
161        .filter(|_| width <= pitch)
162        .ok_or(RenderError::TextureReadback(ReadbackFailure::Layout))?;
163    Ok(region.chunks_exact(pitch).take(rows))
164}
165
166pub(crate) struct EncodedLayoutReadback {
167    buffer: ReadbackBufferLease,
168    size: RenderSize,
169    staging: StagingLayout,
170    pixel_layout: PixelLayout,
171    staging_bytes: u64,
172    canary: Canary,
173    planes: Vec<TextureLease>,
174}
175
176pub(crate) struct EncodedYuv420pReadback {
177    buffer: ReadbackBufferLease,
178    size: RenderSize,
179    layout: StagingLayout,
180    staging_bytes: u64,
181    canary: Canary,
182    y_texture: TextureLease,
183    u_texture: TextureLease,
184    v_texture: TextureLease,
185}
186
187impl Renderer {
188    /// Uploads tightly packed premultiplied sRGB RGBA8 pixels into a pooled upload texture.
189    ///
190    /// # Errors
191    /// [`RenderError::InvalidImageData`] when `pixels` is not four bytes per pixel.
192    pub fn upload_rgba8(
193        &self,
194        size: RenderSize,
195        pixels: &[u8],
196    ) -> Result<crate::UploadTexture, RenderError> {
197        self.write_rgba8(
198            size,
199            crate::SourcePlane {
200                bytes: pixels,
201                stride: size
202                    .width
203                    .checked_mul(RGBA8_BYTES_PER_PIXEL)
204                    .ok_or(RenderError::InvalidImageData)?,
205            },
206        )
207    }
208
209    /// Uploads tightly packed premultiplied linear RGBA half floats (BT.709, `1.0` = SDR white) for
210    /// [`Renderer::prepare_linear_presented`].
211    ///
212    /// # Errors
213    /// [`RenderError::InvalidImageData`] when `pixels` is not four halves per pixel.
214    pub fn upload_linear_rgba16f(
215        &self,
216        size: RenderSize,
217        pixels: &[u16],
218    ) -> Result<crate::UploadTexture, RenderError> {
219        // Avoids a frame-sized copy per frame on little-endian targets.
220        let bytes: std::borrow::Cow<'_, [u8]> = if cfg!(target_endian = "little") {
221            std::borrow::Cow::Borrowed(bytemuck::cast_slice(pixels))
222        } else {
223            std::borrow::Cow::Owned(pixels.iter().flat_map(|half| half.to_le_bytes()).collect())
224        };
225        self.write_linear_rgba16f(
226            size,
227            crate::SourcePlane {
228                bytes: &bytes,
229                stride: size
230                    .width
231                    .checked_mul(RGBA16F_BYTES_PER_PIXEL)
232                    .ok_or(RenderError::InvalidImageData)?,
233            },
234        )
235    }
236
237    /// Writes strided little-endian RGBA half-float rows into a pooled upload texture.
238    ///
239    /// # Errors
240    /// [`RenderError::InvalidImageData`] for a plane shorter than `size`.
241    pub fn write_linear_rgba16f(
242        &self,
243        size: RenderSize,
244        plane: crate::SourcePlane<'_>,
245    ) -> Result<crate::UploadTexture, RenderError> {
246        self.validate_size(size)?;
247        let texture = self.upload_textures.acquire(
248            self.gpu.device(),
249            size,
250            wgpu::TextureFormat::Rgba16Float,
251            "alpha2 linear RGBA upload texture",
252        );
253        self.write_plane(&texture, size, plane, RGBA16F_BYTES_PER_PIXEL)?;
254        Ok(texture)
255    }
256
257    pub(crate) fn write_rgba8(
258        &self,
259        size: RenderSize,
260        plane: crate::SourcePlane<'_>,
261    ) -> Result<crate::UploadTexture, RenderError> {
262        let texture = self.acquire_rgba8_upload_texture(size)?;
263        self.write_plane(&texture, size, plane, RGBA8_BYTES_PER_PIXEL)?;
264        Ok(texture)
265    }
266
267    fn write_plane(
268        &self,
269        texture: &crate::UploadTexture,
270        size: RenderSize,
271        plane: crate::SourcePlane<'_>,
272        bytes_per_pixel: u32,
273    ) -> Result<(), RenderError> {
274        let row_bytes = size
275            .width
276            .checked_mul(bytes_per_pixel)
277            .ok_or(RenderError::InvalidImageData)?;
278        let required = usize::try_from(plane.stride)
279            .ok()
280            .zip(usize::try_from(size.height).ok())
281            .and_then(|(stride, rows)| stride.checked_mul(rows));
282        if plane.stride < row_bytes || required != Some(plane.bytes.len()) {
283            return Err(RenderError::InvalidImageData);
284        }
285        self.gpu.queue().write_texture(
286            wgpu::TexelCopyTextureInfo {
287                texture: texture.texture(),
288                mip_level: 0,
289                origin: wgpu::Origin3d::ZERO,
290                aspect: wgpu::TextureAspect::All,
291            },
292            plane.bytes,
293            wgpu::TexelCopyBufferLayout {
294                offset: 0,
295                bytes_per_row: Some(plane.stride),
296                rows_per_image: Some(size.height),
297            },
298            wgpu::Extent3d {
299                width: size.width,
300                height: size.height,
301                depth_or_array_layers: 1,
302            },
303        );
304        Ok(())
305    }
306
307    /// Copies one RGBA8 render result into tightly packed premultiplied host memory.
308    ///
309    /// Blocks on the GPU, so native and test only; callers that cannot block use
310    /// [`Renderer::begin_rgba8_readback`]. Half-float intermediates are quantized to RGBA8 on the
311    /// GPU first.
312    ///
313    /// # Errors
314    /// [`RenderError::TextureReadback`] for another target format or a failed mapping.
315    #[cfg(not(target_arch = "wasm32"))]
316    pub fn read_rgba8(&self, target: &RenderedTexture) -> Result<Vec<u8>, RenderError> {
317        self.begin_rgba8_readback(target)?.wait()
318    }
319
320    /// Submits a readback copy and returns an unmapped handle.
321    ///
322    /// The copy is queued on return, so mapping can resolve on an event loop via
323    /// [`Rgba8Readback::map_async`]. Used for stills, thumbnails and goldens; exports use YUV or
324    /// NV12 readbacks instead.
325    ///
326    /// # Errors
327    /// [`RenderError::TextureReadback`] for an unsupported format or unrepresentable row layout.
328    pub fn begin_rgba8_readback(
329        &self,
330        target: &RenderedTexture,
331    ) -> Result<Rgba8Readback, RenderError> {
332        self.ensure_gpu_runs_work()?;
333        self.validate_size(target.size)?;
334        if !matches!(
335            target.format,
336            wgpu::TextureFormat::Rgba8Unorm | wgpu::TextureFormat::Rgba16Float
337        ) {
338            return Err(RenderError::TextureReadback(
339                ReadbackFailure::UnsupportedTarget,
340            ));
341        }
342
343        let unpadded_bytes_per_row = target
344            .size
345            .width
346            .checked_mul(RGBA8_BYTES_PER_PIXEL)
347            .ok_or(RenderError::TextureReadback(ReadbackFailure::Layout))?;
348        let alignment = wgpu::COPY_BYTES_PER_ROW_ALIGNMENT;
349        let padded_bytes_per_row = unpadded_bytes_per_row
350            .checked_add(alignment - 1)
351            .map(|value| value / alignment)
352            .and_then(|rows| rows.checked_mul(alignment))
353            .ok_or(RenderError::TextureReadback(ReadbackFailure::Layout))?;
354        let image_bytes = u64::from(padded_bytes_per_row)
355            .checked_mul(u64::from(target.size.height))
356            .ok_or(RenderError::TextureReadback(ReadbackFailure::Layout))?;
357        // Rows, then the canary.
358        let buffer_size = image_bytes
359            .checked_add(CANARY_BYTES)
360            .ok_or(RenderError::TextureReadback(ReadbackFailure::Layout))?;
361        let mut encoder = self.command_encoder("alpha2 RGBA8 readback encoder");
362        let buffer =
363            self.readback_buffers
364                .acquire(self.gpu.device(), buffer_size, "alpha2 RGBA8 readback");
365        let packed_texture = self.encode_readback_pack(target, &mut encoder)?;
366        let copy_source = packed_texture
367            .as_ref()
368            .map_or(&target.texture, TextureLease::texture);
369        encoder.copy_texture_to_buffer(
370            wgpu::TexelCopyTextureInfo {
371                texture: copy_source,
372                mip_level: 0,
373                origin: wgpu::Origin3d::ZERO,
374                aspect: wgpu::TextureAspect::All,
375            },
376            wgpu::TexelCopyBufferInfo {
377                buffer: buffer.buffer(),
378                layout: wgpu::TexelCopyBufferLayout {
379                    offset: 0,
380                    bytes_per_row: Some(padded_bytes_per_row),
381                    rows_per_image: Some(target.size.height),
382                },
383            },
384            wgpu::Extent3d {
385                width: target.size.width,
386                height: target.size.height,
387                depth_or_array_layers: 1,
388            },
389        );
390        // Same encoder, after the copy, so it lands only if the copy ran.
391        let canary = self
392            .canaries
393            .encode(&self.gpu, &mut encoder, buffer.buffer(), image_bytes)?;
394        let command_buffer = encoder.finish();
395        #[cfg(not(target_arch = "wasm32"))]
396        let submission = self.submit([command_buffer])?;
397        #[cfg(target_arch = "wasm32")]
398        self.submit([command_buffer])?;
399        let render_passes = u64::from(packed_texture.is_some());
400        let copy_bytes =
401            u64::from(unpadded_bytes_per_row).saturating_mul(u64::from(target.size.height));
402        crate::diagnostics::record_readback_work(
403            &self.diagnostics,
404            render_passes,
405            1,
406            copy_bytes,
407            true,
408        );
409        Ok(Rgba8Readback {
410            buffer,
411            gpu: self.gpu.clone(),
412            size: target.size,
413            padded_bytes_per_row,
414            unpadded_bytes_per_row,
415            #[cfg(not(target_arch = "wasm32"))]
416            submission,
417            #[cfg(not(target_arch = "wasm32"))]
418            timeout: self.gpu_wait_timeout,
419            staging_bytes: buffer_size,
420            image_bytes,
421            canary,
422            mapping_requested: AtomicBool::new(false),
423        })
424    }
425
426    /// Converts a render result to 8-bit planar YUV420 on the GPU and submits an async readback.
427    ///
428    /// The size must be even. Chroma is filtered for the siting `encoding.chroma` names
429    /// ([`alpha2_media::VideoCodec::chroma_location`]).
430    ///
431    /// # Errors
432    /// [`RenderError::TextureReadback`] for unsupported formats, odd dimensions or unrepresentable
433    /// layouts, and [`RenderError::UnsupportedOutputColor`] for a color the pack cannot write.
434    pub fn begin_yuv420p_readback(
435        &self,
436        target: &RenderedTexture,
437        encoding: YuvEncoding,
438    ) -> Result<Yuv420pReadback, RenderError> {
439        let mut command_encoder = self.command_encoder("alpha2 YUV420P readback encoder");
440        let mut uniforms = self
441            .uniform_buffers
442            .acquire(self.gpu.device(), YUV_PACK_UNIFORM_BYTES);
443        let readback_work =
444            self.encode_yuv420p_readback(target, encoding, &mut command_encoder, &mut uniforms)?;
445        uniforms.flush(self.gpu.queue());
446        #[cfg(not(target_arch = "wasm32"))]
447        let submission = self.submit([command_encoder.finish()])?;
448        #[cfg(target_arch = "wasm32")]
449        self.submit([command_encoder.finish()])?;
450        uniforms.recycle();
451        Ok(self.complete_yuv420p_readback(
452            readback_work,
453            #[cfg(not(target_arch = "wasm32"))]
454            submission,
455            true,
456        ))
457    }
458
459    /// Packs a render result into `layout`'s planes on the GPU and submits an async readback of
460    /// them ([`Yuv420pReadback::finish_into_planes`]), for outputs other than 8-bit 4:2:0.
461    ///
462    /// Codes are the CPU pack's within one, chroma sited as `encoding.chroma` names. 10-bit output
463    /// requires the `rgba16float` intermediate.
464    ///
465    /// # Errors
466    /// [`RenderError::TextureReadback`] for an unsupported format, a 10-bit layout over an 8-bit
467    /// target, a size the chroma cannot subsample or an unrepresentable layout, and
468    /// [`RenderError::UnsupportedOutputColor`] for a color the pack cannot write.
469    pub fn begin_layout_readback(
470        &self,
471        target: &RenderedTexture,
472        encoding: YuvEncoding,
473        layout: PixelLayout,
474    ) -> Result<Yuv420pReadback, RenderError> {
475        let mut encoder = self.command_encoder("alpha2 layout readback encoder");
476        let mut uniforms = self
477            .uniform_buffers
478            .acquire(self.gpu.device(), LAYOUT_PACK_UNIFORM_BYTES);
479        let readback_work =
480            self.encode_layout_readback(target, encoding, layout, &mut encoder, &mut uniforms)?;
481        uniforms.flush(self.gpu.queue());
482        #[cfg(not(target_arch = "wasm32"))]
483        let submission = self.submit([encoder.finish()])?;
484        #[cfg(target_arch = "wasm32")]
485        self.submit([encoder.finish()])?;
486        uniforms.recycle();
487        Ok(self.complete_layout_readback(
488            readback_work,
489            #[cfg(not(target_arch = "wasm32"))]
490            submission,
491            true,
492        ))
493    }
494
495    pub(crate) fn encode_layout_readback(
496        &self,
497        target: &RenderedTexture,
498        encoding: YuvEncoding,
499        layout: PixelLayout,
500        encoder: &mut impl PassEncoder,
501        uniforms: &mut UniformArenaLease,
502    ) -> Result<EncodedLayoutReadback, RenderError> {
503        self.ensure_gpu_runs_work()?;
504        self.validate_size(target.size)?;
505        crate::color::check_packable(encoding)?;
506        check_layout_target(target, layout)?;
507        let staging = StagingLayout::of_layout(layout, target.size)?;
508        let buffer_size = staging.bytes + CANARY_BYTES;
509        let buffer =
510            self.readback_buffers
511                .acquire(self.gpu.device(), buffer_size, "alpha2 layout readback");
512        let [luma, chroma] = LayoutPackPass::of_layout(layout);
513        let chroma_size = layout_chroma_size(target.size, layout);
514        let mut luma_planes = self.layout_pack_planes(luma, target.size);
515        let chroma_planes = self.layout_pack_planes(chroma, chroma_size);
516        let uniform = uniforms.write(bytemuck::cast_slice(&crate::layout_pack::gpu_params(
517            encoding, layout,
518        )))?;
519        let cached = self.layout_pack_pipeline()?;
520        let bind_group = OffsetBindGroup {
521            group: self.bind_group(&wgpu::BindGroupDescriptor {
522                label: Some("alpha2 layout pack bind group"),
523                layout: &cached.bind_group_layout,
524                entries: &[
525                    wgpu::BindGroupEntry {
526                        binding: 0,
527                        resource: wgpu::BindingResource::TextureView(target.view()),
528                    },
529                    wgpu::BindGroupEntry {
530                        binding: 1,
531                        resource: uniforms.dynamic_binding(uniform.size()),
532                    },
533                ],
534            }),
535            offsets: [uniform.dynamic_offset()],
536        };
537        let key = crate::submission_pilot::PassKind::Pack.key(target.size.pixels());
538        for (pass, label, planes, size, work) in [
539            (
540                luma,
541                "alpha2 GPU layout luma pack pass",
542                &luma_planes,
543                target.size,
544                layout_luma_work(target.size),
545            ),
546            (
547                chroma,
548                "alpha2 GPU layout chroma pack pass",
549                &chroma_planes,
550                chroma_size,
551                layout_chroma_work(target.size, layout),
552            ),
553        ] {
554            let pipeline = self.layout_pack_program(cached, pass)?;
555            let views = planes
556                .iter()
557                .map(TextureLease::view)
558                .collect::<arrayvec::ArrayVec<_, 2>>();
559            encoder.placed_pass(work, PixelRect::whole(size), key, |encoder, piece| {
560                encode_yuv_render_pass(encoder, label, pipeline, &bind_group, &views, piece);
561            });
562        }
563        let alpha_plane = layout.alpha.then(|| luma_planes.pop()).flatten();
564        let planes = luma_planes
565            .into_iter()
566            .chain(chroma_planes)
567            .chain(alpha_plane)
568            .collect::<Vec<_>>();
569        encoder.place_whole(layout_copy_work(target.size, layout));
570        let encoder = encoder.commands();
571        for (texture, staged) in planes.iter().zip(&staging.planes) {
572            let texture = texture.texture();
573            let size = RenderSize::new(texture.width(), texture.height())?;
574            encode_plane_copy(
575                encoder,
576                texture,
577                buffer.buffer(),
578                staged.offset,
579                staged.pitch,
580                size,
581            );
582        }
583        let canary = self
584            .canaries
585            .encode(&self.gpu, encoder, buffer.buffer(), staging.bytes)?;
586        Ok(EncodedLayoutReadback {
587            buffer,
588            size: target.size,
589            staging,
590            pixel_layout: layout,
591            staging_bytes: buffer_size,
592            canary,
593            planes,
594        })
595    }
596
597    pub(crate) fn complete_layout_readback(
598        &self,
599        encoded: EncodedLayoutReadback,
600        #[cfg(not(target_arch = "wasm32"))] submission: crate::submission_clock::ClockedSubmission,
601        standalone_submission: bool,
602    ) -> Yuv420pReadback {
603        let EncodedLayoutReadback {
604            buffer,
605            size,
606            staging,
607            pixel_layout,
608            staging_bytes,
609            canary,
610            planes,
611        } = encoded;
612        crate::diagnostics::record_readback_work(
613            &self.diagnostics,
614            LAYOUT_PACK_PASSES,
615            u64::try_from(planes.len()).unwrap_or(u64::MAX),
616            staging.packed_bytes(),
617            standalone_submission,
618        );
619        drop(planes);
620        Yuv420pReadback {
621            buffer,
622            gpu: self.gpu.clone(),
623            size,
624            layout: staging,
625            pixel_layout: Some(pixel_layout),
626            #[cfg(not(target_arch = "wasm32"))]
627            submission,
628            #[cfg(not(target_arch = "wasm32"))]
629            timeout: self.gpu_wait_timeout,
630            staging_bytes,
631            canary,
632            mapping_requested: AtomicBool::new(false),
633        }
634    }
635
636    pub(crate) fn encode_yuv420p_readback(
637        &self,
638        target: &RenderedTexture,
639        encoding: YuvEncoding,
640        encoder: &mut impl PassEncoder,
641        uniforms: &mut UniformArenaLease,
642    ) -> Result<EncodedYuv420pReadback, RenderError> {
643        self.ensure_gpu_runs_work()?;
644        self.validate_size(target.size)?;
645        crate::color::check_packable(encoding)?;
646        if !matches!(
647            target.format,
648            wgpu::TextureFormat::Rgba8Unorm | wgpu::TextureFormat::Rgba16Float
649        ) || !target.size.width.is_multiple_of(2)
650            || !target.size.height.is_multiple_of(2)
651        {
652            return Err(RenderError::TextureReadback(
653                ReadbackFailure::UnsupportedTarget,
654            ));
655        }
656        let layout = StagingLayout::yuv420(target.size)?;
657        let uv_rows = target.size.height / 2;
658        let chroma_width = target.size.width / 2;
659        let buffer_size = layout.bytes + CANARY_BYTES;
660        let buffer = self.readback_buffers.acquire(
661            self.gpu.device(),
662            buffer_size,
663            "alpha2 YUV420P readback",
664        );
665        let y_texture = self.textures.acquire(
666            self.gpu.device(),
667            target.size,
668            wgpu::TextureFormat::R8Unorm,
669            "alpha2 GPU Y readback texture",
670        );
671        let uv_size = RenderSize {
672            width: chroma_width,
673            height: uv_rows,
674        };
675        let u_texture = self.textures.acquire(
676            self.gpu.device(),
677            uv_size,
678            wgpu::TextureFormat::R8Unorm,
679            "alpha2 GPU U readback texture",
680        );
681        let v_texture = self.textures.acquire(
682            self.gpu.device(),
683            uv_size,
684            wgpu::TextureFormat::R8Unorm,
685            "alpha2 GPU V readback texture",
686        );
687        let uniform = uniforms.write(bytemuck::cast_slice(&yuv_uniform(encoding)))?;
688        self.encode_yuv420_pack(
689            target,
690            [y_texture.view(), u_texture.view(), v_texture.view()],
691            encoder,
692            uniforms,
693            uniform,
694        )?;
695        let encoder = encoder.commands();
696        let textures = [
697            (y_texture.texture(), target.size),
698            (u_texture.texture(), uv_size),
699            (v_texture.texture(), uv_size),
700        ];
701        for ((texture, size), plane) in textures.into_iter().zip(&layout.planes) {
702            encode_plane_copy(
703                encoder,
704                texture,
705                buffer.buffer(),
706                plane.offset,
707                plane.pitch,
708                size,
709            );
710        }
711        // Same encoder, after the plane copies. Not counted as a copy in diagnostics.
712        let canary = self
713            .canaries
714            .encode(&self.gpu, encoder, buffer.buffer(), layout.bytes)?;
715        Ok(EncodedYuv420pReadback {
716            buffer,
717            size: target.size,
718            layout,
719            staging_bytes: buffer_size,
720            canary,
721            y_texture,
722            u_texture,
723            v_texture,
724        })
725    }
726
727    pub(crate) fn complete_yuv420p_readback(
728        &self,
729        encoded: EncodedYuv420pReadback,
730        #[cfg(not(target_arch = "wasm32"))] submission: crate::submission_clock::ClockedSubmission,
731        standalone_submission: bool,
732    ) -> Yuv420pReadback {
733        let EncodedYuv420pReadback {
734            buffer,
735            size,
736            layout,
737            staging_bytes,
738            canary,
739            y_texture,
740            u_texture,
741            v_texture,
742        } = encoded;
743        drop((y_texture, u_texture, v_texture));
744        let texture_bytes = yuv420_tight_bytes(size).expect("validated YUV420 dimensions");
745        crate::diagnostics::record_readback_work(
746            &self.diagnostics,
747            2,
748            3,
749            texture_bytes,
750            standalone_submission,
751        );
752        Yuv420pReadback {
753            buffer,
754            gpu: self.gpu.clone(),
755            size,
756            layout,
757            pixel_layout: None,
758            #[cfg(not(target_arch = "wasm32"))]
759            submission,
760            #[cfg(not(target_arch = "wasm32"))]
761            timeout: self.gpu_wait_timeout,
762            staging_bytes,
763            canary,
764            mapping_requested: AtomicBool::new(false),
765        }
766    }
767
768    /// Packs one rendered frame into caller-owned NV12 plane textures.
769    ///
770    /// Same conversion as [`Self::begin_yuv420p_readback`] without the readback. wgpu allows only
771    /// `TEXTURE_BINDING` on `TextureFormat::NV12`, so the native layer copies these `R8Unorm` and
772    /// `Rg8Unorm` targets into the encoder's image afterwards.
773    ///
774    /// # Errors
775    /// [`RenderError::TextureReadback`] for an unaccepted target format or size,
776    /// [`RenderError::InvalidPlaneTarget`] for mismatched plane textures,
777    /// [`RenderError::UnsupportedOutputColor`] for a color the pack cannot write, and
778    /// [`RenderError::GpuWorkDropped`] once the device was found dropping work.
779    #[cfg_attr(not(feature = "wgpu-interop"), doc(hidden))]
780    pub fn encode_nv12_pack(
781        &self,
782        target: &RenderedTexture,
783        planes: Nv12PlaneTargets<'_>,
784        encoding: YuvEncoding,
785        encoder: &mut wgpu::CommandEncoder,
786    ) -> Result<EncodedNv12Pack, RenderError> {
787        let encode = self.open_encode();
788        let mut uniforms = self
789            .uniform_buffers
790            .acquire(self.gpu.device(), YUV_PACK_UNIFORM_BYTES);
791        self.encode_nv12_pack_into(target, planes, encoding, encoder, &mut uniforms)?;
792        uniforms.flush(self.gpu.queue());
793        Ok(EncodedNv12Pack {
794            uniforms: Some(uniforms),
795            _encode: encode,
796        })
797    }
798
799    pub(crate) fn encode_nv12_pack_into(
800        &self,
801        target: &RenderedTexture,
802        planes: Nv12PlaneTargets<'_>,
803        encoding: YuvEncoding,
804        encoder: &mut impl PassEncoder,
805        uniforms: &mut UniformArenaLease,
806    ) -> Result<(), RenderError> {
807        // A pack has no canary of its own; an earlier failed readback canary applies.
808        self.ensure_gpu_runs_work()?;
809        self.validate_size(target.size)?;
810        crate::color::check_packable(encoding)?;
811        if !matches!(
812            target.format,
813            wgpu::TextureFormat::Rgba8Unorm | wgpu::TextureFormat::Rgba16Float
814        ) || !target.size.width.is_multiple_of(2)
815            || !target.size.height.is_multiple_of(2)
816        {
817            return Err(RenderError::TextureReadback(
818                ReadbackFailure::UnsupportedTarget,
819            ));
820        }
821        planes.check(target.size)?;
822        let uniform = uniforms.write(bytemuck::cast_slice(&yuv_uniform(encoding)))?;
823        let cached = self.yuv_readback_pipeline()?;
824        let bind_group = self.yuv_pack_bind_group(target, cached, uniforms, uniform);
825        encode_pack_passes(
826            encoder,
827            &bind_group,
828            target.size,
829            (
830                "alpha2 GPU NV12 Y pack pass",
831                &cached.y_pipeline,
832                &[planes.luma],
833            ),
834            (
835                "alpha2 GPU NV12 UV pack pass",
836                &cached.uv_nv12_pipeline,
837                &[planes.chroma],
838            ),
839        );
840        Ok(())
841    }
842
843    fn yuv_pack_bind_group(
844        &self,
845        target: &RenderedTexture,
846        cached: &CachedYuvReadbackPipeline,
847        uniforms: &crate::uniform::UniformArenaLease,
848        uniform: crate::uniform::UniformSlice,
849    ) -> OffsetBindGroup<1> {
850        let group = self.bind_group(&wgpu::BindGroupDescriptor {
851            label: Some("alpha2 RGB to YUV bind group"),
852            layout: &cached.bind_group_layout,
853            entries: &[
854                wgpu::BindGroupEntry {
855                    binding: 0,
856                    resource: wgpu::BindingResource::TextureView(target.view()),
857                },
858                wgpu::BindGroupEntry {
859                    binding: 1,
860                    resource: uniforms.dynamic_binding(uniform.size()),
861                },
862            ],
863        });
864        OffsetBindGroup {
865            group,
866            offsets: [uniform.dynamic_offset()],
867        }
868    }
869
870    pub(crate) fn encode_pilot_pack(
871        &self,
872        target: &RenderedTexture,
873        plane_views: [&wgpu::TextureView; 3],
874        encoder: &mut crate::renderer::RenderEncoder,
875        uniforms: &mut UniformArenaLease,
876    ) -> Result<(), RenderError> {
877        let uniform = uniforms.write(bytemuck::cast_slice(&yuv_uniform(YuvEncoding::export(
878            alpha2_media::VideoCodec::H264,
879        ))))?;
880        self.encode_yuv420_pack(target, plane_views, encoder, uniforms, uniform)
881    }
882
883    fn encode_yuv420_pack(
884        &self,
885        target: &RenderedTexture,
886        plane_views: [&wgpu::TextureView; 3],
887        encoder: &mut impl PassEncoder,
888        uniforms: &crate::uniform::UniformArenaLease,
889        uniform: crate::uniform::UniformSlice,
890    ) -> Result<(), RenderError> {
891        let cached = self.yuv_readback_pipeline()?;
892        let bind_group = self.yuv_pack_bind_group(target, cached, uniforms, uniform);
893        let [y_view, u_view, v_view] = plane_views;
894        encode_pack_passes(
895            encoder,
896            &bind_group,
897            target.size,
898            ("alpha2 GPU Y pack pass", &cached.y_pipeline, &[y_view]),
899            (
900                "alpha2 GPU UV pack pass",
901                &cached.uv_pipeline,
902                &[u_view, v_view],
903            ),
904        );
905        Ok(())
906    }
907
908    fn yuv_readback_pipeline(&self) -> Result<&CachedYuvReadbackPipeline, RenderError> {
909        crate::gpu_errors::checked_cell(&self.pipelines.yuv_readback, self.gpu.device(), || {
910            let bind_group_layout =
911                self.gpu
912                    .device()
913                    .create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
914                        label: Some("alpha2 RGB to YUV layout"),
915                        entries: &[
916                            wgpu::BindGroupLayoutEntry {
917                                binding: 0,
918                                visibility: wgpu::ShaderStages::FRAGMENT,
919                                ty: wgpu::BindingType::Texture {
920                                    sample_type: wgpu::TextureSampleType::Float {
921                                        filterable: false,
922                                    },
923                                    view_dimension: wgpu::TextureViewDimension::D2,
924                                    multisampled: false,
925                                },
926                                count: None,
927                            },
928                            wgpu::BindGroupLayoutEntry {
929                                binding: 1,
930                                visibility: wgpu::ShaderStages::FRAGMENT,
931                                ty: wgpu::BindingType::Buffer {
932                                    ty: wgpu::BufferBindingType::Uniform,
933                                    has_dynamic_offset: true,
934                                    min_binding_size: None,
935                                },
936                                count: None,
937                            },
938                        ],
939                    });
940            let shader = self
941                .gpu
942                .device()
943                .create_shader_module(wgpu::ShaderModuleDescriptor {
944                    label: Some("alpha2 RGB to YUV shader"),
945                    source: wgpu::ShaderSource::Wgsl(RGB_TO_YUV420_WGSL.into()),
946                });
947            let layout =
948                self.gpu
949                    .device()
950                    .create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
951                        label: Some("alpha2 RGB to YUV pipeline layout"),
952                        bind_group_layouts: &[Some(&bind_group_layout)],
953                        immediate_size: 0,
954                    });
955            CachedYuvReadbackPipeline {
956                y_pipeline: yuv_render_pipeline(
957                    self.gpu.device(),
958                    &layout,
959                    &shader,
960                    "y_fs",
961                    &[wgpu::TextureFormat::R8Unorm],
962                ),
963                uv_pipeline: yuv_render_pipeline(
964                    self.gpu.device(),
965                    &layout,
966                    &shader,
967                    "uv_fs",
968                    &[wgpu::TextureFormat::R8Unorm, wgpu::TextureFormat::R8Unorm],
969                ),
970                uv_nv12_pipeline: yuv_render_pipeline(
971                    self.gpu.device(),
972                    &layout,
973                    &shader,
974                    "uv_nv12_fs",
975                    &[wgpu::TextureFormat::Rg8Unorm],
976                ),
977                bind_group_layout,
978            }
979        })
980    }
981
982    fn layout_pack_pipeline(&self) -> Result<&CachedLayoutPackPipeline, RenderError> {
983        crate::gpu_errors::checked_cell(&self.pipelines.layout_pack, self.gpu.device(), || {
984            let device = self.gpu.device();
985            let bind_group_layout =
986                device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
987                    label: Some("alpha2 layout pack layout"),
988                    entries: &[
989                        wgpu::BindGroupLayoutEntry {
990                            binding: 0,
991                            visibility: wgpu::ShaderStages::FRAGMENT,
992                            ty: wgpu::BindingType::Texture {
993                                sample_type: wgpu::TextureSampleType::Float { filterable: false },
994                                view_dimension: wgpu::TextureViewDimension::D2,
995                                multisampled: false,
996                            },
997                            count: None,
998                        },
999                        wgpu::BindGroupLayoutEntry {
1000                            binding: 1,
1001                            visibility: wgpu::ShaderStages::FRAGMENT,
1002                            ty: wgpu::BindingType::Buffer {
1003                                ty: wgpu::BufferBindingType::Uniform,
1004                                has_dynamic_offset: true,
1005                                min_binding_size: None,
1006                            },
1007                            count: None,
1008                        },
1009                    ],
1010                });
1011            let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
1012                label: Some("alpha2 layout pack shader"),
1013                source: wgpu::ShaderSource::Wgsl(LAYOUT_PACK_WGSL.into()),
1014            });
1015            let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
1016                label: Some("alpha2 layout pack pipeline layout"),
1017                bind_group_layouts: &[Some(&bind_group_layout)],
1018                immediate_size: 0,
1019            });
1020            CachedLayoutPackPipeline {
1021                bind_group_layout,
1022                pipeline_layout,
1023                shader,
1024                programs: Default::default(),
1025            }
1026        })
1027    }
1028
1029    fn layout_pack_planes(&self, pass: LayoutPackPass, size: RenderSize) -> Vec<TextureLease> {
1030        pass.target_formats()
1031            .into_iter()
1032            .map(|format| {
1033                self.textures.acquire(
1034                    self.gpu.device(),
1035                    size,
1036                    format,
1037                    "alpha2 GPU layout pack plane",
1038                )
1039            })
1040            .collect()
1041    }
1042
1043    fn layout_pack_program<'a>(
1044        &self,
1045        cached: &'a CachedLayoutPackPipeline,
1046        pass: LayoutPackPass,
1047    ) -> Result<&'a wgpu::RenderPipeline, RenderError> {
1048        crate::gpu_errors::checked_cell(&cached.programs[pass.index()], self.gpu.device(), || {
1049            yuv_render_pipeline(
1050                self.gpu.device(),
1051                &cached.pipeline_layout,
1052                &cached.shader,
1053                pass.entry_point(),
1054                &pass.target_formats(),
1055            )
1056        })
1057    }
1058
1059    fn encode_readback_pack(
1060        &self,
1061        target: &RenderedTexture,
1062        encoder: &mut wgpu::CommandEncoder,
1063    ) -> Result<Option<TextureLease>, RenderError> {
1064        if target.format != wgpu::TextureFormat::Rgba16Float {
1065            return Ok(None);
1066        }
1067        let texture = self.textures.acquire(
1068            self.gpu.device(),
1069            target.size,
1070            wgpu::TextureFormat::Rgba8Unorm,
1071            "alpha2 GPU-packed RGBA8 readback texture",
1072        );
1073        let cached = self.readback_pack_pipeline()?;
1074        let bind_group = self.bind_group(&wgpu::BindGroupDescriptor {
1075            label: Some("alpha2 readback pack bind group"),
1076            layout: &cached.bind_group_layout,
1077            entries: &[wgpu::BindGroupEntry {
1078                binding: 0,
1079                resource: wgpu::BindingResource::TextureView(target.view()),
1080            }],
1081        });
1082        {
1083            let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
1084                label: Some("alpha2 GPU RGBA8 readback pack pass"),
1085                color_attachments: &[Some(wgpu::RenderPassColorAttachment {
1086                    view: texture.view(),
1087                    depth_slice: None,
1088                    resolve_target: None,
1089                    ops: wgpu::Operations {
1090                        load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT),
1091                        store: wgpu::StoreOp::Store,
1092                    },
1093                })],
1094                depth_stencil_attachment: None,
1095                timestamp_writes: None,
1096                occlusion_query_set: None,
1097                multiview_mask: None,
1098            });
1099            pass.set_pipeline(&cached.pipeline);
1100            pass.set_bind_group(0, &bind_group, &[]);
1101            pass.draw(0..3, 0..1);
1102        }
1103        Ok(Some(texture))
1104    }
1105
1106    fn readback_pack_pipeline(&self) -> Result<&CachedPipeline, RenderError> {
1107        crate::gpu_errors::checked_cell(&self.pipelines.readback_pack, self.gpu.device(), || {
1108            let bind_group_layout =
1109                self.gpu
1110                    .device()
1111                    .create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
1112                        label: Some("alpha2 readback pack layout"),
1113                        entries: &[wgpu::BindGroupLayoutEntry {
1114                            binding: 0,
1115                            visibility: wgpu::ShaderStages::FRAGMENT,
1116                            ty: wgpu::BindingType::Texture {
1117                                sample_type: wgpu::TextureSampleType::Float { filterable: false },
1118                                view_dimension: wgpu::TextureViewDimension::D2,
1119                                multisampled: false,
1120                            },
1121                            count: None,
1122                        }],
1123                    });
1124            let shader = self
1125                .gpu
1126                .device()
1127                .create_shader_module(wgpu::ShaderModuleDescriptor {
1128                    label: Some("alpha2 readback pack shader"),
1129                    source: wgpu::ShaderSource::Wgsl(READBACK_PACK_WGSL.into()),
1130                });
1131            let layout =
1132                self.gpu
1133                    .device()
1134                    .create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
1135                        label: Some("alpha2 readback pack pipeline layout"),
1136                        bind_group_layouts: &[Some(&bind_group_layout)],
1137                        immediate_size: 0,
1138                    });
1139            let pipeline =
1140                self.gpu
1141                    .device()
1142                    .create_render_pipeline(&wgpu::RenderPipelineDescriptor {
1143                        label: Some("alpha2 readback pack pipeline"),
1144                        layout: Some(&layout),
1145                        vertex: wgpu::VertexState {
1146                            module: &shader,
1147                            entry_point: Some("vs"),
1148                            buffers: &[],
1149                            compilation_options: wgpu::PipelineCompilationOptions::default(),
1150                        },
1151                        fragment: Some(wgpu::FragmentState {
1152                            module: &shader,
1153                            entry_point: Some("fs"),
1154                            targets: &[Some(wgpu::TextureFormat::Rgba8Unorm.into())],
1155                            compilation_options: wgpu::PipelineCompilationOptions::default(),
1156                        }),
1157                        primitive: wgpu::PrimitiveState::default(),
1158                        depth_stencil: None,
1159                        multisample: wgpu::MultisampleState::default(),
1160                        multiview_mask: None,
1161                        cache: None,
1162                    });
1163            CachedPipeline {
1164                bind_group_layout,
1165                pipeline,
1166            }
1167        })
1168    }
1169}
1170
1171/// A submitted texture readback whose buffer has not been mapped yet.
1172///
1173/// Owns its staging buffer, so it can move into an async browser task.
1174#[derive(Debug)]
1175pub struct Rgba8Readback {
1176    buffer: ReadbackBufferLease,
1177    gpu: GpuContext,
1178    size: RenderSize,
1179    padded_bytes_per_row: u32,
1180    unpadded_bytes_per_row: u32,
1181    #[cfg(not(target_arch = "wasm32"))]
1182    submission: crate::submission_clock::ClockedSubmission,
1183    #[cfg(not(target_arch = "wasm32"))]
1184    timeout: std::time::Duration,
1185    staging_bytes: u64,
1186    image_bytes: u64,
1187    canary: Canary,
1188    mapping_requested: AtomicBool,
1189}
1190
1191impl Rgba8Readback {
1192    /// Test-only: expect a different canary, simulating a stale staging buffer.
1193    #[cfg(test)]
1194    pub(crate) fn expecting(mut self, canary: Canary) -> Self {
1195        self.canary = canary;
1196        self
1197    }
1198
1199    /// The pixel dimensions of the result.
1200    #[must_use]
1201    pub const fn size(&self) -> RenderSize {
1202        self.size
1203    }
1204
1205    /// Bytes held by the staging buffer.
1206    #[must_use]
1207    pub const fn staging_bytes(&self) -> u64 {
1208        self.staging_bytes
1209    }
1210
1211    /// Blocks a native caller until this readback is mapped, without draining the whole queue.
1212    ///
1213    /// # Errors
1214    /// [`RenderError::TextureReadback`] when mapping or device polling fails.
1215    #[cfg(not(target_arch = "wasm32"))]
1216    pub fn wait_ready(&self) -> Result<(), RenderError> {
1217        let (sender, receiver) = mpsc::channel();
1218        self.map_async(move |mapped| {
1219            let _ = sender.send(mapped);
1220        });
1221        self.submission.wait(&self.gpu, self.timeout)?;
1222        receive_mapped(&self.gpu, &receiver, self.timeout)?
1223    }
1224
1225    /// Waits for this readback and returns tightly packed RGBA8 pixels.
1226    ///
1227    /// # Errors
1228    /// [`RenderError::TextureReadback`] when mapping, polling or row packing fails.
1229    #[cfg(not(target_arch = "wasm32"))]
1230    pub fn wait(self) -> Result<Vec<u8>, RenderError> {
1231        self.wait_ready()?;
1232        self.finish()
1233    }
1234
1235    /// Requests buffer mapping and reports readiness exactly once.
1236    ///
1237    /// A refused or repeated request reports a failure, which callers must treat as a failed frame.
1238    pub fn map_async(&self, on_ready: impl FnOnce(Result<(), RenderError>) + Send + 'static) {
1239        map_staging(&self.gpu, &self.buffer, &self.mapping_requested, on_ready);
1240    }
1241
1242    /// Polls backends that need it to resolve a mapping; browser `WebGPU` ignores this.
1243    pub fn poll(&self) {
1244        let _ = self.gpu.device().poll(wgpu::PollType::Poll);
1245    }
1246
1247    /// Packs the mapped rows into tightly packed premultiplied RGBA8.
1248    ///
1249    /// # Errors
1250    /// [`RenderError::TextureReadback`] when the buffer is not mapped, and
1251    /// [`RenderError::GpuWorkDropped`] when the GPU did not run the copy; the buffer is then not
1252    /// recycled and the renderer refuses further work.
1253    pub fn finish(self) -> Result<Vec<u8>, RenderError> {
1254        let Ok(view) = self.buffer.buffer().slice(..).get_mapped_range() else {
1255            // Unmapping an unmapped buffer is a validation error. Dropping the lease destroys the
1256            // buffer and ends any pending mapping.
1257            return Err(RenderError::TextureReadback(ReadbackFailure::NotMapped));
1258        };
1259        let image_bytes = usize::try_from(self.image_bytes)
1260            .map_err(|_| RenderError::TextureReadback(ReadbackFailure::Layout))?;
1261        let checked = view
1262            .get(image_bytes..)
1263            .ok_or(RenderError::TextureReadback(ReadbackFailure::Layout))
1264            .and_then(|found| self.canary.check(found));
1265        if let Err(error) = checked {
1266            drop(view);
1267            self.buffer.buffer().unmap();
1268            return Err(error);
1269        }
1270        let mapped = &view[..image_bytes];
1271        let padded_row = usize::try_from(self.padded_bytes_per_row)
1272            .map_err(|_| RenderError::TextureReadback(ReadbackFailure::Layout))?;
1273        let unpadded_row = usize::try_from(self.unpadded_bytes_per_row)
1274            .map_err(|_| RenderError::TextureReadback(ReadbackFailure::Layout))?;
1275        let packed = if padded_row == unpadded_row {
1276            mapped.to_vec()
1277        } else {
1278            let capacity = unpadded_row
1279                .checked_mul(
1280                    usize::try_from(self.size.height)
1281                        .map_err(|_| RenderError::TextureReadback(ReadbackFailure::Layout))?,
1282                )
1283                .ok_or(RenderError::TextureReadback(ReadbackFailure::Layout))?;
1284            let mut packed = Vec::with_capacity(capacity);
1285            for row in mapped.chunks_exact(padded_row) {
1286                packed.extend_from_slice(&row[..unpadded_row]);
1287            }
1288            packed
1289        };
1290        drop(view);
1291        self.buffer.buffer().unmap();
1292        self.buffer.recycle();
1293        Ok(packed)
1294    }
1295}
1296
1297/// GPU state an NV12 pack recorded into a caller's encoder still needs.
1298///
1299/// Drop it only after that encoder is submitted; dropping earlier lets a later renderer call
1300/// overwrite the pack's uniforms.
1301#[must_use = "hold the pack until its encoder is submitted"]
1302#[derive(Debug)]
1303#[cfg_attr(not(feature = "wgpu-interop"), doc(hidden))]
1304pub struct EncodedNv12Pack {
1305    uniforms: Option<crate::uniform::UniformArenaLease>,
1306    /// Defers destruction of released pool resources until the pack is dropped.
1307    _encode: crate::retire::EncodeScope,
1308}
1309
1310impl Drop for EncodedNv12Pack {
1311    fn drop(&mut self) {
1312        if let Some(uniforms) = self.uniforms.take() {
1313            uniforms.recycle();
1314        }
1315    }
1316}
1317
1318/// Default views of caller-owned NV12 plane textures for a readback-free pack.
1319///
1320/// `luma` views an `R8Unorm` texture at the output size; `chroma` an `Rg8Unorm` texture at half
1321/// size with U in red and V in green. Keep the views with their textures: a pack creates none.
1322#[derive(Clone, Copy, Debug)]
1323#[cfg_attr(not(feature = "wgpu-interop"), doc(hidden))]
1324pub struct Nv12PlaneTargets<'a> {
1325    /// Full-size single-channel luma target.
1326    pub luma: &'a wgpu::TextureView,
1327    /// Half-size two-channel interleaved chroma target.
1328    pub chroma: &'a wgpu::TextureView,
1329}
1330
1331impl Nv12PlaneTargets<'_> {
1332    pub(crate) fn check(self, size: RenderSize) -> Result<(), RenderError> {
1333        let attachment = |texture: &wgpu::Texture| {
1334            texture
1335                .usage()
1336                .contains(wgpu::TextureUsages::RENDER_ATTACHMENT)
1337                && texture.mip_level_count() == 1
1338                && texture.sample_count() == 1
1339                && texture.depth_or_array_layers() == 1
1340        };
1341        let (luma, chroma) = (self.luma.texture(), self.chroma.texture());
1342        if luma.format() != wgpu::TextureFormat::R8Unorm
1343            || chroma.format() != wgpu::TextureFormat::Rg8Unorm
1344            || luma.width() != size.width
1345            || luma.height() != size.height
1346            || chroma.width() != size.width / 2
1347            || chroma.height() != size.height / 2
1348            || !attachment(luma)
1349            || !attachment(chroma)
1350        {
1351            return Err(RenderError::InvalidPlaneTarget);
1352        }
1353        Ok(())
1354    }
1355}
1356
1357/// A caller-owned destination for one packed plane.
1358#[derive(Debug)]
1359pub struct PlaneTarget<'a> {
1360    pub(crate) bytes: &'a mut [u8],
1361    pub(crate) stride: usize,
1362}
1363
1364impl<'a> PlaneTarget<'a> {
1365    /// Describes plane memory whose rows start `stride` bytes apart.
1366    #[must_use]
1367    pub fn new(bytes: &'a mut [u8], stride: usize) -> Self {
1368        Self { bytes, stride }
1369    }
1370
1371    /// The plane memory.
1372    #[must_use]
1373    pub fn bytes(&self) -> &[u8] {
1374        self.bytes
1375    }
1376
1377    /// Reborrows the plane memory.
1378    pub fn reborrow(&mut self) -> PlaneTarget<'_> {
1379        PlaneTarget {
1380            bytes: self.bytes,
1381            stride: self.stride,
1382        }
1383    }
1384
1385    pub(crate) fn fits(&self, width: usize, height: usize) -> Result<(), RenderError> {
1386        if self.stride < width {
1387            return Err(RenderError::TextureReadback(
1388                ReadbackFailure::DestinationTooSmall,
1389            ));
1390        }
1391        // The last row needs only its visible width, as `FFmpeg` sizes a frame's final plane.
1392        let needed = self
1393            .stride
1394            .checked_mul(height.saturating_sub(1))
1395            .and_then(|rows| rows.checked_add(width))
1396            .ok_or(RenderError::TextureReadback(
1397                ReadbackFailure::DestinationTooSmall,
1398            ))?;
1399        if self.bytes.len() < needed {
1400            return Err(RenderError::TextureReadback(
1401                ReadbackFailure::DestinationTooSmall,
1402            ));
1403        }
1404        Ok(())
1405    }
1406
1407    fn row(&mut self, index: usize, width: usize) -> Result<&mut [u8], RenderError> {
1408        let start = index
1409            .checked_mul(self.stride)
1410            .ok_or(RenderError::TextureReadback(
1411                ReadbackFailure::DestinationTooSmall,
1412            ))?;
1413        let end = start
1414            .checked_add(width)
1415            .ok_or(RenderError::TextureReadback(
1416                ReadbackFailure::DestinationTooSmall,
1417            ))?;
1418        self.bytes
1419            .get_mut(start..end)
1420            .ok_or(RenderError::TextureReadback(
1421                ReadbackFailure::DestinationTooSmall,
1422            ))
1423    }
1424}
1425
1426/// Destinations for the three planes of one packed frame.
1427#[derive(Debug)]
1428pub struct Yuv420pTargets<'a> {
1429    /// Full-resolution luma.
1430    pub y: PlaneTarget<'a>,
1431    /// Half-resolution blue-difference chroma.
1432    pub u: PlaneTarget<'a>,
1433    /// Half-resolution red-difference chroma.
1434    pub v: PlaneTarget<'a>,
1435}
1436
1437/// Tightly packed planar YUV420 data produced by a GPU readback.
1438#[derive(Clone, Debug, Eq, PartialEq)]
1439pub struct Yuv420pPlanes {
1440    /// Full-resolution luma samples.
1441    pub y: Vec<u8>,
1442    /// Half-width, half-height blue-difference chroma samples.
1443    pub u: Vec<u8>,
1444    /// Half-width, half-height red-difference chroma samples.
1445    pub v: Vec<u8>,
1446}
1447
1448/// A submitted GPU pack of a frame into YUV planes whose buffer is not mapped yet.
1449#[derive(Debug)]
1450pub struct Yuv420pReadback {
1451    buffer: ReadbackBufferLease,
1452    gpu: GpuContext,
1453    size: RenderSize,
1454    layout: StagingLayout,
1455    pixel_layout: Option<PixelLayout>,
1456    #[cfg(not(target_arch = "wasm32"))]
1457    submission: crate::submission_clock::ClockedSubmission,
1458    #[cfg(not(target_arch = "wasm32"))]
1459    timeout: std::time::Duration,
1460    staging_bytes: u64,
1461    canary: Canary,
1462    mapping_requested: AtomicBool,
1463}
1464
1465impl Yuv420pReadback {
1466    /// The luma-plane dimensions.
1467    #[must_use]
1468    pub const fn size(&self) -> RenderSize {
1469        self.size
1470    }
1471
1472    /// Bytes held by the staging buffer.
1473    #[must_use]
1474    pub const fn staging_bytes(&self) -> u64 {
1475        self.staging_bytes
1476    }
1477
1478    /// Blocks a native caller until this readback is mapped.
1479    ///
1480    /// # Errors
1481    /// Returns [`RenderError::TextureReadback`] when mapping or polling fails.
1482    #[cfg(not(target_arch = "wasm32"))]
1483    pub fn wait_ready(&self) -> Result<(), RenderError> {
1484        let (sender, receiver) = mpsc::channel();
1485        self.map_async(move |mapped| {
1486            let _ = sender.send(mapped);
1487        });
1488        self.wait_for_submission()?;
1489        self.wait_for_mapped(&receiver)?
1490    }
1491
1492    /// Waits for what a [`Self::map_async`] callback sends to `receiver`, after
1493    /// [`Self::wait_for_submission`], polling the device, for at most the renderer's wait timeout.
1494    ///
1495    /// # Errors
1496    /// [`RenderError::GpuTimeout`] when nothing arrives in time, and
1497    /// [`ReadbackFailure::CallbackDropped`] when the callback was dropped without sending.
1498    #[cfg(not(target_arch = "wasm32"))]
1499    pub fn wait_for_mapped<T>(&self, receiver: &mpsc::Receiver<T>) -> Result<T, RenderError> {
1500        receive_mapped(&self.gpu, receiver, self.timeout)
1501    }
1502
1503    /// Blocks until this readback's submission completes; may follow an earlier
1504    /// [`Self::map_async`].
1505    ///
1506    /// # Errors
1507    /// [`RenderError::GpuTimeout`] past the renderer's wait timeout, or
1508    /// [`RenderError::TextureReadback`] when device polling fails.
1509    #[cfg(not(target_arch = "wasm32"))]
1510    pub fn wait_for_submission(&self) -> Result<(), RenderError> {
1511        self.submission.wait(&self.gpu, self.timeout)?;
1512        Ok(())
1513    }
1514
1515    /// Waits for this readback and returns tightly packed planes.
1516    ///
1517    /// # Errors
1518    /// [`RenderError::TextureReadback`] when mapping, polling or row packing fails.
1519    #[cfg(not(target_arch = "wasm32"))]
1520    pub fn wait(self) -> Result<Yuv420pPlanes, RenderError> {
1521        self.wait_ready()?;
1522        self.finish()
1523    }
1524
1525    /// Requests buffer mapping and reports readiness exactly once.
1526    pub fn map_async(&self, on_ready: impl FnOnce(Result<(), RenderError>) + Send + 'static) {
1527        map_staging(&self.gpu, &self.buffer, &self.mapping_requested, on_ready);
1528    }
1529
1530    /// Polls backends that need it to resolve a mapping.
1531    pub fn poll(&self) {
1532        let _ = self.gpu.device().poll(wgpu::PollType::Poll);
1533    }
1534
1535    /// Packs mapped planes into caller-owned, possibly strided, plane buffers, avoiding the
1536    /// allocation and copy of [`Yuv420pReadback::finish`].
1537    ///
1538    /// # Errors [`RenderError::TextureReadback`] when the buffer is not mapped, the layout is
1539    /// unrepresentable or a target is too small, and [`RenderError::GpuWorkDropped`] when the GPU
1540    /// did not run the copy (the buffer is not recycled and the renderer refuses further work).
1541    pub fn finish_into(self, targets: &mut Yuv420pTargets<'_>) -> Result<(), RenderError> {
1542        if self.pixel_layout.is_some() {
1543            return Err(RenderError::TextureReadback(ReadbackFailure::Layout));
1544        }
1545        self.copy_planes(&mut [&mut targets.y, &mut targets.u, &mut targets.v])
1546    }
1547
1548    fn copy_planes(self, targets: &mut [&mut PlaneTarget<'_>]) -> Result<(), RenderError> {
1549        if targets.len() != self.layout.planes.len() {
1550            return Err(RenderError::TextureReadback(ReadbackFailure::Layout));
1551        }
1552        let Ok(mapped) = self.buffer.buffer().slice(..).get_mapped_range() else {
1553            // Not mapped, so nothing to unmap.
1554            return Err(RenderError::TextureReadback(ReadbackFailure::NotMapped));
1555        };
1556        let result = (|| {
1557            self.check_canary(&mapped)?;
1558            for (plane, target) in self.layout.planes.iter().zip(targets.iter_mut()) {
1559                let width = usize::try_from(plane.row_bytes)
1560                    .map_err(|_| RenderError::TextureReadback(ReadbackFailure::Layout))?;
1561                let rows = usize::try_from(plane.rows)
1562                    .map_err(|_| RenderError::TextureReadback(ReadbackFailure::Layout))?;
1563                target.fits(width, rows)?;
1564                for (index, row) in plane_rows(&mapped, *plane)?.enumerate() {
1565                    target.row(index, width)?.copy_from_slice(&row[..width]);
1566                }
1567            }
1568            Ok(())
1569        })();
1570        drop(mapped);
1571        self.buffer.buffer().unmap();
1572        if result.is_ok() {
1573            self.buffer.recycle();
1574        }
1575        result
1576    }
1577
1578    /// Packs mapped planes into three tightly packed planes.
1579    ///
1580    /// # Errors
1581    /// As [`Self::finish_into`].
1582    pub fn finish(self) -> Result<Yuv420pPlanes, RenderError> {
1583        let planes = self.unpack(|[y, u, v]| Yuv420pPlanes { y, u, v })?;
1584        Ok(planes)
1585    }
1586
1587    /// Plane offsets and strides in the bytes [`Self::finish_mapped`] hands over, in storage
1588    /// order.
1589    #[must_use]
1590    #[cfg_attr(not(feature = "wgpu-interop"), doc(hidden))]
1591    pub fn plane_layout(&self) -> Vec<StagingPlane> {
1592        self.layout
1593            .planes
1594            .iter()
1595            .map(|plane| StagingPlane {
1596                offset: plane.offset,
1597                stride: plane.pitch,
1598            })
1599            .collect()
1600    }
1601
1602    /// Hands the mapped staging buffer to `read`, then unmaps it.
1603    ///
1604    /// Planes are at the offsets and strides [`Self::plane_layout`] reports, rows padded to the
1605    /// copy alignment. A strided consumer such as a `WebCodecs` `VideoFrame` can copy straight from
1606    /// the mapping; in a browser that copy can stay in JavaScript (`BufferView::as_uint8array`).
1607    ///
1608    /// # Errors
1609    /// As [`Self::finish_into`]; `read` is not called then.
1610    #[cfg_attr(not(feature = "wgpu-interop"), doc(hidden))]
1611    pub fn finish_mapped<T>(
1612        self,
1613        read: impl FnOnce(&wgpu::BufferView) -> T,
1614    ) -> Result<T, RenderError> {
1615        let Ok(canary) = self
1616            .buffer
1617            .buffer()
1618            .slice(self.image_bytes()..)
1619            .get_mapped_range()
1620        else {
1621            // Not mapped, so nothing to unmap.
1622            return Err(RenderError::TextureReadback(ReadbackFailure::NotMapped));
1623        };
1624        let checked = self.canary.check(&canary);
1625        drop(canary);
1626        if let Err(error) = checked {
1627            self.buffer.buffer().unmap();
1628            return Err(error);
1629        }
1630        let Ok(mapped) = self
1631            .buffer
1632            .buffer()
1633            .slice(..self.image_bytes())
1634            .get_mapped_range()
1635        else {
1636            self.buffer.buffer().unmap();
1637            return Err(RenderError::TextureReadback(ReadbackFailure::NotMapped));
1638        };
1639        let result = read(&mapped);
1640        drop(mapped);
1641        self.buffer.buffer().unmap();
1642        self.buffer.recycle();
1643        Ok(result)
1644    }
1645
1646    /// Copies the three planes out tightly packed and hands them to `pack`.
1647    fn unpack<T>(self, pack: impl FnOnce([Vec<u8>; 3]) -> T) -> Result<T, RenderError> {
1648        if self.pixel_layout.is_some() {
1649            return Err(RenderError::TextureReadback(ReadbackFailure::Layout));
1650        }
1651        let Ok(mapped) = self.buffer.buffer().slice(..).get_mapped_range() else {
1652            // Not mapped, so nothing to unmap.
1653            return Err(RenderError::TextureReadback(ReadbackFailure::NotMapped));
1654        };
1655        if let Err(error) = self.check_canary(&mapped) {
1656            drop(mapped);
1657            self.buffer.buffer().unmap();
1658            return Err(error);
1659        }
1660        let [y, u, v] = [0, 1, 2].map(|index| self.layout.planes[index]);
1661        let planes = [y, u, v].map(|plane| {
1662            let width = usize::try_from(plane.row_bytes)
1663                .map_err(|_| RenderError::TextureReadback(ReadbackFailure::Layout))?;
1664            let rows = usize::try_from(plane.rows)
1665                .map_err(|_| RenderError::TextureReadback(ReadbackFailure::Layout))?;
1666            plane_rows(&mapped, plane).map(|source| {
1667                let mut tight = Vec::with_capacity(width * rows);
1668                for row in source {
1669                    tight.extend_from_slice(&row[..width]);
1670                }
1671                tight
1672            })
1673        });
1674        drop(mapped);
1675        self.buffer.buffer().unmap();
1676        let [y, u, v] = planes;
1677        let planes = [y?, u?, v?];
1678        self.buffer.recycle();
1679        Ok(pack(planes))
1680    }
1681
1682    /// Bytes before the canary.
1683    fn image_bytes(&self) -> u64 {
1684        self.layout.bytes
1685    }
1686
1687    /// The layout a layout readback ([`Renderer::begin_layout_readback`]) packed, `None` for an
1688    /// 8-bit 4:2:0 readback.
1689    #[must_use]
1690    pub fn pixel_layout(&self) -> Option<PixelLayout> {
1691        self.pixel_layout
1692    }
1693
1694    /// Copies the mapped planes into one target per plane, in storage order
1695    /// ([`PixelLayout::planes`], or Y, U, V for 8-bit 4:2:0).
1696    ///
1697    /// # Errors
1698    /// As [`Self::finish_into`], and [`RenderError::TextureReadback`] for a wrong target count.
1699    pub fn finish_into_planes(self, targets: &mut [PlaneTarget<'_>]) -> Result<(), RenderError> {
1700        self.copy_planes(&mut targets.iter_mut().collect::<Vec<_>>())
1701    }
1702
1703    /// Checks that the mapped buffer ends in this readback's canary; a failing buffer is not
1704    /// recycled.
1705    fn check_canary(&self, mapped: &[u8]) -> Result<(), RenderError> {
1706        let start = usize::try_from(self.image_bytes())
1707            .map_err(|_| RenderError::TextureReadback(ReadbackFailure::Layout))?;
1708        let found = mapped
1709            .get(start..)
1710            .ok_or(RenderError::TextureReadback(ReadbackFailure::Layout))?;
1711        self.canary.check(found)
1712    }
1713}
1714
1715/// A map callback runs on whichever thread's poll collected the mapping, possibly after this
1716/// thread's own wait returned.
1717#[cfg(not(target_arch = "wasm32"))]
1718fn receive_mapped<T>(
1719    gpu: &GpuContext,
1720    receiver: &mpsc::Receiver<T>,
1721    timeout: std::time::Duration,
1722) -> Result<T, RenderError> {
1723    crate::settle::receive_polling(receiver, timeout, || {
1724        let _ = gpu.device().poll(wgpu::PollType::Poll);
1725    })
1726}
1727
1728/// How the next [`map_staging`] on this thread delivers its callback in tests.
1729#[cfg(test)]
1730#[derive(Clone, Copy, Debug)]
1731pub(crate) enum MapReport {
1732    /// From another thread, after this delay.
1733    Elsewhere(std::time::Duration),
1734    Never,
1735}
1736
1737#[cfg(test)]
1738thread_local! {
1739    pub(crate) static MAP_REPORT: std::cell::Cell<Option<MapReport>> =
1740        const { std::cell::Cell::new(None) };
1741}
1742
1743fn map_staging(
1744    gpu: &GpuContext,
1745    buffer: &ReadbackBufferLease,
1746    requested: &AtomicBool,
1747    on_ready: impl FnOnce(Result<(), RenderError>) + Send + 'static,
1748) {
1749    #[cfg(test)]
1750    let on_ready = {
1751        let report = MAP_REPORT.with(std::cell::Cell::take);
1752        move |result: Result<(), RenderError>| match report {
1753            None => on_ready(result),
1754            Some(MapReport::Elsewhere(delay)) => {
1755                std::thread::spawn(move || {
1756                    std::thread::sleep(delay);
1757                    on_ready(result);
1758                });
1759            }
1760            Some(MapReport::Never) => std::mem::forget(on_ready),
1761        }
1762    };
1763    if requested.swap(true, Ordering::AcqRel) {
1764        on_ready(Err(RenderError::TextureReadback(
1765            ReadbackFailure::DuplicateMapRequest,
1766        )));
1767        return;
1768    }
1769    gpu.map_async(
1770        &buffer.buffer().slice(..),
1771        wgpu::MapMode::Read,
1772        move |result| {
1773            // `BufferAsyncError` names no cause; device diagnostics may explain it.
1774            on_ready(result.map_err(|_| RenderError::TextureReadback(ReadbackFailure::MapFailed)));
1775        },
1776    );
1777}
1778
1779/// Where one plane sits in a mapped readback staging buffer.
1780#[derive(Copy, Clone, Debug, Eq, PartialEq)]
1781pub struct StagingPlane {
1782    /// Byte offset of the plane's first row.
1783    pub offset: u64,
1784    /// Bytes from the start of one row to the start of the next.
1785    pub stride: u32,
1786}
1787
1788fn aligned_copy_row(width: u32) -> Result<u32, RenderError> {
1789    let alignment = wgpu::COPY_BYTES_PER_ROW_ALIGNMENT;
1790    width
1791        .checked_add(alignment - 1)
1792        .map(|value| value / alignment)
1793        .and_then(|rows| rows.checked_mul(alignment))
1794        .ok_or(RenderError::TextureReadback(ReadbackFailure::Layout))
1795}
1796
1797fn yuv420_tight_bytes(size: RenderSize) -> Result<u64, RenderError> {
1798    u64::from(size.width)
1799        .checked_mul(u64::from(size.height))
1800        .and_then(|luma| luma.checked_mul(YUV420_PLANE_COUNT))
1801        .map(|three_planes| three_planes / 2)
1802        .ok_or(RenderError::TextureReadback(ReadbackFailure::Layout))
1803}
1804
1805/// Pack-shader uniforms for `encoding`: luma weights, range levels and chroma co-siting axes,
1806/// from the same definitions import decodes with so a round trip is the identity.
1807const YUV_PACK_UNIFORM_FLOATS: usize = 12;
1808
1809pub(crate) const YUV_PACK_UNIFORM_BYTES: u64 =
1810    crate::uniform::float_uniform_bytes(YUV_PACK_UNIFORM_FLOATS);
1811
1812pub(crate) fn yuv_uniform(encoding: YuvEncoding) -> [f32; YUV_PACK_UNIFORM_FLOATS] {
1813    let YuvEncoding { color, chroma } = encoding;
1814    // Components that are already RGB have no pack: they take BT.709's.
1815    let (kr, kb) = color
1816        .matrix
1817        .luma_weights()
1818        .or(ColorMatrix::Bt709.luma_weights())
1819        .expect("BT.709 is a YCbCr matrix");
1820    let levels = color.range.levels(8);
1821    let (cosited_x, cosited_y) = match chroma {
1822        ChromaLocation::Left => (true, false),
1823        ChromaLocation::TopLeft => (true, true),
1824        ChromaLocation::Unspecified | ChromaLocation::Center => (false, false),
1825    };
1826    [
1827        kr,
1828        1.0 - kr - kb,
1829        kb,
1830        0.0,
1831        levels.luma_black / levels.maximum,
1832        levels.luma_span / levels.maximum,
1833        levels.chroma_center / levels.maximum,
1834        levels.chroma_span / levels.maximum,
1835        f32::from(u8::from(cosited_x)),
1836        f32::from(u8::from(cosited_y)),
1837        0.0,
1838        0.0,
1839    ]
1840}
1841
1842fn yuv_render_pipeline(
1843    device: &wgpu::Device,
1844    layout: &wgpu::PipelineLayout,
1845    shader: &wgpu::ShaderModule,
1846    fragment_entry: &'static str,
1847    target_formats: &[wgpu::TextureFormat],
1848) -> wgpu::RenderPipeline {
1849    let targets = target_formats
1850        .iter()
1851        .copied()
1852        .map(|format| Some(format.into()))
1853        .collect::<Vec<_>>();
1854    device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
1855        label: Some("alpha2 RGB to YUV pipeline"),
1856        layout: Some(layout),
1857        vertex: wgpu::VertexState {
1858            module: shader,
1859            entry_point: Some("vs"),
1860            buffers: &[],
1861            compilation_options: wgpu::PipelineCompilationOptions::default(),
1862        },
1863        fragment: Some(wgpu::FragmentState {
1864            module: shader,
1865            entry_point: Some(fragment_entry),
1866            targets: &targets,
1867            compilation_options: wgpu::PipelineCompilationOptions::default(),
1868        }),
1869        primitive: wgpu::PrimitiveState::default(),
1870        depth_stencil: None,
1871        multisample: wgpu::MultisampleState::default(),
1872        multiview_mask: None,
1873        cache: None,
1874    })
1875}
1876
1877type PackPass<'a> = (
1878    &'static str,
1879    &'a wgpu::RenderPipeline,
1880    &'a [&'a wgpu::TextureView],
1881);
1882
1883fn encode_pack_passes(
1884    encoder: &mut impl PassEncoder,
1885    bind_group: &OffsetBindGroup<1>,
1886    size: RenderSize,
1887    luma: PackPass<'_>,
1888    chroma: PackPass<'_>,
1889) {
1890    let chroma_size = RenderSize {
1891        width: size.width.div_ceil(2),
1892        height: size.height.div_ceil(2),
1893    };
1894    let pass = crate::submission_pilot::PassKind::Pack.key(size.pixels());
1895    for ((label, pipeline, targets), work, size) in [
1896        (luma, pack_luma_work(size), size),
1897        (chroma, pack_chroma_work(size), chroma_size),
1898    ] {
1899        encoder.placed_pass(work, PixelRect::whole(size), pass, |encoder, piece| {
1900            encode_yuv_render_pass(encoder, label, pipeline, bind_group, targets, piece);
1901        });
1902    }
1903}
1904
1905pub(crate) fn pack_luma_work(size: RenderSize) -> crate::FrameCost {
1906    crate::FrameCost::of(PACK_SAMPLE_COST, size.pixels())
1907}
1908
1909pub(crate) fn pack_chroma_work(size: RenderSize) -> crate::FrameCost {
1910    let chroma = u64::from(size.width.div_ceil(2)) * u64::from(size.height.div_ceil(2));
1911    crate::FrameCost::of(PACK_SAMPLE_COST.times(4), chroma)
1912}
1913
1914pub(crate) fn layout_chroma_size(size: RenderSize, layout: PixelLayout) -> RenderSize {
1915    let (step_x, step_y) = layout.chroma.subsampling();
1916    RenderSize {
1917        width: size.width / step_x,
1918        height: size.height / step_y,
1919    }
1920}
1921
1922pub(crate) fn layout_luma_work(size: RenderSize) -> crate::FrameCost {
1923    crate::FrameCost::of(PACK_SAMPLE_COST, size.pixels())
1924}
1925
1926pub(crate) fn layout_chroma_work(size: RenderSize, layout: PixelLayout) -> crate::FrameCost {
1927    let (step_x, step_y) = layout.chroma.subsampling();
1928    crate::FrameCost::of(
1929        PACK_SAMPLE_COST.times(u64::from(step_x * step_y)),
1930        layout_chroma_size(size, layout).pixels(),
1931    )
1932}
1933
1934pub(crate) fn layout_copy_work(size: RenderSize, layout: PixelLayout) -> crate::FrameCost {
1935    let [luma, chroma] = LayoutPackPass::of_layout(layout);
1936    let texels = luma.target_formats().len() as u64 * size.pixels()
1937        + chroma.target_formats().len() as u64 * layout_chroma_size(size, layout).pixels();
1938    crate::FrameCost::of(PACK_SAMPLE_COST, texels)
1939}
1940
1941pub(crate) fn layout_pack_work(size: RenderSize, layout: PixelLayout) -> crate::FrameCost {
1942    let mut work = layout_luma_work(size);
1943    work.add_cost(layout_chroma_work(size, layout));
1944    work.add_cost(layout_copy_work(size, layout));
1945    work
1946}
1947
1948pub(crate) const LAYOUT_PACK_UNIFORM_BYTES: u64 =
1949    (crate::layout_pack::GPU_PARAMS_WORDS * size_of::<u32>()) as u64;
1950
1951const PACK_SAMPLE_COST: crate::effect_cost::EffectCost =
1952    crate::effect_cost::EffectCost::fixed(1, 0);
1953
1954fn encode_yuv_render_pass(
1955    encoder: &mut wgpu::CommandEncoder,
1956    label: &'static str,
1957    pipeline: &wgpu::RenderPipeline,
1958    bind_group: &OffsetBindGroup<1>,
1959    targets: &[&wgpu::TextureView],
1960    Piece { scissor, first }: Piece,
1961) {
1962    let load = if first {
1963        wgpu::LoadOp::Clear(wgpu::Color::BLACK)
1964    } else {
1965        wgpu::LoadOp::Load
1966    };
1967    let attachments = targets
1968        .iter()
1969        .map(|target| {
1970            Some(wgpu::RenderPassColorAttachment {
1971                view: target,
1972                depth_slice: None,
1973                resolve_target: None,
1974                ops: wgpu::Operations {
1975                    load,
1976                    store: wgpu::StoreOp::Store,
1977                },
1978            })
1979        })
1980        .collect::<arrayvec::ArrayVec<_, 2>>();
1981    let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
1982        label: Some(label),
1983        color_attachments: &attachments,
1984        depth_stencil_attachment: None,
1985        timestamp_writes: None,
1986        occlusion_query_set: None,
1987        multiview_mask: None,
1988    });
1989    if let Some(scissor) = scissor {
1990        if scissor.area() == 0 {
1991            return;
1992        }
1993        pass.set_scissor_rect(scissor.x, scissor.y, scissor.width, scissor.height);
1994    }
1995    pass.set_pipeline(pipeline);
1996    bind_group.set(&mut pass, 0);
1997    pass.draw(0..3, 0..1);
1998}
1999
2000fn encode_plane_copy(
2001    encoder: &mut wgpu::CommandEncoder,
2002    texture: &wgpu::Texture,
2003    buffer: &wgpu::Buffer,
2004    offset: u64,
2005    bytes_per_row: u32,
2006    size: RenderSize,
2007) {
2008    encoder.copy_texture_to_buffer(
2009        wgpu::TexelCopyTextureInfo {
2010            texture,
2011            mip_level: 0,
2012            origin: wgpu::Origin3d::ZERO,
2013            aspect: wgpu::TextureAspect::All,
2014        },
2015        wgpu::TexelCopyBufferInfo {
2016            buffer,
2017            layout: wgpu::TexelCopyBufferLayout {
2018                offset,
2019                bytes_per_row: Some(bytes_per_row),
2020                rows_per_image: Some(size.height),
2021            },
2022        },
2023        wgpu::Extent3d {
2024            width: size.width,
2025            height: size.height,
2026            depth_or_array_layers: 1,
2027        },
2028    );
2029}
2030
2031#[cfg(test)]
2032pub(crate) fn read_rgba8(renderer: &Renderer, target: &RenderedTexture) -> Vec<u8> {
2033    renderer
2034        .read_rgba8(target)
2035        .expect("test texture readback succeeds")
2036}
2037
2038#[cfg(test)]
2039#[path = "readback_tests.rs"]
2040mod layout_tests;