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
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,8 @@ Solo con `--features devtools`:

| Argumentos | Qué hace |
| --- | --- |
| `--test <seg> <carpeta> [game\|desktop\|mic\|juegos\|720\|1080\|1440]` | Graba, guarda un clip y sale (imprime el encoder y el juego detectado; un número elige la resolución del clip). Con la variable `CLIPPY_CPU_ENCODER=1`, codifica con el procesador como en una placa sin encoder; con `CLIPPY_TEST_LOST=<seg>`, a esos segundos se pierde la placa una vez, como en un reinicio del driver. |
| `--test <seg> <carpeta> [game\|desktop\|mic\|juegos\|720\|1080\|1440]` | Graba, guarda un clip y sale (imprime el encoder y el juego detectado; un número elige la resolución del clip). Con la variable `CLIPPY_CPU_ENCODER=1`, codifica con el procesador como en una placa sin encoder; con `CLIPPY_TEST_LOST=<seg>`, a esos segundos se pierde la placa una vez, como en un reinicio del driver; con `CLIPPY_TEST_STALL=<seg>`, la captura se traba pasado ese tiempo. |
| `--test-fullscreen <ancho>x<alto> <seg> [alttab]` | Un juego de mentira en pantalla completa exclusiva (cambia el modo de video, como una resolución estirada); con `alttab`, sale y vuelve cada 6 s. Corré una copia del exe con otro nombre para que cuente como juego. |
| `--test-mic` | Cuánto audio entrega cada micrófono en 3 s. |
| `--test-download` | Descarga la versión publicada como el botón "Actualizar". |
| `--test-export`, `--test-frame`, `--test-strip` | Pruebas del editor (ver `src/editor/devtools.rs`). |
Expand Down
108 changes: 108 additions & 0 deletions src/devtools.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,13 @@
//! - `--test <segundos> <carpeta> [game|desktop|mic|juegos|resolución]`: graba, guarda un clip y sale. Con
//! `CLIPPY_TEST_ALIGN16=1`, el encoder falla con tamaños que no son múltiplo de 16 (`--test 8 <carpeta> 766`).
//! Con `CLIPPY_TEST_LOST=<segundos>`, a esos segundos se pierde la placa una vez, como en un reinicio del driver.
//! Con `CLIPPY_TEST_STALL=<segundos>`, pasado ese tiempo la captura se traba (la duplicación se pierde apenas se abre).
//! - `--test-mic`: cuánto audio entrega cada micrófono en 3 s.
//! - `--test-download`: descarga la versión publicada como el botón "Actualizar".
//! - `--test-export`, `--test-frame`, `--test-strip`, `--test-covers`: ver `editor::devtools`.
//! - `--test-fullscreen <ancho>x<alto> <segundos> [alttab]`: un juego de mentira en pantalla completa exclusiva (D3D11,
//! cambia el modo de video como una resolución estirada) que cambia de color en cada cuadro; con `alttab`, cada 6 s
//! sale 2 s y vuelve. Para que cuente como juego, corré una copia del exe con otro nombre ("clippy" no es juego).

