Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

cpu fallback etc

Richie McIlroyb971194d6a79
diff --git a/apps/desktop/src-tauri/src/frame_ws.rs b/apps/desktop/src-tauri/src/frame_ws.rs
index 2c96a338c..ff8569e69 100644
--- a/apps/desktop/src-tauri/src/frame_ws.rs
+++ b/apps/desktop/src-tauri/src/frame_ws.rs
@@ -1,7 +1,6 @@
-use std::sync::Arc;
use std::sync::atomic::{AtomicU32, AtomicU64, Ordering};
use std::time::Instant;
-use tokio::sync::{Mutex, broadcast, mpsc, watch};
+use tokio::sync::{broadcast, watch};
use tokio_util::sync::CancellationToken;
static TOTAL_BYTES_SENT: AtomicU64 = AtomicU64::new(0);
@@ -66,7 +65,7 @@ fn downscale_and_convert_to_nv12(
let y = ((66 * r + 129 * g + 25 * b + 128) >> 8) + 16;
y_plane[y_row_start + dst_x] = y.clamp(0, 255) as u8;
- if is_uv_row && dst_x % 2 == 0 && dst_x + 1 < new_width as usize {
+ if is_uv_row && dst_x.is_multiple_of(2) && dst_x + 1 < new_width as usize {
let src_x1 = (((dst_x + 1) as u32 * scale_x) >> 16) as usize;
let px1 = src_row + src_x1 * 4;
@@ -97,95 +96,6 @@ fn downscale_and_convert_to_nv12(
(output, new_width, new_height)
}
-fn downscale_rgba_fast(data: &[u8], width: u32, height: u32, stride: u32) -> (Vec<u8>, u32, u32) {
- let new_width = ((width * DOWNSCALE_PERCENT) / 100) & !1;
- let new_height = ((height * DOWNSCALE_PERCENT) / 100) & !1;
-
- if new_width == 0 || new_height == 0 {
- return (Vec::new(), 0, 0);
- }
-
- let new_stride = new_width * 4;
- let output_size = (new_stride * new_height) as usize;
-
- let stride_bytes = stride as usize;
- let dst_width = new_width as usize;
- let dst_height = new_height as usize;
-
- let scale_x = (width << 16) / new_width;
- let scale_y = (height << 16) / new_height;
-
- let mut output = vec![0u8; output_size];
-
- let chunks_of_4 = dst_width / 4;
- let remainder = dst_width % 4;
-
- for dst_y in 0..dst_height {
- let src_y = ((dst_y as u32 * scale_y) >> 16) as usize;
- let src_row = src_y * stride_bytes;
- let dst_row = dst_y * (new_stride as usize);
-
- if src_row + stride_bytes > data.len() {
- continue;
- }
-
- let mut dst_x = 0usize;
- for _ in 0..chunks_of_4 {
- let src_x0 = ((dst_x as u32 * scale_x) >> 16) as usize;
- let src_x1 = (((dst_x + 1) as u32 * scale_x) >> 16) as usize;
- let src_x2 = (((dst_x + 2) as u32 * scale_x) >> 16) as usize;
- let src_x3 = (((dst_x + 3) as u32 * scale_x) >> 16) as usize;
-
- let px0 = src_row + src_x0 * 4;
- let px1 = src_row + src_x1 * 4;
- let px2 = src_row + src_x2 * 4;
- let px3 = src_row + src_x3 * 4;
-
- let dst_base = dst_row + dst_x * 4;
-
- if px3 + 3 < data.len() && dst_base + 15 < output.len() {
- output[dst_base] = data[px0];
- output[dst_base + 1] = data[px0 + 1];
- output[dst_base + 2] = data[px0 + 2];
- output[dst_base + 3] = 255;
-
- output[dst_base + 4] = data[px1];
- output[dst_base + 5] = data[px1 + 1];
- output[dst_base + 6] = data[px1 + 2];
- output[dst_base + 7] = 255;
-
- output[dst_base + 8] = data[px2];
- output[dst_base + 9] = data[px2 + 1];
- output[dst_base + 10] = data[px2 + 2];
- output[dst_base + 11] = 255;
-
- output[dst_base + 12] = data[px3];
- output[dst_base + 13] = data[px3 + 1];
- output[dst_base + 14] = data[px3 + 2];
- output[dst_base + 15] = 255;
- }
-
- dst_x += 4;
- }
-
- for _ in 0..remainder {
- let src_x = ((dst_x as u32 * scale_x) >> 16) as usize;
- let px = src_row + src_x * 4;
- let dst_px = dst_row + dst_x * 4;
-
- if px + 3 < data.len() && dst_px + 3 < output.len() {
- output[dst_px] = data[px];
- output[dst_px + 1] = data[px + 1];
- output[dst_px + 2] = data[px + 2];
- output[dst_px + 3] = 255;
- }
- dst_x += 1;
- }
- }
-
- (output, new_width, new_height)
-}
-
fn pack_nv12_frame(
data: Vec<u8>,
width: u32,
@@ -207,26 +117,6 @@ fn pack_nv12_frame(
output
}
-fn pack_downscaled_rgba_frame(
- data: Vec<u8>,
- width: u32,
- height: u32,
- frame_number: u32,
- target_time_ns: u64,
-) -> Vec<u8> {
- let stride = width * 4;
- let metadata_size = 24;
- let mut output = Vec::with_capacity(data.len() + metadata_size);
- output.extend_from_slice(&data);
- output.extend_from_slice(&stride.to_le_bytes());
- output.extend_from_slice(&height.to_le_bytes());
- output.extend_from_slice(&width.to_le_bytes());
- output.extend_from_slice(&frame_number.to_le_bytes());
- output.extend_from_slice(&target_time_ns.to_le_bytes());
-
- output
-}
-
fn pack_frame_data(
mut data: Vec<u8>,
stride: u32,
@@ -420,103 +310,6 @@ pub async fn create_watch_frame_ws(
(port, cancel_token_child)
}
-pub async fn create_mpsc_frame_ws(
- frame_rx: Arc<Mutex<mpsc::Receiver<WSFrame>>>,
-) -> (u16, CancellationToken) {
- use axum::{
- extract::{
- State,
- ws::{Message, WebSocket, WebSocketUpgrade},
- },
- response::IntoResponse,
- routing::get,
- };
-
- type RouterState = Arc<Mutex<mpsc::Receiver<WSFrame>>>;
-
- #[axum::debug_handler]
- async fn ws_handler(
- ws: WebSocketUpgrade,
- State(state): State<RouterState>,
- ) -> impl IntoResponse {
- ws.on_upgrade(move |socket| handle_socket(socket, state))
- }
-
- async fn handle_socket(mut socket: WebSocket, frame_rx: RouterState) {
- tracing::info!("Socket connection established (mpsc)");
- let now = std::time::Instant::now();
-
- loop {
- let frame_opt = {
- let mut rx = frame_rx.lock().await;
- tokio::select! {
- biased;
- msg = socket.recv() => {
- match msg {
- Some(Ok(Message::Close(_))) | None => {
- tracing::info!("WebSocket closed");
- break;
- }
- Some(Ok(_)) => {
- continue;
- }
- Some(Err(e)) => {
- tracing::error!("WebSocket error: {:?}", e);
- break;
- }
- }
- },
- frame = rx.recv() => frame,
- }
- };
-
- let Some(frame) = frame_opt else {
- tracing::info!("Frame channel closed");
- break;
- };
-
- let packed = pack_frame_data(
- frame.data,
- frame.stride,
- frame.height,
- frame.width,
- frame.frame_number,
- frame.target_time_ns,
- );
-
- if let Err(e) = socket.send(Message::Binary(packed)).await {
- tracing::error!("Failed to send frame to socket: {:?}", e);
- break;
- }
- }
-
- let elapsed = now.elapsed();
- tracing::info!("Websocket closing after {elapsed:.2?}");
- }
-
- let router = axum::Router::new()
- .route("/", get(ws_handler))
- .with_state(frame_rx);
-
- let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
- let port = listener.local_addr().unwrap().port();
- tracing::info!("WebSocket server (mpsc) listening on port {}", port);
-
- let cancel_token = CancellationToken::new();
- let cancel_token_child = cancel_token.child_token();
- tokio::spawn(async move {
- let server = axum::serve(listener, router.into_make_service());
- tokio::select! {
- _ = server => {},
- _ = cancel_token.cancelled() => {
- tracing::info!("WebSocket server shutting down");
- }
- }
- });
-
- (port, cancel_token_child)
-}
-
pub async fn create_frame_ws(frame_tx: broadcast::Sender<WSFrame>) -> (u16, CancellationToken) {
use axum::{
extract::{
diff --git a/apps/desktop/src/utils/frame-worker.ts b/apps/desktop/src/utils/frame-worker.ts
index 6062310c5..0a75ca66a 100644
--- a/apps/desktop/src/utils/frame-worker.ts
+++ b/apps/desktop/src/utils/frame-worker.ts
@@ -284,6 +284,62 @@ function parseFrameMetadata(bytes: Uint8Array): FrameMetadata | null {
};
}
+let nv12ConversionBuffer: Uint8ClampedArray | null = null;
+let nv12ConversionBufferSize = 0;
+
+function convertNv12ToRgba(
+ nv12Data: Uint8ClampedArray,
+ width: number,
+ height: number,
+ yStride: number,
+): Uint8ClampedArray {
+ const rgbaSize = width * height * 4;
+ if (!nv12ConversionBuffer || nv12ConversionBufferSize < rgbaSize) {
+ nv12ConversionBuffer = new Uint8ClampedArray(rgbaSize);
+ nv12ConversionBufferSize = rgbaSize;
+ }
+ const rgba = nv12ConversionBuffer;
+
+ const ySize = yStride * height;
+ const yPlane = nv12Data;
+ const uvPlane = nv12Data.subarray(ySize);
+ const uvStride = width;
+
+ for (let row = 0; row < height; row++) {
+ const yRowOffset = row * yStride;
+ const uvRowOffset = Math.floor(row / 2) * uvStride;
+ const rgbaRowOffset = row * width * 4;
+
+ for (let col = 0; col < width; col++) {
+ const y = yPlane[yRowOffset + col] - 16;
+
+ const uvCol = Math.floor(col / 2) * 2;
+ const u = uvPlane[uvRowOffset + uvCol] - 128;
+ const v = uvPlane[uvRowOffset + uvCol + 1] - 128;
+
+ const c = 298 * y;
+ const d = u;
+ const e = v;
+
+ let r = (c + 409 * e + 128) >> 8;
+ let g = (c - 100 * d - 208 * e + 128) >> 8;
+ let b = (c + 516 * d + 128) >> 8;
+
+ r = r < 0 ? 0 : r > 255 ? 255 : r;
+ g = g < 0 ? 0 : g > 255 ? 255 : g;
+ b = b < 0 ? 0 : b > 255 ? 255 : b;
+
+ const rgbaOffset = rgbaRowOffset + col * 4;
+ rgba[rgbaOffset] = r;
+ rgba[rgbaOffset + 1] = g;
+ rgba[rgbaOffset + 2] = b;
+ rgba[rgbaOffset + 3] = 255;
+ }
+ }
+
+ return rgba.subarray(0, rgbaSize);
+}
+
function renderBorrowedWebGPU(bytes: Uint8Array, release: () => void): boolean {
if (
(renderMode !== "webgpu" && renderMode !== "pending") ||
@@ -865,39 +921,46 @@ function processFrameBytesSync(
return { type: "frame-queued", width, height };
}
- if (meta.format !== "rgba") {
- releaseCallback?.();
- return {
- type: "error",
- message: "Canvas2D mode does not support NV12 format",
- };
- }
-
const expectedRowBytes = width * 4;
const expectedLength = expectedRowBytes * height;
- const frameData = new Uint8ClampedArray(
- bytes.buffer,
- bytes.byteOffset,
- bytes.byteLength - 24,
- );
-
let processedFrameData: Uint8ClampedArray;
- if (meta.strideBytes === expectedRowBytes) {
- processedFrameData = frameData.subarray(0, expectedLength);
+
+ if (meta.format === "nv12") {
+ const nv12FrameData = new Uint8ClampedArray(
+ bytes.buffer,
+ bytes.byteOffset,
+ meta.totalSize,
+ );
+ processedFrameData = convertNv12ToRgba(
+ nv12FrameData,
+ width,
+ height,
+ meta.yStride,
+ );
} else {
- if (!strideBuffer || strideBufferSize < expectedLength) {
- strideBuffer = new Uint8ClampedArray(expectedLength);
- strideBufferSize = expectedLength;
- }
- for (let row = 0; row < height; row += 1) {
- const srcStart = row * meta.strideBytes;
- const destStart = row * expectedRowBytes;
- strideBuffer.set(
- frameData.subarray(srcStart, srcStart + expectedRowBytes),
- destStart,
- );
+ const frameData = new Uint8ClampedArray(
+ bytes.buffer,
+ bytes.byteOffset,
+ bytes.byteLength - 24,
+ );
+
+ if (meta.strideBytes === expectedRowBytes) {
+ processedFrameData = frameData.subarray(0, expectedLength);
+ } else {
+ if (!strideBuffer || strideBufferSize < expectedLength) {
+ strideBuffer = new Uint8ClampedArray(expectedLength);
+ strideBufferSize = expectedLength;
+ }
+ for (let row = 0; row < height; row += 1) {
+ const srcStart = row * meta.strideBytes;
+ const destStart = row * expectedRowBytes;
+ strideBuffer.set(
+ frameData.subarray(srcStart, srcStart + expectedRowBytes),
+ destStart,
+ );
+ }
+ processedFrameData = strideBuffer.subarray(0, expectedLength);
}
- processedFrameData = strideBuffer.subarray(0, expectedLength);
}
if (!lastRawFrameData || lastRawFrameData.length < expectedLength) {
diff --git a/apps/desktop/src/utils/socket.ts b/apps/desktop/src/utils/socket.ts
index 31ac33425..a7c50bbf0 100644
--- a/apps/desktop/src/utils/socket.ts
+++ b/apps/desktop/src/utils/socket.ts
@@ -24,6 +24,62 @@ const FRAME_BUFFER_CONFIG: SharedFrameBufferConfig = {
slotSize: 16 * 1024 * 1024,
};
+let mainThreadNv12Buffer: Uint8ClampedArray | null = null;
+let mainThreadNv12BufferSize = 0;
+
+function convertNv12ToRgbaMainThread(
+ nv12Data: Uint8ClampedArray,
+ width: number,
+ height: number,
+ yStride: number,
+): Uint8ClampedArray {
+ const rgbaSize = width * height * 4;
+ if (!mainThreadNv12Buffer || mainThreadNv12BufferSize < rgbaSize) {
+ mainThreadNv12Buffer = new Uint8ClampedArray(rgbaSize);
+ mainThreadNv12BufferSize = rgbaSize;
+ }
+ const rgba = mainThreadNv12Buffer;
+
+ const ySize = yStride * height;
+ const yPlane = nv12Data;
+ const uvPlane = nv12Data.subarray(ySize);
+ const uvStride = width;
+
+ for (let row = 0; row < height; row++) {
+ const yRowOffset = row * yStride;
+ const uvRowOffset = Math.floor(row / 2) * uvStride;
+ const rgbaRowOffset = row * width * 4;
+
+ for (let col = 0; col < width; col++) {
+ const y = yPlane[yRowOffset + col] - 16;
+
+ const uvCol = Math.floor(col / 2) * 2;
+ const u = uvPlane[uvRowOffset + uvCol] - 128;
+ const v = uvPlane[uvRowOffset + uvCol + 1] - 128;
+
+ const c = 298 * y;
+ const d = u;
+ const e = v;
+
+ let r = (c + 409 * e + 128) >> 8;
+ let g = (c - 100 * d - 208 * e + 128) >> 8;
+ let b = (c + 516 * d + 128) >> 8;
+
+ r = r < 0 ? 0 : r > 255 ? 255 : r;
+ g = g < 0 ? 0 : g > 255 ? 255 : g;
+ b = b < 0 ? 0 : b > 255 ? 255 : b;
+
+ const rgbaOffset = rgbaRowOffset + col * 4;
+ rgba[rgbaOffset] = r;
+ rgba[rgbaOffset + 1] = g;
+ rgba[rgbaOffset + 2] = b;
+ rgba[rgbaOffset + 3] = 255;
+ }
+ }
+
+ return rgba.subarray(0, rgbaSize);
+}
+
export type FrameData = {
width: number;
height: number;
@@ -499,6 +555,53 @@ export function createImageDataWS(
return;
}
+ if (directCanvas && directCtx) {
+ const metadataOffset = buffer.byteLength - 28;
+ const meta = new DataView(buffer, metadataOffset, 28);
+ const yStride = meta.getUint32(0, true);
+ const height = meta.getUint32(4, true);
+ const width = meta.getUint32(8, true);
+
+ if (width > 0 && height > 0) {
+ const ySize = yStride * height;
+ const uvSize = width * (height / 2);
+ const totalSize = ySize + uvSize;
+
+ const nv12Data = new Uint8ClampedArray(buffer, 0, totalSize);
+ const rgbaData = convertNv12ToRgbaMainThread(
+ nv12Data,
+ width,
+ height,
+ yStride,
+ );
+
+ if (directCanvas.width !== width || directCanvas.height !== height) {
+ directCanvas.width = width;
+ directCanvas.height = height;
+ }
+
+ if (
+ !cachedDirectImageData ||
+ cachedDirectWidth !== width ||
+ cachedDirectHeight !== height
+ ) {
+ cachedDirectImageData = new ImageData(width, height);
+ cachedDirectWidth = width;
+ cachedDirectHeight = height;
+ }
+ cachedDirectImageData.data.set(rgbaData);
+ directCtx.putImageData(cachedDirectImageData, 0, 0);
+ actualRendersCount++;
+ renderFrameCount++;
+
+ if (!hasRenderedFrame()) {
+ setHasRenderedFrame(true);
+ }
+ onmessage({ width, height });
+ }
+ return;
+ }
+
if (isProcessing) {
framesDropped++;
nextFrame = buffer;
diff --git a/crates/video-decode/src/media_foundation.rs b/crates/video-decode/src/media_foundation.rs
index acc83c037..ff45467fd 100644
--- a/crates/video-decode/src/media_foundation.rs
+++ b/crates/video-decode/src/media_foundation.rs
@@ -10,28 +10,27 @@ use windows::{
Foundation::{HANDLE, HMODULE},
Graphics::{
Direct3D::{
- D3D_DRIVER_TYPE_HARDWARE, D3D_FEATURE_LEVEL, D3D_SRV_DIMENSION_TEXTURE2D, ID3DBlob,
+ D3D_DRIVER_TYPE_HARDWARE, D3D_DRIVER_TYPE_WARP, D3D_FEATURE_LEVEL,
+ D3D_SRV_DIMENSION_TEXTURE2D, ID3DBlob,
},
Direct3D11::{
D3D11_BIND_CONSTANT_BUFFER, D3D11_BIND_SHADER_RESOURCE,
D3D11_BIND_UNORDERED_ACCESS, D3D11_BUFFER_DESC, D3D11_CPU_ACCESS_READ,
D3D11_CREATE_DEVICE_BGRA_SUPPORT, D3D11_CREATE_DEVICE_VIDEO_SUPPORT,
D3D11_DECODER_PROFILE_H264_VLD_NOFGT, D3D11_DECODER_PROFILE_HEVC_VLD_MAIN,
- D3D11_MAP_READ, D3D11_MAPPED_SUBRESOURCE, D3D11_RESOURCE_MISC_SHARED_NTHANDLE,
- D3D11_SDK_VERSION, D3D11_SHADER_RESOURCE_VIEW_DESC1,
- D3D11_SHADER_RESOURCE_VIEW_DESC1_0, D3D11_TEX2D_SRV1, D3D11_TEX2D_UAV,
- D3D11_TEXTURE2D_DESC, D3D11_UAV_DIMENSION_TEXTURE2D,
- D3D11_UNORDERED_ACCESS_VIEW_DESC, D3D11_UNORDERED_ACCESS_VIEW_DESC_0,
- D3D11_USAGE_DEFAULT, D3D11_USAGE_STAGING, D3D11_VIDEO_DECODER_DESC,
- D3D11CreateDevice, ID3D11Buffer, ID3D11ComputeShader, ID3D11Device, ID3D11Device3,
- ID3D11DeviceContext, ID3D11DeviceContext1, ID3D11ShaderResourceView,
- ID3D11ShaderResourceView1, ID3D11Texture2D, ID3D11UnorderedAccessView,
- ID3D11VideoDevice,
+ D3D11_MAP_READ, D3D11_MAPPED_SUBRESOURCE, D3D11_SDK_VERSION,
+ D3D11_SHADER_RESOURCE_VIEW_DESC1, D3D11_SHADER_RESOURCE_VIEW_DESC1_0,
+ D3D11_TEX2D_SRV1, D3D11_TEX2D_UAV, D3D11_TEXTURE2D_DESC,
+ D3D11_UAV_DIMENSION_TEXTURE2D, D3D11_UNORDERED_ACCESS_VIEW_DESC,
+ D3D11_UNORDERED_ACCESS_VIEW_DESC_0, D3D11_USAGE_DEFAULT, D3D11_USAGE_STAGING,
+ D3D11_VIDEO_DECODER_DESC, D3D11CreateDevice, ID3D11Buffer, ID3D11ComputeShader,
+ ID3D11Device, ID3D11Device3, ID3D11DeviceContext, ID3D11DeviceContext1,
+ ID3D11ShaderResourceView, ID3D11ShaderResourceView1, ID3D11Texture2D,
+ ID3D11UnorderedAccessView, ID3D11VideoDevice,
},
Dxgi::Common::{
DXGI_FORMAT_NV12, DXGI_FORMAT_R8_UNORM, DXGI_FORMAT_R8G8_UNORM, DXGI_SAMPLE_DESC,
},
- Dxgi::{DXGI_SHARED_RESOURCE_READ, DXGI_SHARED_RESOURCE_WRITE, IDXGIResource1},
},
Media::MediaFoundation::{
IMFAttributes, IMFDXGIBuffer, IMFDXGIDeviceManager, IMFSample, IMFSourceReader,
@@ -480,43 +479,6 @@ fn create_constant_buffer(device: &ID3D11Device3) -> Result<ID3D11Buffer, String
}
}
-fn create_nv12_texture(
- device: &ID3D11Device,
- width: u32,
- height: u32,
-) -> Result<FrameTexture, String> {
- let desc = D3D11_TEXTURE2D_DESC {
- Width: width,
- Height: height,
- MipLevels: 1,
- ArraySize: 1,
- Format: DXGI_FORMAT_NV12,
- SampleDesc: DXGI_SAMPLE_DESC {
- Count: 1,
- Quality: 0,
- },
- Usage: D3D11_USAGE_DEFAULT,
- BindFlags: D3D11_BIND_SHADER_RESOURCE.0 as u32,
- CPUAccessFlags: 0,
- MiscFlags: 0,
- };
-
- let texture = unsafe {
- let mut tex: Option<ID3D11Texture2D> = None;
- device
- .CreateTexture2D(&desc, None, Some(&mut tex))
- .map_err(|e| format!("CreateTexture2D NV12 failed: {e:?}"))?;
- tex.ok_or("CreateTexture2D NV12 returned null")?
- };
-
- Ok(FrameTexture {
- texture,
- handle: HANDLE::default(),
- width,
- height,
- })
-}
-
fn create_internal_texture(
device: &ID3D11Device,
width: u32,
@@ -556,58 +518,6 @@ fn create_internal_texture(
})
}
-fn create_shared_texture(
- device: &ID3D11Device,
- width: u32,
- height: u32,
- format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT,
- bind: u32,
-) -> Result<FrameTexture, String> {
- let desc = D3D11_TEXTURE2D_DESC {
- Width: width,
- Height: height,
- MipLevels: 1,
- ArraySize: 1,
- Format: format,
- SampleDesc: DXGI_SAMPLE_DESC {
- Count: 1,
- Quality: 0,
- },
- Usage: D3D11_USAGE_DEFAULT,
- BindFlags: bind,
- CPUAccessFlags: 0,
- MiscFlags: D3D11_RESOURCE_MISC_SHARED_NTHANDLE.0 as u32,
- };
-
- let texture = unsafe {
- let mut tex: Option<ID3D11Texture2D> = None;
- if let Err(e) = device.CreateTexture2D(&desc, None, Some(&mut tex)) {
- return Err(format!("CreateTexture2D failed: {e:?}"));
- }
- tex.ok_or("CreateTexture2D returned null")?
- };
-
- let handle = unsafe {
- let resource: IDXGIResource1 = texture
- .cast()
- .map_err(|e| format!("Failed to cast texture to IDXGIResource1: {e:?}"))?;
- resource
- .CreateSharedHandle(
- None,
- DXGI_SHARED_RESOURCE_READ.0 | DXGI_SHARED_RESOURCE_WRITE.0,
- None,
- )
- .map_err(|e| format!("CreateSharedHandle failed: {e:?}"))?
- };
-
- Ok(FrameTexture {
- texture,
- handle,
- width,
- height,
- })
-}
-
fn create_uav(
device: &ID3D11Device,
texture: &ID3D11Texture2D,
@@ -979,35 +889,67 @@ unsafe fn create_d3d11_device() -> Result<(ID3D11Device, ID3D11DeviceContext), S
windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_10_0,
];
- let mut device: Option<ID3D11Device> = None;
- let mut context: Option<ID3D11DeviceContext> = None;
+ let driver_types = [
+ (D3D_DRIVER_TYPE_HARDWARE, "hardware"),
+ (D3D_DRIVER_TYPE_WARP, "WARP (software)"),
+ ];
- unsafe {
- D3D11CreateDevice(
- None,
- D3D_DRIVER_TYPE_HARDWARE,
- HMODULE::default(),
- flags,
- Some(&feature_levels),
- D3D11_SDK_VERSION,
- Some(&mut device),
- None,
- Some(&mut context),
- )
- .map_err(|e| format!("D3D11CreateDevice failed: {e:?}"))?;
- }
+ let mut last_error = String::new();
- let device = device.ok_or("D3D11CreateDevice returned null device")?;
- let context = context.ok_or("D3D11CreateDevice returned null context")?;
+ for (driver_type, driver_name) in driver_types {
+ let mut device: Option<ID3D11Device> = None;
+ let mut context: Option<ID3D11DeviceContext> = None;
- let multithread: windows::Win32::Graphics::Direct3D11::ID3D11Multithread = device
- .cast()
- .map_err(|e| format!("Failed to get ID3D11Multithread: {e:?}"))?;
- unsafe {
- let _ = multithread.SetMultithreadProtected(true);
+ let result = unsafe {
+ D3D11CreateDevice(
+ None,
+ driver_type,
+ HMODULE::default(),
+ flags,
+ Some(&feature_levels),
+ D3D11_SDK_VERSION,
+ Some(&mut device),
+ None,
+ Some(&mut context),
+ )
+ };
+
+ match result {
+ Ok(()) => {
+ if let (Some(device), Some(context)) = (device, context) {
+ if driver_type == D3D_DRIVER_TYPE_WARP {
+ warn!(
+ "Using WARP software rasterizer for D3D11 - hardware GPU unavailable"
+ );
+ } else {
+ info!("D3D11 device created using {} adapter", driver_name);
+ }
+
+ let multithread: windows::Win32::Graphics::Direct3D11::ID3D11Multithread =
+ device
+ .cast()
+ .map_err(|e| format!("Failed to get ID3D11Multithread: {e:?}"))?;
+ unsafe {
+ let _ = multithread.SetMultithreadProtected(true);
+ }
+
+ return Ok((device, context));
+ }
+ last_error = format!(
+ "D3D11CreateDevice ({}) returned null device/context",
+ driver_name
+ );
+ }
+ Err(e) => {
+ last_error = format!("D3D11CreateDevice ({}) failed: {e:?}", driver_name);
+ if driver_type == D3D_DRIVER_TYPE_HARDWARE {
+ warn!("{}, trying WARP fallback", last_error);
+ }
+ }
+ }
}
- Ok((device, context))
+ Err(last_error)
}
unsafe fn create_dxgi_device_manager(