Skip to main content

alpha2_engine/extract/
pixels.rs

1//! The delivered frame size, its presentation on the CPU renderer and the `luma8` conversion,
2//! computed alike on every surface.
3
4use std::sync::Arc;
5
6use alpha2_media::DecodedVideoFrame;
7use alpha2_render::{
8    BlendMode, ColorPolicy, CpuRenderer, GraphLayer, LayerTransform, RenderGraph, RenderSize,
9    SourceView,
10};
11
12use super::{FramePlace, SuppliedFrame};
13
14/// The size a frame of displayed size `(width, height)` is delivered at for a request `size`:
15/// contain-fit so the long edge is at most `size`, never upscaled, each edge rounded half up and
16/// at least one pixel.
17#[must_use]
18pub fn delivered_size(displayed: (u32, u32), size: u32) -> (u32, u32) {
19    let (width, height) = displayed;
20    let long = width.max(height);
21    if long == 0 || long <= size {
22        return (width.max(1), height.max(1));
23    }
24    // floor(edge * size / long + 1/2) in integers: (2 * edge * size + long) / (2 * long).
25    let edge = |value: u32| {
26        let scaled =
27            (2 * u64::from(value) * u64::from(size) + u64::from(long)) / (2 * u64::from(long));
28        u32::try_from(scaled).unwrap_or(u32::MAX).max(1)
29    };
30    (edge(width), edge(height))
31}
32
33/// BT.709 Y' of straight-alpha sRGB-encoded RGBA8 pixels, rounded half up; alpha is ignored.
34#[must_use]
35pub fn luma8_from_rgba8(rgba: &[u8]) -> Vec<u8> {
36    rgba.as_chunks::<4>()
37        .0
38        .iter()
39        .map(|pixel| luma(*pixel))
40        .collect()
41}
42
43pub(crate) fn luma8_into(rgba: &[u8], out: &mut [u8]) {
44    for (to, pixel) in out.iter_mut().zip(rgba.as_chunks::<4>().0) {
45        *to = luma(*pixel);
46    }
47}
48
49fn luma(pixel: [u8; 4]) -> u8 {
50    let weighted =
51        2_126 * u32::from(pixel[0]) + 7_152 * u32::from(pixel[1]) + 722 * u32::from(pixel[2]);
52    u8::try_from((weighted + 5_000) / 10_000).unwrap_or(u8::MAX)
53}
54
55/// The mixer's mono fold of `planes`, whose speakers are `speakers`. Each plane is weighted by the
56/// mean of its stereo weights and summed in plane order. `None` for no planes or too many.
57#[must_use]
58pub fn mono_downmix(speakers: &[alpha2_media::Speaker], planes: &[Vec<f32>]) -> Option<Vec<f32>> {
59    let mix = crate::downmix::Downmix::new(speakers, alpha2_audio::ChannelLayout::Mono)?;
60    let frames = planes.first().map_or(0, Vec::len);
61    let mut out = vec![0.0_f32; frames];
62    for (plane, weight) in mix.channel(0).terms() {
63        let samples = planes.get(*plane)?;
64        for (sample, value) in out.iter_mut().zip(samples) {
65            *sample += value * weight;
66        }
67    }
68    Some(out)
69}
70
71/// The displayed size of a decoded frame, its visible rectangle widened by the pixel aspect ratio
72/// (rounded half up) and turned upright.
73#[must_use]
74pub fn displayed_size(frame: &DecodedVideoFrame) -> (u32, u32) {
75    let sar = frame.sample_aspect_ratio;
76    let (num, den) = (u64::from(sar.num.max(1)), u64::from(sar.den.max(1)));
77    let width = (2 * u64::from(frame.visible_rect.width) * num + den) / (2 * den);
78    let width = u32::try_from(width).unwrap_or(u32::MAX).max(1);
79    let height = frame.visible_rect.height.max(1);
80    if frame.orientation.rotation.swaps_axes() {
81        (height, width)
82    } else {
83        (width, height)
84    }
85}
86
87/// A decoded frame presented on the CPU renderer as an extraction delivery: display-oriented,
88/// contain-fit to at most `size` on the long edge, straight-alpha sRGB RGBA8. HDR is tone-mapped
89/// with the default tone map.
90///
91/// # Errors
92/// A frame the renderer cannot present.
93pub fn present_for_extraction(
94    renderer: &CpuRenderer,
95    frame: Arc<DecodedVideoFrame>,
96    size: u32,
97) -> Result<SuppliedFrame, String> {
98    present(renderer, frame, size, None)
99}
100
101/// [`present_for_extraction`], writing the pixels into the memory `place` gives when it gives
102/// some; the returned frame's `rgba` is then empty.
103///
104/// # Errors
105/// A frame the renderer cannot present.
106pub fn present_for_extraction_into(
107    renderer: &CpuRenderer,
108    frame: Arc<DecodedVideoFrame>,
109    size: u32,
110    place: &mut FramePlace<'_>,
111) -> Result<SuppliedFrame, String> {
112    present(renderer, frame, size, Some(place))
113}
114
115fn present(
116    renderer: &CpuRenderer,
117    frame: Arc<DecodedVideoFrame>,
118    size: u32,
119    place: Option<&mut FramePlace<'_>>,
120) -> Result<SuppliedFrame, String> {
121    let (width, height) = delivered_size(displayed_size(&frame), size);
122    let target = RenderSize::new(width, height).map_err(|error| error.to_string())?;
123    let pts = frame.pts;
124    let source = alpha2_render::decoded::present_decoded(
125        renderer,
126        target,
127        ColorPolicy::ToneMapHdr(alpha2_render::hdr::HdrToneMap::default()),
128        frame,
129    )?;
130    let mut graph = RenderGraph::new(target);
131    let node = graph.add_source(SourceView::from(&source));
132    let output = graph
133        .add_composite(vec![GraphLayer {
134            source: node,
135            visual: LayerTransform {
136                position: [0.5, 0.5],
137                anchor: [0.5, 0.5],
138                scale: [1.0, 1.0],
139                rotation_degrees: 0.0,
140                opacity: 1.0,
141            },
142            blend_mode: BlendMode::Normal,
143        }])
144        .map_err(|error| error.to_string())?;
145    graph
146        .set_output(output)
147        .map_err(|error| error.to_string())?;
148    let image = renderer
149        .execute_graph(&graph)
150        .map_err(|error| error.to_string())?;
151    let premultiplied = image.read_rgba8();
152    let placed = place.and_then(|place| place.buffer(premultiplied.len()));
153    let rgba = if let Some(buffer) = placed {
154        for (to, from) in buffer
155            .as_chunks_mut::<4>()
156            .0
157            .iter_mut()
158            .zip(premultiplied.as_chunks::<4>().0)
159        {
160            *to = unpremultiplied(*from);
161        }
162        Vec::new()
163    } else {
164        let mut rgba = premultiplied;
165        for pixel in rgba.as_chunks_mut::<4>().0 {
166            *pixel = unpremultiplied(*pixel);
167        }
168        rgba
169    };
170    Ok(SuppliedFrame {
171        pts,
172        width,
173        height,
174        rgba,
175    })
176}
177
178/// Straight alpha from premultiplied RGBA8, rounded half up.
179fn unpremultiplied(mut pixel: [u8; 4]) -> [u8; 4] {
180    let alpha = u32::from(pixel[3]);
181    if alpha == 0 {
182        pixel[..3].fill(0);
183    } else if alpha < 255 {
184        for channel in &mut pixel[..3] {
185            *channel =
186                u8::try_from(((u32::from(*channel) * 255 * 2 + alpha) / (2 * alpha)).min(255))
187                    .unwrap_or(u8::MAX);
188        }
189    }
190    pixel
191}