use std::sync::Arc;
use std::time::Duration;
Expand All @@ -18,6 +22,9 @@ pub fn run(args: &[String]) -> Option<i32> {
if at("--test-download").is_some() {
return Some(test_download());
}
if let Some(i) = at("--test-fullscreen") {
return Some(test_fullscreen(&args[i + 1..]));
}
if at("--test-mic").is_some() {
return Some(test_mic());
}
Expand Down Expand Up @@ -127,3 +134,104 @@ fn test_mode(args: &[String]) -> i32 {
println!("ERROR timeout");
2
}

fn test_fullscreen(args: &[String]) -> i32 {
use windows::core::w;
use windows::Win32::Foundation::{HMODULE, HWND, LPARAM, LRESULT, WPARAM};
use windows::Win32::Graphics::Direct3D::D3D_DRIVER_TYPE_HARDWARE;
use windows::Win32::Graphics::Direct3D11::*;
use windows::Win32::Graphics::Dxgi::Common::*;
use windows::Win32::Graphics::Dxgi::*;
use windows::Win32::System::LibraryLoader::GetModuleHandleW;
use windows::Win32::UI::WindowsAndMessaging::*;

extern "system" fn proc(h: HWND, m: u32, wp: WPARAM, lp: LPARAM) -> LRESULT {
unsafe { DefWindowProcW(h, m, wp, lp) }
}
let size = args.first().and_then(|s| s.split_once('x')).and_then(|(a, b)| Some((a.parse().ok()?, b.parse().ok()?)));
let (w, h): (u32, u32) = size.unwrap_or((1920, 1080));
let secs: u64 = args.get(1).and_then(|s| s.parse().ok()).unwrap_or(10);
unsafe {
let inst = GetModuleHandleW(None).unwrap();
let class = w!("ClippyPruebaPantallaCompleta");
RegisterClassW(&WNDCLASSW { lpfnWndProc: Some(proc), hInstance: inst.into(), lpszClassName: class, ..Default::default() });
let hwnd = CreateWindowExW(WINDOW_EX_STYLE(0), class, class, WS_POPUP | WS_VISIBLE, 0, 0, w as i32, h as i32, None, None, inst, None).unwrap();
let _ = SetForegroundWindow(hwnd);
let mode = DXGI_MODE_DESC {
Width: w,
Height: h,
RefreshRate: DXGI_RATIONAL { Numerator: 60, Denominator: 1 },
Format: DXGI_FORMAT_B8G8R8A8_UNORM,
..Default::default()
};
let desc = DXGI_SWAP_CHAIN_DESC {
BufferDesc: mode,
SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 },
BufferUsage: DXGI_USAGE_RENDER_TARGET_OUTPUT,
BufferCount: 2,
OutputWindow: hwnd,
Windowed: true.into(),
SwapEffect: DXGI_SWAP_EFFECT_DISCARD,
Flags: DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH.0 as u32,
};
let (mut sc, mut dev, mut ctx) = (None, None, None);
D3D11CreateDeviceAndSwapChain(
None,
D3D_DRIVER_TYPE_HARDWARE,
HMODULE::default(),
D3D11_CREATE_DEVICE_FLAG(0),
None,
D3D11_SDK_VERSION,
Some(&desc),
Some(&mut sc),
Some(&mut dev),
None,
Some(&mut ctx),
)
.unwrap();
let (sc, dev, ctx): (IDXGISwapChain, ID3D11Device, ID3D11DeviceContext) = (sc.unwrap(), dev.unwrap(), ctx.unwrap());
println!("pantalla completa: {:?}", sc.SetFullscreenState(true, None));
println!("modo {w}x{h}: {:?}", sc.ResizeTarget(&mode));
// Con "alttab", cada 6 s sale 2 s de la pantalla completa (minimizado), como un Alt+Tab, y vuelve.
let alttab = args.get(2).is_some_and(|a| a == "alttab");
let mut out = false;
let start = std::time::Instant::now();
let mut frame = 0u64;
while start.elapsed() < Duration::from_secs(secs) {
let mut msg = MSG::default();
while PeekMessageW(&mut msg, None, 0, 0, PM_REMOVE).as_bool() {
let _ = TranslateMessage(&msg);
DispatchMessageW(&msg);
}
let secs_in = start.elapsed().as_secs_f32();
let want_out = alttab && secs_in > 3.0 && secs_in % 6.0 >= 4.0;
if want_out != out {
out = want_out;
if out {
let _ = sc.SetFullscreenState(false, None);
let _ = ShowWindow(hwnd, SW_MINIMIZE);
} else {
let _ = ShowWindow(hwnd, SW_RESTORE);
let _ = SetForegroundWindow(hwnd);
let _ = sc.SetFullscreenState(true, None);
let _ = sc.ResizeTarget(&mode);
}
println!("{:.1} s: {}", secs_in, if out { "Alt+Tab afuera" } else { "vuelve al juego" });
}
let d = sc.GetDesc().unwrap_or_default();
if (d.BufferDesc.Width, d.BufferDesc.Height) != (w, h) {
let _ = sc.ResizeBuffers(0, w, h, DXGI_FORMAT_UNKNOWN, DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH);
}
let back: ID3D11Texture2D = sc.GetBuffer(0).unwrap();
let mut rtv = None;
dev.CreateRenderTargetView(&back, None, Some(&mut rtv)).unwrap();
let t = start.elapsed().as_secs_f32();
ctx.ClearRenderTargetView(&rtv.unwrap(), &[(t * 0.7).fract(), 0.2, (t * 0.3).fract(), 1.0]);
let _ = sc.Present(1, DXGI_PRESENT(0));
frame += 1;
}
let _ = sc.SetFullscreenState(false, None);
println!("{frame} cuadros en {secs} s");
}
0
}
67 changes: 65 additions & 2 deletions src/record/capture.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,11 @@ const QUICK_RETRY: i64 = 2_500_000;
const QUICK_FOR: i64 = 30_000_000;
const RETRY: i64 = 50_000_000;

