Skip to main content

velox_engine/
media.rs

1//! 零拷贝视频帧表面(`VideoSurface`)与原生 WebView 宿主裁剪同步模型(`WebViewHostSync`)。
2//!
3//! 全模块核心保持 100% `#![no_std]` 零堆兼容:
4//! - **GPU 零拷贝视频通道**:直接复用 [`crate::paint::ExternalTextureId`],外部硬件解码器(MediaFoundation /
5//!   VideoToolbox / VA-API / MediaCodec)产出的 GPU 纹理零拷贝直出合成;
6//! - **CPU YUV 回退转换**:内置定点 BT.709 `convert_nv12_to_rgba8` 与 `convert_i420_to_rgba8`,在无硬件直出纹理时
7//!   极速转码为 RGBA8 供双后端统一显示;
8//! - **原生 WebView 宿主同步**:[`WebViewHostSync`] 每帧基于布局结果做几何 Diff,仅当位置/尺寸/裁剪/可见性变化时
9//!   产出 [`WebViewHostUpdate`],供 Windows WebView2 / macOS WKWebView / Linux WebKitGTK 零闪烁洞穿跟随。
10
11use crate::image_pipeline::ObjectFit;
12use crate::paint::ExternalTextureId;
13use crate::solver::Region;
14
15/// 视频帧像素格式。
16#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
17pub enum VideoPixelFormat {
18    /// 半平面 YUV 4:2:0(Y 平面 + 交错 UV 平面,硬件解码器最常用格式)。
19    Nv12,
20    /// 三平面 YUV 4:2:0(Y + U + V 独立平面)。
21    I420,
22    /// 交错 RGBA8888。
23    Rgba8,
24    /// 交错 BGRA8888。
25    Bgra8,
26}
27
28/// 零拷贝视频帧表面规格(同时兼容 GPU 外部纹理句柄与软件转码尺寸描述)。
29#[derive(Copy, Clone, PartialEq, Eq, Debug)]
30pub struct VideoSurfaceSpec {
31    pub texture_id: Option<ExternalTextureId>,
32    pub video_width: u32,
33    pub video_height: u32,
34    pub format: VideoPixelFormat,
35    pub fit: ObjectFit,
36    pub rounded: u8,
37    pub opacity: u8,
38}
39
40impl VideoSurfaceSpec {
41    #[inline(always)]
42    pub const fn new(video_width: u32, video_height: u32, format: VideoPixelFormat) -> Self {
43        Self {
44            texture_id: None,
45            video_width,
46            video_height,
47            format,
48            fit: ObjectFit::Contain,
49            rounded: 8,
50            opacity: 255,
51        }
52    }
53
54    #[inline(always)]
55    pub const fn external_texture(mut self, id: ExternalTextureId) -> Self {
56        self.texture_id = Some(id);
57        self
58    }
59
60    #[inline(always)]
61    pub const fn fit(mut self, fit: ObjectFit) -> Self {
62        self.fit = fit;
63        self
64    }
65
66    #[inline(always)]
67    pub const fn rounded(mut self, r: u8) -> Self {
68        self.rounded = r;
69        self
70    }
71}
72
73#[inline(always)]
74fn yuv_to_rgb_bt709(y: u8, u: u8, v: u8) -> (u8, u8, u8) {
75    let c = (y as i32 - 16).max(0);
76    let d = u as i32 - 128;
77    let e = v as i32 - 128;
78    let r = (298 * c + 459 * e + 128) >> 8;
79    let g = (298 * c - 55 * d - 136 * e + 128) >> 8;
80    let b = (298 * c + 541 * d + 128) >> 8;
81    (
82        r.clamp(0, 255) as u8,
83        g.clamp(0, 255) as u8,
84        b.clamp(0, 255) as u8,
85    )
86}
87
88/// BT.709 定点快速转换 NV12(Y 平面 + 交错 UV 平面)至 RGBA8888。
89/// 返回成功写入的像素数(`width * height`);输入/输出缓冲区尺寸不足时返回 `0`。
90pub fn convert_nv12_to_rgba8(
91    y_plane: &[u8],
92    uv_plane: &[u8],
93    width: usize,
94    height: usize,
95    out_rgba: &mut [u8],
96) -> usize {
97    let pixels = width.saturating_mul(height);
98    let uv_w = (width + 1) / 2;
99    let uv_h = (height + 1) / 2;
100    if pixels == 0
101        || y_plane.len() < pixels
102        || uv_plane.len() < uv_w.saturating_mul(uv_h).saturating_mul(2)
103        || out_rgba.len() < pixels.saturating_mul(4)
104    {
105        return 0;
106    }
107    for row in 0..height {
108        let y_row = row * width;
109        let uv_row = (row >> 1) * uv_w * 2;
110        let out_row = row * width * 4;
111        for col in 0..width {
112            let y = y_plane[y_row + col];
113            let uv_idx = uv_row + (col >> 1) * 2;
114            let u = uv_plane[uv_idx];
115            let v = uv_plane[uv_idx + 1];
116            let (r, g, b) = yuv_to_rgb_bt709(y, u, v);
117            let o = out_row + col * 4;
118            out_rgba[o] = r;
119            out_rgba[o + 1] = g;
120            out_rgba[o + 2] = b;
121            out_rgba[o + 3] = 255;
122        }
123    }
124    pixels
125}
126
127/// BT.709 定点快速转换 I420(Y + U + V 三平面)至 RGBA8888。
128pub fn convert_i420_to_rgba8(
129    y_plane: &[u8],
130    u_plane: &[u8],
131    v_plane: &[u8],
132    width: usize,
133    height: usize,
134    out_rgba: &mut [u8],
135) -> usize {
136    let pixels = width.saturating_mul(height);
137    let cw = (width + 1) / 2;
138    let ch = (height + 1) / 2;
139    let c_len = cw.saturating_mul(ch);
140    if pixels == 0
141        || y_plane.len() < pixels
142        || u_plane.len() < c_len
143        || v_plane.len() < c_len
144        || out_rgba.len() < pixels.saturating_mul(4)
145    {
146        return 0;
147    }
148    for row in 0..height {
149        let y_row = row * width;
150        let c_row = (row >> 1) * cw;
151        let out_row = row * width * 4;
152        for col in 0..width {
153            let y = y_plane[y_row + col];
154            let c_idx = c_row + (col >> 1);
155            let (r, g, b) = yuv_to_rgb_bt709(y, u_plane[c_idx], v_plane[c_idx]);
156            let o = out_row + col * 4;
157            out_rgba[o] = r;
158            out_rgba[o + 1] = g;
159            out_rgba[o + 2] = b;
160            out_rgba[o + 3] = 255;
161        }
162    }
163    pixels
164}
165
166/// 原生子窗口 WebView 宿主区域描述(供 WebView2 / WKWebView / WebKitGTK 洞穿定位)。
167#[derive(Copy, Clone, PartialEq, Eq, Debug, Default)]
168pub struct WebViewHostRegion {
169    pub id: u32,
170    pub logical_bounds: Region,
171    pub clip_bounds: Region,
172    pub visible: bool,
173    pub z_order: i16,
174}
175
176impl WebViewHostRegion {
177    /// 计算裁剪后的有效逻辑可见框。
178    #[inline]
179    pub fn effective_bounds(&self) -> Region {
180        if !self.visible {
181            return Region::EMPTY;
182        }
183        self.logical_bounds.intersect(self.clip_bounds)
184    }
185
186    /// 换算为物理像素矩形 `(x, y, w, h)`(适配分数 HiDPI 缩放)。
187    #[inline]
188    pub fn physical_rect(&self, scale_factor: f32) -> (i32, i32, u32, u32) {
189        let eff = self.effective_bounds();
190        if eff.is_empty() {
191            return (0, 0, 0, 0);
192        }
193        let sf = scale_factor.clamp(0.5, 4.0);
194        let x = ((eff.x as f32) * sf) as i32;
195        let y = ((eff.y as f32) * sf) as i32;
196        let w = ((eff.w.max(0) as f32) * sf) as u32;
197        let h = ((eff.h.max(0) as f32) * sf) as u32;
198        (x, y, w, h)
199    }
200}
201
202/// 单帧 WebView 宿主几何变更通知(零冗余 IPC 同步)。
203#[derive(Copy, Clone, PartialEq, Eq, Debug)]
204pub struct WebViewHostUpdate {
205    pub id: u32,
206    pub physical_rect: (i32, i32, u32, u32),
207    pub visible: bool,
208    pub z_order: i16,
209}
210
211/// 跨帧 WebView 宿主裁剪同步器(最多追踪 8 个嵌入式 WebView,静息帧 0 同步开销)。
212#[derive(Clone, Debug, Default)]
213pub struct WebViewHostSync {
214    last: [Option<WebViewHostUpdate>; 8],
215}
216
217impl WebViewHostSync {
218    #[inline(always)]
219    pub const fn new() -> Self {
220        Self { last: [None; 8] }
221    }
222
223    /// 对比本帧布局算出的 [`WebViewHostRegion`];仅当物理坐标、可见性或 Z 序发生变化时返回 `Some(update)`。
224    pub fn diff_region(
225        &mut self,
226        region: WebViewHostRegion,
227        scale_factor: f32,
228    ) -> Option<WebViewHostUpdate> {
229        let phys = region.physical_rect(scale_factor);
230        let vis = region.visible && phys.2 > 0 && phys.3 > 0;
231        let next = WebViewHostUpdate {
232            id: region.id,
233            physical_rect: phys,
234            visible: vis,
235            z_order: region.z_order,
236        };
237        for slot in &mut self.last {
238            if let Some(prev) = slot {
239                if prev.id == region.id {
240                    if *prev == next {
241                        return None;
242                    }
243                    *prev = next;
244                    return Some(next);
245                }
246            }
247        }
248        for slot in &mut self.last {
249            if slot.is_none() {
250                *slot = Some(next);
251                return Some(next);
252            }
253        }
254        Some(next)
255    }
256}