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        PixelFormat::Rgba8 => {
88            if frame.planes.len() != 1 {
89                return Err("an RGBA frame must contain one plane".into());
90            }
91            renderer
92                .prepare_rgba8_presented(plane(frame, 0), coded, presentation)
93                .map_err(|error| error.to_string())?
94        }
95        PixelFormat::LinearRgbaF16 => {
96            if frame.planes.len() != 1 {
97                return Err("a linear RGBA frame must contain one plane".into());
98            }
99            let upload = renderer
100                .write_linear_rgba16f(coded, plane(frame, 0))
101                .map_err(|error| error.to_string())?;
102            renderer
103                .prepare_linear_presented(upload, coded, presentation)
104                .map_err(|error| error.to_string())?
105        }
106        other => return Err(format!("the decoder returned {other:?}")),
107    };
108    Ok(gpu_source(prepared, size))
109}
110
111fn gpu_source(prepared: PreparedSourceTexture, size: RenderSize) -> GpuSource {
112    let (presented, pending) = prepared.into_parts();
113    let view = presented.view().clone();
114    let bytes = u64::from(size.width) * u64::from(size.height) * 8;
115    GpuSource {
116        _texture: presented,
117        view,
118        pending,
119        bytes,
120    }
121}
122
123/// Prepares a frame whose planes are already GPU textures, drawn at `size`; `lease` keeps what
124/// the planes need until the renderer's work on them completes.
125///
126/// # Errors
127/// An HDR frame the color policy refuses, planes that do not match their format, or a renderer
128/// failure.
129pub fn prepare_gpu_planes(
130    renderer: &Renderer,
131    size: RenderSize,
132    color: ColorPolicy,
133    facts: &FrameFacts,
134    planes: GpuVideoPlanes<'_>,
135    lease: Arc<dyn ExternalTextureLease>,
136) -> Result<GpuSource, String> {
137    refuse_hdr(color, planes.color)?;
138    let presentation = SourcePresentation {
139        output_size: size,
140        visible_rect: facts.visible_rect,
141        orientation: facts.orientation,
142        sample_aspect_ratio: (facts.sample_aspect_ratio.num, facts.sample_aspect_ratio.den),
143        chroma_siting: facts.chroma_location,
144    };
145    let (prepared, diagnostics) = renderer
146        .prepare_gpu_yuv_presented(planes, presentation, color, lease)
147        .map_err(|error| error.to_string())?;
148    if skipped_hdr(&diagnostics) {
149        return Err("the project skips HDR sources".into());
150    }
151    Ok(gpu_source(prepared, size))
152}
153
154/// Turns a platform decoder's surfaces into GPU sources: the GPU renderer's path for frames that
155/// stay on the GPU, made by the platform that decodes them.
156pub trait SurfaceImport: Send + Sync {
157    /// The surface `lease` of a frame with `facts`, prepared for `renderer` at `size`.
158    ///
159    /// # Errors
160    /// A surface of another platform, a failed import, or an error of [`prepare_gpu_planes`].
161    fn prepare(
162        &self,
163        renderer: &Renderer,
164        size: RenderSize,
165        color: ColorPolicy,
166        facts: &FrameFacts,
167        lease: &Arc<dyn SurfaceLease>,
168    ) -> Result<GpuSource, String>;
169
170    /// Lets go of the surfaces whose preparation finished, without waiting; work that stops
171    /// importing calls it so finished frames do not wait for the next import. The default does
172    /// nothing.
173    fn collect(&self) {}
174}