/// Un juego adelante manda imágenes todo el tiempo: si pasa esto sin ninguna nueva, la captura quedó trabada (100 ns).
const STALL: i64 = 50_000_000;
/// Imágenes nuevas que tiene que haber recibido una sesión para darla por andando (2 s a 60 fps).
const WORKED: u32 = 120;

/// Qué hizo `Capture::aim`.
pub enum Aim {
/// Sigue igual (ya era ese monitor, o no se puede cambiar sin reiniciar y no hacía falta).
Expand Down Expand Up @@ -91,12 +96,19 @@ pub struct Capture {
skipped: Option<HMONITOR>,
/// Monitores que hicieron perder la placa al pasar a ellos: no se vuelven a probar.
lost_on: Vec<HMONITOR>,
/// Imágenes nuevas recibidas en la sesión (hasta `WORKED`), cuándo llegó la última y cuántas veces se perdió
/// la duplicación desde entonces.
new_frames: u32,
last_new: i64,
dup_lost: u32,
}

impl Capture {
/// Captura `monitor` (si no hay, ya no existe o está en `lost_on`, el principal u otro). Prueba cada GPU que lo ve:
/// en notebooks con dos GPUs la que lo enumera primero no siempre puede duplicarlo.
pub fn new(monitor: Option<HMONITOR>, lost_on: &[HMONITOR]) -> Result<Self> {
#[cfg(feature = "devtools")]
SESSIONS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
let factory: IDXGIFactory1 = unsafe { CreateDXGIFactory1()? };
let mut all = Vec::new();
let mut i = 0;
Expand Down Expand Up @@ -161,12 +173,31 @@ impl Capture {
failing: false,
skipped: None,
lost_on: lost_on.to_vec(),
new_frames: 0,
last_new: 0,
dup_lost: 0,
};
cap.open()?;
Ok(cap)
}
}

/// El monitor que se graba.
pub fn monitor(&self) -> HMONITOR {
self.out.monitor
}

/// Si desde `since` (o desde la última imagen nueva, si es después) pasaron `STALL` sin ninguna imagen nueva,
/// cuántas veces se perdió la duplicación en ese tiempo.
pub fn stalled(&self, now: i64, since: i64) -> Option<u32> {
(now - self.last_new.max(since) > STALL).then_some(self.dup_lost)
}

/// La sesión llegó a capturar (si después se traba, es que algo la trabó, no que nunca anduvo).
pub fn worked(&self) -> bool {
self.new_frames >= WORKED
}

/// "\\.\DISPLAY2 (NVIDIA GeForce RTX 2060)", para el log.
pub fn describe(&self) -> String {
format!("{} ({})", self.out.name, self.gpu)
Expand Down Expand Up @@ -301,7 +332,10 @@ impl Capture {
let dup = self.dup.clone().unwrap();
let mut info = DXGI_OUTDUPL_FRAME_INFO::default();
let mut res: Option<IDXGIResource> = None;
match unsafe { dup.AcquireNextFrame(0, &mut info, &mut res) } {
let got = unsafe { dup.AcquireNextFrame(0, &mut info, &mut res) };
#[cfg(feature = "devtools")]
let got = test_stall(now, got, &dup);
match got {
Ok(()) => {
let r = if info.LastPresentTime != 0 {
match res {
Expand All @@ -315,13 +349,21 @@ impl Capture {
let _ = dup.ReleaseFrame();
}
self.check(r)?;
if info.LastPresentTime != 0 {
self.new_frames = (self.new_frames + 1).min(WORKED);
(self.last_new, self.dup_lost) = (now, 0);
}
}
Err(e) if e.code() == DXGI_ERROR_WAIT_TIMEOUT => {}
Err(e) => {
if let Some(why) = self.removed() {
return Err(self.lost(&why, &e));
}
if e.code() != DXGI_ERROR_ACCESS_LOST {
// Se pierde en cada cambio de modo o Alt+Tab y se reabre en el cuadro siguiente. Si queda trabada,
// lo nota `stalled`.
if e.code() == DXGI_ERROR_ACCESS_LOST {
self.dup_lost += 1;
} else {
log(&format!("duplicación de {}: {e}", self.out.name));
}
self.dup = None;
Expand Down Expand Up @@ -376,6 +418,27 @@ fn test_lost(now: i64) -> bool {
at.is_some_and(|s| now >= s * 10_000_000) && !DONE.swap(true, Ordering::Relaxed)
}

/// Prueba: cuántas veces se creó la captura (la primera sesión es la que se traba con `CLIPPY_TEST_STALL`).
#[cfg(feature = "devtools")]
static SESSIONS: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);

/// Prueba (CLIPPY_TEST_STALL=<segundos>): pasado ese tiempo de la primera sesión, la duplicación se pierde apenas se
/// abre, como con algunos juegos en pantalla completa exclusiva en Windows 11 24H2.
#[cfg(feature = "devtools")]
fn test_stall(now: i64, got: windows::core::Result<()>, dup: &IDXGIOutputDuplication) -> windows::core::Result<()> {
let after = std::env::var("CLIPPY_TEST_STALL").ok().and_then(|s| s.parse::<i64>().ok());
let first = SESSIONS.load(std::sync::atomic::Ordering::Relaxed) == 1;
if !after.is_some_and(|s| first && now >= s * 10_000_000) {
return got;
}
if got.is_ok() {
unsafe {
let _ = dup.ReleaseFrame();
}
}
Err(DXGI_ERROR_ACCESS_LOST.into())
}

/// Monitores conectados al escritorio que ve esta GPU.
fn outputs(adapter: &IDXGIAdapter1) -> Vec<Output> {
let screens = screen::all();
Expand Down
5 changes: 5 additions & 0 deletions src/record/game.rs
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,11 @@ impl Detector {
}
}

/// Monitor del juego si está adelante en pantalla completa ahora mismo (ahí manda imágenes todo el tiempo).
pub fn front_monitor(&self) -> Option<HMONITOR> {
self.monitor().filter(|_| self.in_front)
}

/// El juego se ve en su monitor: está adelante, o la ventana activa está en otro monitor
/// (con dos o más pantallas, mirar Discord en la otra no tapa el juego).
pub fn visible(&self) -> bool {
Expand Down
24 changes: 24 additions & 0 deletions src/record/recorder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -319,6 +319,9 @@ fn session(
let mut next_frame = 0i64;
let mut packets: VecDeque<Packet> = VecDeque::new();
let mut out = Vec::new();
// Desde cuándo el juego está adelante en el monitor que se graba, y si ya se avisó que ahí no llegan imágenes.
let mut front_since: Option<i64> = None;
let mut stall_told = false;

loop {
loop {
Expand Down Expand Up @@ -361,6 +364,27 @@ fn session(
}
}
cap.poll(now)?;
// Un juego adelante manda imágenes todo el tiempo. Si no llega ninguna, la captura quedó trabada (puede pasar
// al volver de un Alt+Tab con resolución estirada): reabrirla con el mismo dispositivo no alcanza y el video
// repetiría la última imagen para siempre. Se empieza de nuevo, como al cambiar un ajuste de video.
if au.game.front_monitor() == Some(cap.monitor()) {
let since = *front_since.get_or_insert(now);
if let Some(lost) = cap.stalled(now, since) {
if cap.worked() {
log(&format!(
"el juego está adelante y no llegan imágenes nuevas de {} (se perdió {lost} veces): se reinicia la captura",
cap.describe()
));
return Ok(End::Restart(cap.monitor()));
}
// Nunca llegó a capturar: reiniciar una y otra vez no lo arreglaría. Queda en el log.
if !std::mem::replace(&mut stall_told, true) {
log(&format!("el juego está adelante y no llegan imágenes nuevas de {} (se perdió {lost} veces)", cap.describe()));
}
}
} else {
front_since = None;
}
if let Some(f) = &cap.latest {
if !conv.as_ref().is_some_and(|c| c.is_for(f)) {
conv = Some(cap.check(Converter::new(&cap.device, &cap.context, f, w, h, fps, 8))?);
Expand Down
Loading