feat(awareness): add WGC frame quality probe
这个提交存在于:
父节点
dfc26aa37e
当前提交
48599db6d4
共有 8 个文件被更改,包括 365 次插入 和 6 次删除
|
|
@ -11,6 +11,7 @@ The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and
|
|||
- Separate companion navigation for text chat, voice chat, and game companion. The game surface remains explicitly unavailable until Windows.Graphics.Capture has validated real DirectX/Vulkan frames.
|
||||
- Screen-awareness implementation framework for scoped display consent, WGC capture, local privacy/quality gates, multimodal AstrBot validation, and low-interruption response control.
|
||||
- WGC S0.1 target-binding preflight for authorized windows and attached displays. It returns metadata only; no capture session, pixels, disk write, or upload is performed.
|
||||
- Bounded WGC S0.2 diagnostic readback for an already authorized window: one in-memory D3D11 frame, local blank-frame classification, and discarded PNG conversion metadata only.
|
||||
- Debug-level tracing of AstrBot SSE frame shapes: frame type, which identity fields are present, and the key names inside `data`. No payload text is recorded. Enable with `RUST_LOG`.
|
||||
- Q10-Q15 chat experience increment: lightweight Markdown rendering, message actions, generation controls, session actions, connection controls, and responsive chat layout.
|
||||
- AstrBot OpenAPI adapter foundation: SSE mapper, dual-slot runtime skeleton, credential enrollment IPC, transport-aware profiles (ADR-0005).
|
||||
|
|
|
|||
|
|
@ -243,6 +243,15 @@ The following are deliberately not marked complete: HTTPS certificate pinning, s
|
|||
|
||||
验收:隔离目标目录执行 `cargo check -p astrbot-desktop --lib` 通过;`cargo test -p astrbot-desktop --lib` 为 117 passed。
|
||||
|
||||
|
||||
### S0.2:WGC 单帧 D3D11 质量诊断(2026-07-27,代码完成;人工证据未完成)
|
||||
|
||||
- 对已授权窗口新增一个仅诊断的一帧路径:硬件 D3D11 + free-threaded WGC frame pool + staging texture readback,最长等待 2 秒。
|
||||
- 仅在 Rust 内存中将 BGRA 按行距转换为 RGBA,执行 1600 万像素上限、坏行距、黑帧/透明帧检测,并通过 PNG 编码验证转换;返回的 Tauri 元数据不包含图像字节。
|
||||
- 不创建设置入口、不接入调度、不扩展显示器授权、不持久化原始画面,也不向 AstrBot 发送任何数据。
|
||||
|
||||
验收:隔离 Rust check、121 个库测试和 Clippy 均通过。仍缺少实际窗口/游戏、最小化、锁屏、受保护内容、显示器变化的人工证据,故 S0 整体未完成。
|
||||
|
||||
### C1:聊天、语音聊天、游戏陪玩三页面壳
|
||||
|
||||
- 在现有“聊天”之后增加“语音聊天”“游戏陪玩”两个独立导航入口。
|
||||
|
|
|
|||
|
|
@ -771,3 +771,16 @@ This increment does **not** create a `GraphicsCaptureSession`, read a frame, enc
|
|||
- Isolated Rust check: passed (`cargo check -p astrbot-desktop --lib`).
|
||||
- Isolated Rust library tests: 117 passed, 0 failed.
|
||||
- Frontend gates remain to be re-run before this increment is committed.
|
||||
|
||||
|
||||
## 2026-07-27: WGC S0.2 one-frame quality diagnostic
|
||||
|
||||
Added a Rust-only, manually invokable diagnostic command for one frame from an already authorized window. It creates a hardware D3D11 device, uses a free-threaded WGC frame pool, copies the frame through a staging texture, converts BGRA rows to RGBA, detects blank/transparent output, and validates an in-memory PNG encoding. Only dimensions, encoded size and a quality category cross the command boundary; image bytes are discarded.
|
||||
|
||||
This is not a user-facing capture feature and has no scheduler, settings UI, display scope authorization, persistence or AstrBot path. Manual evidence for actual games, minimized targets, lock screens, protected content and display changes is still absent, so S0 remains open.
|
||||
|
||||
### Test status
|
||||
|
||||
- Isolated Rust check: passed.
|
||||
- Isolated Rust library tests: 121 passed, 0 failed.
|
||||
- Isolated Rust Clippy with warnings denied: passed.
|
||||
|
|
|
|||
|
|
@ -26,3 +26,16 @@ The isolated target is required in this workspace because the default Cargo targ
|
|||
S0.1 provides no proof that WGC returns useful pixels. It does not validate DirectX/Vulkan games, minimized targets, display topology changes, lock screens, protected content, sensitive-application filtering, quality thresholds, or AstrBot visual understanding.
|
||||
|
||||
S0.2 must create a bounded D3D11 WGC frame path, copy one frame to a staging texture, convert BGRA to RGBA, detect black/transparent/empty results, and record manual Windows evidence before any screen frame can progress to a local privacy or network path.
|
||||
|
||||
## S0.2 implementation status
|
||||
|
||||
Implemented a bounded one-frame diagnostic path for an already authorized window:
|
||||
|
||||
- Creates a hardware D3D11 device with BGRA support, wraps it as a WinRT `IDirect3DDevice`, and uses a free-threaded WGC frame pool with one buffer and a bounded `FrameArrived` event wait.
|
||||
- Waits for one frame for at most two seconds, copies the source texture to a CPU-readable staging texture, strips row padding, and converts BGRA to RGBA.
|
||||
- Applies a 16 megapixel ceiling, rejects malformed mapped rows, samples alpha/luminance to classify black or transparent frames as `rejected_blank`, and encodes a PNG only in memory to validate the conversion path.
|
||||
- Returns only width, height, encoded byte count and quality. The frame and PNG bytes are discarded before the Tauri command returns; nothing is persisted, scheduled, or sent to AstrBot.
|
||||
|
||||
Validation: isolated `cargo check -p astrbot-desktop --lib`, `cargo test -p astrbot-desktop --lib` (121 passed), and `cargo clippy -p astrbot-desktop --lib -- -D warnings` all passed.
|
||||
|
||||
Manual evidence is still pending. No active UI invokes the diagnostic command yet, and no game, minimized window, lock screen, protected content, or multi-display run has been claimed as validated. Those observations remain blocking S0 acceptance.
|
||||
|
|
|
|||
11
docs/错题本.md
11
docs/错题本.md
|
|
@ -91,3 +91,14 @@
|
|||
- 修复或规避:保留项目内隔离目标缓存并以足够时限重跑;最终 117 个库测试全部通过。
|
||||
- 预防规则:默认目标触发 UNC `os error 5` 时,使用已验证的项目内 `CARGO_TARGET_DIR`;首次冷启动须看退出码和最终测试结果,不能把工具超时当作断言失败。
|
||||
- 验证证据:隔离 `cargo check` 和后续 `cargo test -p astrbot-desktop --lib` 均成功。
|
||||
|
||||
|
||||
## 2026-07-27 — WGC frame availability must have an explicit bounded timeout
|
||||
|
||||
- 阶段:S0.2 WGC 单帧 D3D11 质量诊断
|
||||
- 类型:功能行为 / Windows API 契约
|
||||
- 现象:`TryGetNextFrame()` 在第一帧尚未到达时会返回失败,不能把首次失败当作捕获不可用,也不能无限轮询。
|
||||
- 根因:free-threaded frame pool 启动后,帧到达与调用时刻异步;无帧与永久等待都是正常风险。
|
||||
- 修复或规避:注册 `FrameArrived` 事件并只等待 2 秒,到期返回明确的 `FrameTimedOut`;每次退出移除事件并关闭 frame/session/pool,避免留存捕获资源。
|
||||
- 预防规则:所有主动捕获路径必须有帧、尺寸、内存和生命周期上限;超时是可解释拒绝,不得重试成后台观察。
|
||||
- 验证证据:Rust 121 个库测试通过,Clippy 通过;真实 Windows 场景证据仍待人工验收。
|
||||
|
|
|
|||
|
|
@ -45,8 +45,14 @@ zeroize.workspace = true
|
|||
windows = { workspace = true, features = [
|
||||
"Win32_Foundation",
|
||||
"Graphics_Capture",
|
||||
"Graphics_DirectX_Direct3D11",
|
||||
"Win32_Graphics_Direct3D",
|
||||
"Win32_Graphics_Direct3D11",
|
||||
"Win32_Graphics_Dxgi",
|
||||
"Win32_Graphics_Dxgi_Common",
|
||||
"Win32_Graphics_Gdi",
|
||||
"Win32_System_WinRT_Graphics_Capture",
|
||||
"Win32_System_WinRT_Direct3D11",
|
||||
"Win32_NetworkManagement_IpHelper",
|
||||
"Win32_Networking_WinSock",
|
||||
"Win32_Security_Credentials",
|
||||
|
|
|
|||
|
|
@ -576,6 +576,17 @@ fn wgc_spike_probe_displays() -> Result<Vec<windows::wgc::WgcTargetProbe>, Strin
|
|||
windows::wgc::probe_display_targets().map_err(|error| error.to_string())
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
fn wgc_spike_probe_authorized_window_frame(
|
||||
app: AppHandle,
|
||||
session_token: uuid::Uuid,
|
||||
) -> Result<windows::wgc::WgcFrameProbe, String> {
|
||||
app.state::<capture_policy::CapturePolicy>()
|
||||
.inspect(session_token, windows::wgc::probe_selected_window_frame)
|
||||
.map_err(|error| error.to_string())?
|
||||
.map_err(|error| error.to_string())
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
fn end_window_capture_session(app: AppHandle, session_token: uuid::Uuid) -> ScreenReadingStatus {
|
||||
let policy = app.state::<capture_policy::CapturePolicy>();
|
||||
|
|
@ -966,6 +977,7 @@ pub fn run() {
|
|||
wgc_spike_support_status,
|
||||
wgc_spike_probe_authorized_window,
|
||||
wgc_spike_probe_displays,
|
||||
wgc_spike_probe_authorized_window_frame,
|
||||
set_screen_reading_enabled,
|
||||
begin_window_capture_session,
|
||||
end_window_capture_session,
|
||||
|
|
|
|||
|
|
@ -1,11 +1,9 @@
|
|||
//! Windows.Graphics.Capture target-binding spike.
|
||||
//!
|
||||
//! This module intentionally stops before a pixel frame is requested. It proves
|
||||
//! whether this Windows build can construct WGC capture items for an already
|
||||
//! authorized window and for the attached displays, without exposing a frame to
|
||||
//! React, disk, logging, or the network. The next S0 increment must add a
|
||||
//! bounded D3D11 frame path and black-frame validation before this can become a
|
||||
//! capture feature.
|
||||
//! S0.1 proves target binding; S0.2 adds a bounded, one-frame D3D11 readback
|
||||
//! for an already authorized window. The frame never crosses this Rust module:
|
||||
//! it is converted and quality-checked in memory, then discarded. React, disk,
|
||||
//! logs, scheduling, and the network receive only metadata.
|
||||
|
||||
use std::fmt;
|
||||
|
||||
|
|
@ -35,12 +33,31 @@ pub struct WgcSupportStatus {
|
|||
pub display_target_count: u16,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum WgcFrameQuality {
|
||||
Usable,
|
||||
RejectedBlank,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct WgcFrameProbe {
|
||||
pub width: u32,
|
||||
pub height: u32,
|
||||
pub encoded_png_bytes: u32,
|
||||
pub quality: WgcFrameQuality,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum WgcProbeError {
|
||||
Selection(ForegroundWindowError),
|
||||
UnsupportedPlatform,
|
||||
UnsupportedByWindows,
|
||||
InvalidTargetSize,
|
||||
FrameTimedOut,
|
||||
FrameTooLarge,
|
||||
EncodingFailed,
|
||||
Platform(u32),
|
||||
}
|
||||
|
||||
|
|
@ -56,6 +73,15 @@ impl fmt::Display for WgcProbeError {
|
|||
Self::InvalidTargetSize => {
|
||||
formatter.write_str("Windows.Graphics.Capture returned an invalid target size")
|
||||
}
|
||||
Self::FrameTimedOut => formatter.write_str(
|
||||
"Windows.Graphics.Capture did not deliver a frame before the bounded timeout",
|
||||
),
|
||||
Self::FrameTooLarge => {
|
||||
formatter.write_str("Windows.Graphics.Capture frame exceeds the local pixel budget")
|
||||
}
|
||||
Self::EncodingFailed => {
|
||||
formatter.write_str("Windows.Graphics.Capture frame could not be encoded in memory")
|
||||
}
|
||||
Self::Platform(code) => write!(
|
||||
formatter,
|
||||
"Windows.Graphics.Capture failed with HRESULT 0x{code:08x}"
|
||||
|
|
@ -145,6 +171,29 @@ pub fn probe_display_targets() -> Result<Vec<WgcTargetProbe>, WgcProbeError> {
|
|||
}
|
||||
}
|
||||
|
||||
/// Captures at most one WGC frame from an existing, authorized window. The
|
||||
/// frame is never returned: this is only an S0.2 quality probe for manual
|
||||
/// Windows evidence.
|
||||
pub fn probe_selected_window_frame(
|
||||
selection: &WindowSelection,
|
||||
) -> Result<WgcFrameProbe, WgcProbeError> {
|
||||
selection.validate().map_err(WgcProbeError::Selection)?;
|
||||
|
||||
#[cfg(windows)]
|
||||
{
|
||||
if !wgc_supported()? {
|
||||
return Err(WgcProbeError::UnsupportedByWindows);
|
||||
}
|
||||
capture_one_frame(capture_item_for_window(selection)?)
|
||||
}
|
||||
|
||||
#[cfg(not(windows))]
|
||||
{
|
||||
let _ = selection;
|
||||
Err(WgcProbeError::UnsupportedPlatform)
|
||||
}
|
||||
}
|
||||
|
||||
fn target_probe(kind: WgcTargetKind, size: WgcSize) -> Result<WgcTargetProbe, WgcProbeError> {
|
||||
let width = u32::try_from(size.width).map_err(|_| WgcProbeError::InvalidTargetSize)?;
|
||||
let height = u32::try_from(size.height).map_err(|_| WgcProbeError::InvalidTargetSize)?;
|
||||
|
|
@ -249,6 +298,226 @@ fn display_handles() -> Result<Vec<windows::Win32::Graphics::Gdi::HMONITOR>, Wgc
|
|||
Ok(displays)
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
fn capture_one_frame(
|
||||
item: windows::Graphics::Capture::GraphicsCaptureItem,
|
||||
) -> Result<WgcFrameProbe, WgcProbeError> {
|
||||
use std::{slice, sync::mpsc, time::Duration};
|
||||
|
||||
use windows::{
|
||||
Foundation::TypedEventHandler,
|
||||
Graphics::{
|
||||
Capture::Direct3D11CaptureFramePool,
|
||||
DirectX::{Direct3D11::IDirect3DDevice, DirectXPixelFormat},
|
||||
},
|
||||
Win32::{
|
||||
Foundation::HMODULE,
|
||||
Graphics::{
|
||||
Direct3D::D3D_DRIVER_TYPE_HARDWARE,
|
||||
Direct3D11::{
|
||||
D3D11_CPU_ACCESS_READ, D3D11_CREATE_DEVICE_BGRA_SUPPORT, D3D11_MAP_READ,
|
||||
D3D11_SDK_VERSION, D3D11_TEXTURE2D_DESC, D3D11_USAGE_STAGING,
|
||||
D3D11CreateDevice, ID3D11Device, ID3D11DeviceContext, ID3D11Texture2D,
|
||||
},
|
||||
Dxgi::IDXGIDevice,
|
||||
},
|
||||
System::WinRT::Direct3D11::{
|
||||
CreateDirect3D11DeviceFromDXGIDevice, IDirect3DDxgiInterfaceAccess,
|
||||
},
|
||||
},
|
||||
core::Interface,
|
||||
};
|
||||
|
||||
const MAX_FRAME_PIXELS: u64 = 16_000_000;
|
||||
const FRAME_TIMEOUT: Duration = Duration::from_secs(2);
|
||||
|
||||
let mut native_device: Option<ID3D11Device> = None;
|
||||
let mut context: Option<ID3D11DeviceContext> = None;
|
||||
unsafe {
|
||||
D3D11CreateDevice(
|
||||
None,
|
||||
D3D_DRIVER_TYPE_HARDWARE,
|
||||
HMODULE::default(),
|
||||
D3D11_CREATE_DEVICE_BGRA_SUPPORT,
|
||||
None,
|
||||
D3D11_SDK_VERSION,
|
||||
Some(&mut native_device),
|
||||
None,
|
||||
Some(&mut context),
|
||||
)
|
||||
.map_err(map_windows_error)?;
|
||||
}
|
||||
let native_device = native_device.ok_or(WgcProbeError::Platform(0))?;
|
||||
let context = context.ok_or(WgcProbeError::Platform(0))?;
|
||||
let dxgi_device: IDXGIDevice = native_device.cast().map_err(map_windows_error)?;
|
||||
let capture_device: IDirect3DDevice = unsafe {
|
||||
CreateDirect3D11DeviceFromDXGIDevice(&dxgi_device)
|
||||
.map_err(map_windows_error)?
|
||||
.cast()
|
||||
.map_err(map_windows_error)?
|
||||
};
|
||||
let size = item.Size().map_err(map_windows_error)?;
|
||||
let expected = target_probe(WgcTargetKind::Window, size.into())?;
|
||||
if u64::from(expected.width) * u64::from(expected.height) > MAX_FRAME_PIXELS {
|
||||
return Err(WgcProbeError::FrameTooLarge);
|
||||
}
|
||||
|
||||
let frame_pool = Direct3D11CaptureFramePool::CreateFreeThreaded(
|
||||
&capture_device,
|
||||
DirectXPixelFormat::B8G8R8A8UIntNormalized,
|
||||
1,
|
||||
size,
|
||||
)
|
||||
.map_err(map_windows_error)?;
|
||||
let session = frame_pool
|
||||
.CreateCaptureSession(&item)
|
||||
.map_err(map_windows_error)?;
|
||||
let (arrived_sender, arrived_receiver) = mpsc::sync_channel(1);
|
||||
let arrived_token = frame_pool
|
||||
.FrameArrived(&TypedEventHandler::new(move |_, _| {
|
||||
let _ = arrived_sender.try_send(());
|
||||
Ok(())
|
||||
}))
|
||||
.map_err(map_windows_error)?;
|
||||
if let Err(error) = session.StartCapture() {
|
||||
let _ = frame_pool.RemoveFrameArrived(arrived_token);
|
||||
let _ = session.Close();
|
||||
let _ = frame_pool.Close();
|
||||
return Err(map_windows_error(error));
|
||||
}
|
||||
if arrived_receiver.recv_timeout(FRAME_TIMEOUT).is_err() {
|
||||
let _ = frame_pool.RemoveFrameArrived(arrived_token);
|
||||
let _ = session.Close();
|
||||
let _ = frame_pool.Close();
|
||||
return Err(WgcProbeError::FrameTimedOut);
|
||||
}
|
||||
let frame = frame_pool.TryGetNextFrame().map_err(map_windows_error)?;
|
||||
let _ = frame_pool.RemoveFrameArrived(arrived_token);
|
||||
let surface = frame.Surface().map_err(map_windows_error)?;
|
||||
let surface_access: IDirect3DDxgiInterfaceAccess = surface.cast().map_err(map_windows_error)?;
|
||||
let source: ID3D11Texture2D =
|
||||
unsafe { surface_access.GetInterface().map_err(map_windows_error)? };
|
||||
let mut description = D3D11_TEXTURE2D_DESC::default();
|
||||
unsafe { source.GetDesc(&mut description) };
|
||||
if u64::from(description.Width) * u64::from(description.Height) > MAX_FRAME_PIXELS {
|
||||
let _ = frame.Close();
|
||||
let _ = session.Close();
|
||||
let _ = frame_pool.Close();
|
||||
return Err(WgcProbeError::FrameTooLarge);
|
||||
}
|
||||
description.Usage = D3D11_USAGE_STAGING;
|
||||
description.BindFlags = 0;
|
||||
description.CPUAccessFlags = D3D11_CPU_ACCESS_READ.0 as u32;
|
||||
description.MiscFlags = 0;
|
||||
let mut staging: Option<ID3D11Texture2D> = None;
|
||||
unsafe {
|
||||
native_device
|
||||
.CreateTexture2D(&description, None, Some(&mut staging))
|
||||
.map_err(map_windows_error)?;
|
||||
context.CopyResource(staging.as_ref().ok_or(WgcProbeError::Platform(0))?, &source);
|
||||
}
|
||||
let staging = staging.ok_or(WgcProbeError::Platform(0))?;
|
||||
let mut mapped = Default::default();
|
||||
unsafe {
|
||||
context
|
||||
.Map(&staging, 0, D3D11_MAP_READ, 0, Some(&mut mapped))
|
||||
.map_err(map_windows_error)?;
|
||||
}
|
||||
let rgba = copy_bgra_rows_to_rgba(
|
||||
unsafe {
|
||||
slice::from_raw_parts(
|
||||
mapped.pData.cast::<u8>(),
|
||||
usize::try_from(mapped.RowPitch).map_err(|_| WgcProbeError::FrameTooLarge)?
|
||||
* usize::try_from(description.Height)
|
||||
.map_err(|_| WgcProbeError::FrameTooLarge)?,
|
||||
)
|
||||
},
|
||||
description.Width,
|
||||
description.Height,
|
||||
mapped.RowPitch,
|
||||
);
|
||||
unsafe { context.Unmap(&staging, 0) };
|
||||
let rgba = rgba?;
|
||||
let quality = if frame_is_blank(&rgba) {
|
||||
WgcFrameQuality::RejectedBlank
|
||||
} else {
|
||||
WgcFrameQuality::Usable
|
||||
};
|
||||
let encoded_png_bytes =
|
||||
u32::try_from(encode_rgba_png(description.Width, description.Height, &rgba)?.len())
|
||||
.map_err(|_| WgcProbeError::EncodingFailed)?;
|
||||
let _ = frame.Close();
|
||||
let _ = session.Close();
|
||||
let _ = frame_pool.Close();
|
||||
Ok(WgcFrameProbe {
|
||||
width: description.Width,
|
||||
height: description.Height,
|
||||
encoded_png_bytes,
|
||||
quality,
|
||||
})
|
||||
}
|
||||
|
||||
fn copy_bgra_rows_to_rgba(
|
||||
source: &[u8],
|
||||
width: u32,
|
||||
height: u32,
|
||||
row_pitch: u32,
|
||||
) -> Result<Vec<u8>, WgcProbeError> {
|
||||
let row_bytes =
|
||||
usize::try_from(u64::from(width) * 4).map_err(|_| WgcProbeError::FrameTooLarge)?;
|
||||
let row_pitch = usize::try_from(row_pitch).map_err(|_| WgcProbeError::FrameTooLarge)?;
|
||||
let height = usize::try_from(height).map_err(|_| WgcProbeError::FrameTooLarge)?;
|
||||
if row_pitch < row_bytes
|
||||
|| source.len()
|
||||
< row_pitch
|
||||
.checked_mul(height)
|
||||
.ok_or(WgcProbeError::FrameTooLarge)?
|
||||
{
|
||||
return Err(WgcProbeError::FrameTooLarge);
|
||||
}
|
||||
let mut rgba = Vec::with_capacity(
|
||||
row_bytes
|
||||
.checked_mul(height)
|
||||
.ok_or(WgcProbeError::FrameTooLarge)?,
|
||||
);
|
||||
for row in source.chunks_exact(row_pitch).take(height) {
|
||||
for pixel in row[..row_bytes].chunks_exact(4) {
|
||||
rgba.extend_from_slice(&[pixel[2], pixel[1], pixel[0], pixel[3]]);
|
||||
}
|
||||
}
|
||||
Ok(rgba)
|
||||
}
|
||||
|
||||
fn frame_is_blank(rgba: &[u8]) -> bool {
|
||||
let mut visible = 0_u64;
|
||||
let mut non_dark = 0_u64;
|
||||
for pixel in rgba.chunks_exact(4).step_by(64) {
|
||||
if pixel[3] >= 8 {
|
||||
visible += 1;
|
||||
if u16::from(pixel[0]) + u16::from(pixel[1]) + u16::from(pixel[2]) >= 24 {
|
||||
non_dark += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
visible == 0 || non_dark.saturating_mul(100) < visible
|
||||
}
|
||||
|
||||
fn encode_rgba_png(width: u32, height: u32, pixels: &[u8]) -> Result<Vec<u8>, WgcProbeError> {
|
||||
let mut encoded = Vec::new();
|
||||
{
|
||||
let mut encoder = png::Encoder::new(&mut encoded, width, height);
|
||||
encoder.set_color(png::ColorType::Rgba);
|
||||
encoder.set_depth(png::BitDepth::Eight);
|
||||
let mut writer = encoder
|
||||
.write_header()
|
||||
.map_err(|_| WgcProbeError::EncodingFailed)?;
|
||||
writer
|
||||
.write_image_data(pixels)
|
||||
.map_err(|_| WgcProbeError::EncodingFailed)?;
|
||||
}
|
||||
Ok(encoded)
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
fn map_windows_error(error: windows::core::Error) -> WgcProbeError {
|
||||
WgcProbeError::Platform(error.code().0 as u32)
|
||||
|
|
@ -288,6 +557,31 @@ mod tests {
|
|||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn converts_bgra_rows_without_retaining_padding() {
|
||||
let rgba = copy_bgra_rows_to_rgba(&[3, 2, 1, 255, 7, 8, 9, 255, 0, 0, 0, 0], 2, 1, 12)
|
||||
.expect("convert");
|
||||
assert_eq!(rgba, vec![1, 2, 3, 255, 9, 8, 7, 255]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_an_undersized_mapped_row() {
|
||||
assert_eq!(
|
||||
copy_bgra_rows_to_rgba(&[0; 7], 2, 1, 7),
|
||||
Err(WgcProbeError::FrameTooLarge)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_blank_or_transparent_frames() {
|
||||
assert!(frame_is_blank(&[0, 0, 0, 0]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn accepts_a_frame_with_visible_non_dark_pixels() {
|
||||
assert!(!frame_is_blank(&[24, 0, 0, 255]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn serializable_support_status_starts_with_no_pixels() {
|
||||
let status = WgcSupportStatus {
|
||||
|
|
|
|||
正在加载…
添加表格
在新工单中引用