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::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| {
40            let weighted = 2_126 * u32::from(pixel[0])
41                + 7_152 * u32::from(pixel[1])
42                + 722 * u32::from(pixel[2]);
43            u8::try_from((weighted + 5_000) / 10_000).unwrap_or(u8::MAX)
44        })
45        .collect()
46}
47
48/// The mixer's mono fold of `planes`, whose speakers are `speakers`. Each plane is weighted by the
49/// mean of its stereo weights and summed in plane order. `None` for no planes or too many.
50#[must_use]
51pub fn mono_downmix(speakers: &[alpha2_media::Speaker], planes: &[Vec<f32>]) -> Option<Vec<f32>> {
52    let mix = crate::downmix::Downmix::new(speakers, alpha2_audio::ChannelLayout::Mono)?;
53    let frames = planes.first().map_or(0, Vec::len);
54    let mut out = vec![0.0_f32; frames];
55    for (plane, weight) in mix.channel(0).terms() {
56        let samples = planes.get(*plane)?;
57        for (sample, value) in out.iter_mut().zip(samples) {
58            *sample += value * weight;
59        }
60    }
61    Some(out)
62}
63
64/// The displayed size of a decoded frame, its visible rectangle widened by the pixel aspect ratio
65/// (rounded half up) and turned upright.
66#[must_use]
67pub fn displayed_size(frame: &DecodedVideoFrame) -> (u32, u32) {
68    let sar = frame.sample_aspect_ratio;
69    let (num, den) = (u64::from(sar.num.max(1)), u64::from(sar.den.max(1)));
70    let width = (2 * u64::from(frame.visible_rect.width) * num + den) / (2 * den);
71    let width = u32::try_from(width).unwrap_or(u32::MAX).max(1);
72    let height = frame.visible_rect.height.max(1);
73    if frame.orientation.rotation.swaps_axes() {
74        (height, width)
75    } else {
76        (width, height)
77    }
78}
79
80/// A decoded frame presented on the CPU renderer as an extraction delivery: display-oriented,
81/// contain-fit to at most `size` on the long edge, straight-alpha sRGB RGBA8. HDR is tone-mapped
82/// with the default tone map.
83///
84/// # Errors
85/// A frame the renderer cannot present.
86pub fn present_for_extraction(
87    renderer: &CpuRenderer,
88    frame: Arc<DecodedVideoFrame>,
89    size: u32,
90) -> Result<SuppliedFrame, String> {
91    let (width, height) = delivered_size(displayed_size(&frame), size);
92    let target = RenderSize::new(width, height).map_err(|error| error.to_string())?;
93    let pts = frame.pts;
94    let source = alpha2_render::decoded::present_decoded(
95        renderer,
96        target,
97        ColorPolicy::ToneMapHdr(alpha2_render::hdr::HdrToneMap::default()),
98        frame,
99    )?;
100    let mut graph = RenderGraph::new(target);
101    let node = graph.add_source(SourceView::from(&source));
102    let output = graph
103        .add_composite(vec![GraphLayer {
104            source: node,
105            visual: LayerTransform {
106                position: [0.5, 0.5],
107                anchor: [0.5, 0.5],
108                scale: [1.0, 1.0],
109                rotation_degrees: 0.0,
110                opacity: 1.0,
111            },
112            blend_mode: BlendMode::Normal,
113        }])
114        .map_err(|error| error.to_string())?;
115    graph
116        .set_output(output)
117        .map_err(|error| error.to_string())?;
118    let image = renderer
119        .execute_graph(&graph)
120        .map_err(|error| error.to_string())?;
121    Ok(SuppliedFrame {
122        pts,
123        width,
124        height,
125        rgba: unpremultiply(image.read_rgba8()),
126    })
127}
128
129/// Straight alpha from premultiplied RGBA8, rounded half up.
130fn unpremultiply(mut rgba: Vec<u8>) -> Vec<u8> {
131    for pixel in rgba.as_chunks_mut::<4>().0 {
132        let alpha = u32::from(pixel[3]);
133        if alpha == 0 {
134            pixel[..3].fill(0);
135        } else if alpha < 255 {
136            for channel in &mut pixel[..3] {
137                *channel =
138                    u8::try_from(((u32::from(*channel) * 255 * 2 + alpha) / (2 * alpha)).min(255))
139                        .unwrap_or(u8::MAX);
140            }
141        }
142    }
143    rgba
144}