Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 5 additions & 2 deletions .github/workflows/instant-reliability.yml
Original file line number Diff line number Diff line change
Expand Up @@ -316,8 +316,11 @@ jobs:
run: |
set -euo pipefail
sudo apt-get update -qq
# v4l2loopback needs videodev, which is in the extra kernel modules.
sudo apt-get install -y -qq "linux-modules-extra-$(uname -r)" v4l2loopback-dkms xvfb x11-utils xdotool \
if ! sudo modprobe videodev 2>/dev/null; then
sudo apt-get install -y -qq "linux-modules-extra-$(uname -r)"
sudo modprobe videodev
fi
sudo apt-get install -y -qq "linux-headers-$(uname -r)" v4l2loopback-dkms xvfb x11-utils xdotool \
dbus ffmpeg pulseaudio pulseaudio-utils libasound2-plugins >/dev/null
chmod +x "$RUNNER_TEMP/build/cap-gpui" "$RUNNER_TEMP/build/real-app-tests"
sudo modprobe v4l2loopback video_nr=42 card_label="Cap Test Camera" exclusive_caps=1
Expand Down
47 changes: 40 additions & 7 deletions crates/rendering/src/decoder/media_foundation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -246,6 +246,9 @@ impl MFDecoder {
Step::Seek(frame) => match decoder.seek(frame_to_100ns(frame, fps)) {
Ok(()) => {
requests.seeked(frame);
for retired in requests.take_retired() {
decoder.recycle_nv12_buffer(retired.data);
}
Vec::new()
}
Err(e) => {
Expand All @@ -259,11 +262,15 @@ impl MFDecoder {
Ok(Some(sample)) => {
health.record_success(decode_start.elapsed());
let bytes = sample.data.data.len();
requests.decoded(
let answers = requests.decoded(
pts_100ns_to_frame(sample.pts, fps),
sample.data,
bytes,
)
);
for retired in requests.take_retired() {
decoder.recycle_nv12_buffer(retired.data);
}
answers
}
Ok(None) => requests.stopped(),
Err(e) => {
Expand Down Expand Up @@ -317,6 +324,7 @@ struct FrameRequests<T, R> {
// below a frame is the stream's newest sample there.
cache: BTreeMap<u32, (T, usize)>,
cache_bytes: usize,
retired: Vec<T>,
waiting: Vec<(u32, R)>,
seeked_to: Option<u32>,
readahead_frames: u32,
Expand All @@ -328,6 +336,7 @@ impl<T: Clone, R> FrameRequests<T, R> {
Self {
cache: BTreeMap::new(),
cache_bytes: 0,
retired: Vec::new(),
waiting: Vec::new(),
seeked_to: None,
readahead_frames,
Expand Down Expand Up @@ -402,11 +411,19 @@ impl<T: Clone, R> FrameRequests<T, R> {
}

fn seeked(&mut self, frame: u32) {
self.cache.clear();
self.retired.extend(
std::mem::take(&mut self.cache)
.into_values()
.map(|(sample, _)| sample),
);
self.cache_bytes = 0;
self.seeked_to = Some(frame);
}

fn take_retired(&mut self) -> Vec<T> {
std::mem::take(&mut self.retired)
}

// A waiting frame the decoder jumped past has no sample at or below it since the seek, so
// it gets the first one after.
fn decoded(&mut self, frame: u32, sample: T, bytes: usize) -> Vec<Answer<T, R>> {
Expand All @@ -422,15 +439,17 @@ impl<T: Clone, R> FrameRequests<T, R> {
})
.collect();

if let Some((_, replaced)) = self.cache.remove(&frame) {
self.cache_bytes -= replaced;
if let Some((replaced, bytes)) = self.cache.remove(&frame) {
self.retired.push(replaced);
self.cache_bytes -= bytes;
}
while !self.cache.is_empty()
&& (self.cache.len() >= FRAME_CACHE_SIZE
|| self.cache_bytes + bytes > MAX_FRAME_CACHE_BYTES)
{
if let Some((_, (_, evicted))) = self.cache.pop_first() {
self.cache_bytes -= evicted;
if let Some((_, (evicted, bytes))) = self.cache.pop_first() {
self.retired.push(evicted);
self.cache_bytes -= bytes;
}
}
self.cache.insert(frame, (sample, bytes));
Expand Down Expand Up @@ -469,6 +488,20 @@ mod tests {
assert_eq!(pts_100ns_to_frame(10_000_000, 30), 30);
}

#[test]
fn cache_replacements_evictions_and_seeks_retire_samples() {
let mut requests = FrameRequests::<usize, ()>::new(0);
requests.decoded(0, 1, 1);
requests.decoded(0, 2, 1);
assert_eq!(requests.take_retired(), [1]);

requests.decoded(1, 3, MAX_FRAME_CACHE_BYTES);
assert_eq!(requests.take_retired(), [2]);

requests.seeked(10);
assert_eq!(requests.take_retired(), [3]);
}

// Samples are their index in `frames`, which holds the frame each one rounds to.
struct FakeStream {
frames: Vec<u32>,
Expand Down
43 changes: 42 additions & 1 deletion crates/scap-targets/src/platform/linux/wayland.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ use wayland_protocols::xdg::xdg_output::zv1::client::{zxdg_output_manager_v1, zx

use super::{DisplayImpl, LogicalBounds, LogicalPosition, LogicalSize};

const QUERY_TIMEOUT: Duration = Duration::from_secs(1);

#[derive(Clone, Copy, Default)]
struct OutputGeometry {
position: (i32, i32),
Expand Down Expand Up @@ -108,7 +110,7 @@ pub(super) fn displays() -> Option<Vec<DisplayImpl>> {
runtime.join(display)
};
let connection = Connection::from_socket(UnixStream::connect(socket).ok()?).ok()?;
query(&connection, Duration::from_millis(250))
query(&connection, QUERY_TIMEOUT)
}

fn output_uuid(name: &str) -> Option<uuid::Uuid> {
Expand Down Expand Up @@ -453,6 +455,45 @@ mod tests {
assert!(started.elapsed() < Duration::from_secs(1));
}

#[test]
fn busy_compositor_can_finish_display_enumeration_after_a_quarter_second() {
use std::io::{Read, Write};

let (client, mut server) = UnixStream::pair().unwrap();
let (finished_tx, finished_rx) = std::sync::mpsc::channel();
let responder = std::thread::spawn(move || -> std::io::Result<()> {
for reply in 0..2 {
loop {
let mut header = [0u8; 8];
server.read_exact(&mut header)?;
let object = u32::from_ne_bytes(header[..4].try_into().unwrap());
let message = u32::from_ne_bytes(header[4..].try_into().unwrap());
let mut payload = vec![0; (message >> 16) as usize - header.len()];
server.read_exact(&mut payload)?;
if object != 1 || message & 0xffff != 0 {
continue;
}
if reply == 0 {
std::thread::sleep(Duration::from_millis(350));
}
let callback = u32::from_ne_bytes(payload[..4].try_into().unwrap());
server.write_all(&callback.to_ne_bytes())?;
server.write_all(&(12u32 << 16).to_ne_bytes())?;
server.write_all(&0u32.to_ne_bytes())?;
break;
}
}
let _ = finished_rx.recv();
Ok(())
});
let connection = Connection::from_socket(client).unwrap();
let result = query(&connection, QUERY_TIMEOUT);
drop(connection);
let _ = finished_tx.send(());
responder.join().unwrap().unwrap();
assert!(result.is_some());
}

#[test]
fn wayland_session_does_not_use_xwayland_dimensions() {
assert!(super::super::prefers_wayland_environment(
Expand Down
115 changes: 113 additions & 2 deletions crates/video-decode/src/media_foundation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -585,6 +585,58 @@ fn create_uav(

// Samples whose copy to a staging texture can be in flight while an earlier one is read back.
const READBACK_DEPTH: usize = 2;
const MAX_CPU_READBACK_BUFFERS: usize = 8;
const MAX_CPU_READBACK_BUFFER_BYTES: usize = 128 * 1024 * 1024;

#[derive(Default)]
struct CpuReadbackPool {
free: Vec<Vec<u8>>,
pending: Vec<Arc<Vec<u8>>>,
}

impl CpuReadbackPool {
fn acquire(&mut self, size: usize) -> Vec<u8> {
self.collect();
let mut buffer = self.free.pop().unwrap_or_default();
buffer.clear();
if buffer.capacity() < size {
buffer.reserve(size);
}
buffer
}

fn recycle(&mut self, buffer: Arc<Vec<u8>>) {
self.collect();
match Arc::try_unwrap(buffer) {
Ok(buffer) if self.can_retain(buffer.capacity()) => self.free.push(buffer),
Ok(_) => {}
Err(buffer) if self.can_retain(buffer.capacity()) => self.pending.push(buffer),
Err(_) => {}
}
}

fn collect(&mut self) {
for buffer in std::mem::take(&mut self.pending) {
match Arc::try_unwrap(buffer) {
Ok(buffer) => self.free.push(buffer),
Err(buffer) => self.pending.push(buffer),
}
}
}

fn can_retain(&self, capacity: usize) -> bool {
self.free.len() + self.pending.len() < MAX_CPU_READBACK_BUFFERS
&& self.retained_bytes().saturating_add(capacity) <= MAX_CPU_READBACK_BUFFER_BYTES
}

fn retained_bytes(&self) -> usize {
self.free
.iter()
.map(Vec::capacity)
.chain(self.pending.iter().map(|buffer| buffer.capacity()))
.fold(0, |total, capacity| total.saturating_add(capacity))
}
}

pub struct MediaFoundationDecoder {
source_reader: IMFSourceReader,
Expand All @@ -597,6 +649,7 @@ pub struct MediaFoundationDecoder {
frame_rate_den: u32,
readback_free: Vec<ID3D11Texture2D>,
readback_queue: VecDeque<(i64, ID3D11Texture2D)>,
cpu_readback_pool: CpuReadbackPool,
// How the stream stopped, reported once the queued readbacks are drained.
readback_end: Option<Result<(), String>>,
frame_pool: FramePool,
Expand Down Expand Up @@ -690,6 +743,7 @@ impl MediaFoundationDecoder {
frame_rate_den,
readback_free,
readback_queue: VecDeque::new(),
cpu_readback_pool: CpuReadbackPool::default(),
readback_end: None,
frame_pool: FramePool::new(),
plane_converter,
Expand Down Expand Up @@ -759,7 +813,7 @@ impl MediaFoundationDecoder {
Ok(Some(NV12Sample { pts, data: data? }))
}

unsafe fn map_staging(&self, staging: &ID3D11Texture2D) -> Result<NV12Data, String> {
unsafe fn map_staging(&mut self, staging: &ID3D11Texture2D) -> Result<NV12Data, String> {
let mut mapped = D3D11_MAPPED_SUBRESOURCE::default();
unsafe {
self.d3d11_context
Expand All @@ -775,9 +829,12 @@ impl MediaFoundationDecoder {
let uv_size = (y_stride * uv_height) as usize;
let total_size = y_size + uv_size;

let mut data = vec![0u8; total_size];
let mut data = self.cpu_readback_pool.acquire(total_size);
// SAFETY: the mapped NV12 resource contains `total_size` bytes and the pool reserves that
// much destination capacity. The copy initializes every byte before setting the length.
unsafe {
std::ptr::copy_nonoverlapping(mapped.pData as *const u8, data.as_mut_ptr(), total_size);
data.set_len(total_size);
self.d3d11_context.Unmap(staging, 0);
}

Expand All @@ -800,6 +857,10 @@ impl MediaFoundationDecoder {
}
}

pub fn recycle_nv12_buffer(&mut self, buffer: Arc<Vec<u8>>) {
self.cpu_readback_pool.recycle(buffer);
}

unsafe fn read_decoder_surface(&mut self) -> Result<Option<DecoderSurface>, String> {
let mut stream_index = 0u32;
let mut flags = 0u32;
Expand Down Expand Up @@ -1181,6 +1242,56 @@ unsafe impl Send for MediaFoundationDecoder {}
mod tests {
use super::*;

#[test]
fn cpu_readback_pool_reuses_recycled_buffers() {
let mut pool = CpuReadbackPool::default();
let mut buffer = pool.acquire(16);
buffer.resize(16, 7);
let pointer = buffer.as_ptr();
pool.recycle(Arc::new(buffer));

let reused = pool.acquire(8);
assert_eq!(reused.as_ptr(), pointer);
assert!(reused.is_empty());
}

#[test]
fn cpu_readback_pool_handles_changed_buffer_sizes() {
let mut pool = CpuReadbackPool::default();
let mut buffer = pool.acquire(16);
buffer.resize(16, 7);
pool.recycle(Arc::new(buffer));

let mut grown = pool.acquire(64);
assert!(grown.capacity() >= 64);
assert!(grown.is_empty());
grown.resize(64, 9);
let pointer = grown.as_ptr();
pool.recycle(Arc::new(grown));

let reduced = pool.acquire(8);
assert_eq!(reduced.as_ptr(), pointer);
assert!(reduced.is_empty());
}

#[test]
fn cpu_readback_pool_waits_for_shared_buffers_to_be_released() {
let mut pool = CpuReadbackPool::default();
let buffer = Arc::new(vec![7; 16]);
let pointer = buffer.as_ptr();
let renderer_reference = Arc::clone(&buffer);
pool.recycle(buffer);

let separate = pool.acquire(16);
assert_ne!(separate.as_ptr(), pointer);
drop(separate);
drop(renderer_reference);

let reused = pool.acquire(8);
assert_eq!(reused.as_ptr(), pointer);
assert!(reused.is_empty());
}

#[test]
#[ignore = "requires a Windows D3D11 device"]
fn repeatedly_releases_decoder_objects_before_com_shutdown() {
Expand Down
11 changes: 11 additions & 0 deletions scripts/linux-desktop-harness/arch-up.sh
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,17 @@ debug { disable_logs = false }
exec-once = sh -c '$export_session'
exec-once = waybar
CONF
cat >"$HOME/.config/hypr/hyprland.lua" <<LUA
hl.monitor({ output = "", mode = "1920x1080", position = "0x0", scale = 1 })
hl.config({
misc = { disable_hyprland_logo = true },
debug = { disable_logs = false, enable_stdout_logs = true },
})
hl.on("hyprland.start", function()
hl.exec_cmd("sh -c '$export_session'")
hl.exec_cmd("waybar")
end)
LUA
# The screen-share picker: answer with the one screen, as a person would.
cat >"$HOME/.config/hypr/xdph.conf" <<CONF
screencopy {
Expand Down
8 changes: 7 additions & 1 deletion scripts/linux-desktop-harness/scenario-screenshot.sh
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,12 @@ export XDG_RUNTIME_DIR=/run/user/$(id -u)
export DBUS_SESSION_BUS_ADDRESS=unix:path=$XDG_RUNTIME_DIR/bus
out=${HARNESS_OUT:-/out}
eval "$(systemctl --user show-environment | grep -E "^(WAYLAND_DISPLAY|XDG_SESSION_TYPE|XDG_CURRENT_DESKTOP|XDG_SESSION_DESKTOP|LIBGL_ALWAYS_SOFTWARE|HYPRLAND_INSTANCE_SIGNATURE|NIRI_SOCKET)=" | sed 's/^/export /')"
expected_size=${SCREEN:-1920x1080}
if [[ -n ${HYPRLAND_INSTANCE_SIGNATURE:-} ]]; then
expected_size=$(hyprctl -j monitors | python3 -c 'import json, sys
monitor, = json.load(sys.stdin)
print("{}x{}".format(monitor["width"], monitor["height"]))') || exit 1
fi
: >"$out/result.txt"
result() { printf '%s=%s\n' "$1" "$2" >>"$out/result.txt"; }

Expand Down Expand Up @@ -81,7 +87,7 @@ if data[:8] == b"\x89PNG\r\n\x1a\n":
print(*struct.unpack(">II", data[16:24]))' "$shot")
echo "screenshot: ${shot:-none} ${size:-}" >>"$out/actions.log"
result screenshot_taken "$([[ -n $size ]] && echo yes || echo no)"
result screenshot_size "$([[ ${size// /x} == "${SCREEN:-1920x1080}" ]] && echo yes || echo "${size// /x}")"
result screenshot_size "$([[ ${size// /x} == "$expected_size" ]] && echo yes || echo "${size// /x}")"
result capture_failed "$(grep -ac 'screenshot capture failed' "$out/cap.log")"
if [[ -z $shot ]]; then
find "$HOME" /tmp -newer "$out/profile/store" -iname "Screenshot*.png" -printf "portal file: %s bytes %p\n" 2>/dev/null >>"$out/actions.log"
Expand Down
Loading