Skip to main content

alpha2_host_core/export/
prepare.rs

1//! Decoded frames made ready for the renderer: GPU textures, or CPU sources lending the planes.
2
3use std::sync::Arc;
4
5use alpha2_engine::frame_store::StoredFrame;
6use alpha2_media::{DecodedVideoFrame, PixelFormat};
7pub use alpha2_render::decoded::present_decoded as prepare_cpu;
8use alpha2_render::decoded::{
9    coded_size, plane, presentation, refuse_hdr, skipped_hdr, yuv_source,
10};
11use alpha2_render::{
12    ColorPolicy, ExternalTextureLease, GpuVideoPlanes, PendingSourceWork, PreparedSourceTexture,
13    RenderSize, RenderedTexture, Renderer, SourcePresentation, SourceView,
14};
15
16use crate::video_stream::{FrameFacts, SurfaceLease};
17
18/// A source picture on the GPU, with the work it still waits on before it may be sampled.
19pub struct GpuSource {
20    _texture: RenderedTexture,
21    view: wgpu::TextureView,
22    pending: Option<PendingSourceWork>,
23    bytes: u64,
24}
25
26impl std::fmt::Debug for GpuSource {
27    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
28        formatter
29            .debug_struct("GpuSource")
30            .field("bytes", &self.bytes)
31            .finish_non_exhaustive()
32    }
33}
34
35impl GpuSource {
36    /// Bytes the picture and its pending work keep alive.
37    #[must_use]
38    pub fn retained_bytes(&self) -> u64 {
39        self.bytes.saturating_add(
40            self.pending
41                .as_ref()
42                .map_or(0, PendingSourceWork::retained_bytes),
43        )
44    }
45}
46
47impl StoredFrame for GpuSource {
48    fn view(&self) -> SourceView<'_> {
49        SourceView::from_wgpu(&self.view)
50    }
51
52    fn pending_work(&self) -> Option<&PendingSourceWork> {
53        self.pending.as_ref()
54    }
55}
56
57/// Uploads a decoded frame for the GPU renderer, drawn at `size`.
58///
59/// # Errors
60/// An HDR frame the color policy refuses, a plane count that does not match the pixel format,
61/// an unsupported format, or a renderer failure.
62pub fn prepare_gpu(
63    renderer: &Renderer,
64    size: RenderSize,
65    color: ColorPolicy,
66    frame: &DecodedVideoFrame,
67) -> Result<GpuSource, String> {
68    refuse_hdr(color, frame.color)?;
69    let coded = coded_size(frame)?;
70    let presentation = presentation(frame, size);
71    let prepared = match frame.pixel_format {
72        PixelFormat::Yuv(format) => {
73            if frame.planes.len() != format.plane_count() {
74                return Err(format!(
75                    "a YUV frame must contain {} planes",
76                    format.plane_count()
77                ));
78            }
79            let (prepared, diagnostics) = renderer
80                .prepare_yuv_presented(yuv_source(frame, format, coded), presentation, color)
81                .map_err(|error| error.to_string())?;
82            if skipped_hdr(&diagnostics) {
83                return Err("the project skips HDR sources".into());
84            }
85            prepared
86        }
87        format @ (PixelFormat::Rgba8 | PixelFormat::Rgba8Premultiplied) => {
88            if frame.planes.len() != 1 {
89                return Err("an RGBA frame must contain one plane".into());
90            }
91            let alpha = if format == PixelFormat::Rgba8Premultiplied {
92                alpha2_render::SourceAlpha::Premultiplied
93            } else {
94                alpha2_render::SourceAlpha::Straight
95            };
96            renderer
97                .prepare_rgba8_presented(plane(frame, 0), coded, presentation, alpha)
98                .map_err(|error| error.to_string())?
99        }
100        PixelFormat::LinearRgbaF16 => {
101            if frame.planes.len() != 1 {
102                return Err("a linear RGBA frame must contain one plane".into());
103            }
104            let upload = renderer
105                .write_linear_rgba16f(coded, plane(frame, 0))
106                .map_err(|error| error.to_string())?;
107            renderer
108                .prepare_linear_presented(upload, coded, presentation)
109                .map_err(|error| error.to_string())?
110        }
111        other => return Err(format!("the decoder returned {other:?}")),
112    };
113    Ok(gpu_source(prepared, size))
114}
115
116fn gpu_source(prepared: PreparedSourceTexture, size: RenderSize) -> GpuSource {
117    let (presented, pending) = prepared.into_parts();
118    let view = presented.view().clone();
119    let bytes = u64::from(size.width) * u64::from(size.height) * 8;
120    GpuSource {
121        _texture: presented,
122        view,
123        pending,
124        bytes,
125    }
126}
127
128/// Prepares a frame whose planes are already GPU textures, drawn at `size`; `lease` keeps what
129/// the planes need until the renderer's work on them completes.
130///
131/// # Errors
132/// An HDR frame the color policy refuses, planes that do not match their format, or a renderer
133/// failure.
134pub fn prepare_gpu_planes(
135    renderer: &Renderer,
136    size: RenderSize,
137    color: ColorPolicy,
138    facts: &FrameFacts,
139    planes: GpuVideoPlanes<'_>,
140    lease: Arc<dyn ExternalTextureLease>,
141) -> Result<GpuSource, String> {
142    refuse_hdr(color, planes.color)?;
143    let presentation = SourcePresentation {
144        output_size: size,
145        visible_rect: facts.visible_rect,
146        orientation: facts.orientation,
147        sample_aspect_ratio: (facts.sample_aspect_ratio.num, facts.sample_aspect_ratio.den),
148        chroma_siting: facts.chroma_location,
149    };
150    let (prepared, diagnostics) = renderer
151        .prepare_gpu_yuv_presented(planes, presentation, color, lease, None)
152        .map_err(|error| error.to_string())?;
153    if skipped_hdr(&diagnostics) {
154        return Err("the project skips HDR sources".into());
155    }
156    Ok(gpu_source(prepared, size))
157}
158
159/// Turns a platform decoder's surfaces into GPU sources: the GPU renderer's path for frames that
160/// stay on the GPU, made by the platform that decodes them.
161pub trait SurfaceImport: Send + Sync {
162    /// The surface `lease` of a frame with `facts`, prepared for `renderer` at `size`.
163    ///
164    /// # Errors
165    /// A surface of another platform, a failed import, or an error of [`prepare_gpu_planes`].
166    fn prepare(
167        &self,
168        renderer: &Renderer,
169        size: RenderSize,
170        color: ColorPolicy,
171        facts: &FrameFacts,
172        lease: &Arc<dyn SurfaceLease>,
173    ) -> Result<GpuSource, String>;
174
175    /// Lets go of the surfaces whose preparation finished, without waiting; work that stops
176    /// importing calls it so finished frames do not wait for the next import. The default does
177    /// nothing.
178    fn collect(&self) {}
179}