format the rust sources and split the functions that pushed over the line
This commit is contained in:
+7
-4
@@ -18,9 +18,8 @@ fn compile_shaders() {
|
|||||||
clippy::expect_used,
|
clippy::expect_used,
|
||||||
reason = "a build script without OUT_DIR cannot produce a usable build"
|
reason = "a build script without OUT_DIR cannot produce a usable build"
|
||||||
)]
|
)]
|
||||||
let out_dir = PathBuf::from(
|
let out_dir =
|
||||||
std::env::var("OUT_DIR").expect("OUT_DIR is set by cargo for build scripts"),
|
PathBuf::from(std::env::var("OUT_DIR").expect("OUT_DIR is set by cargo for build scripts"));
|
||||||
);
|
|
||||||
let shader_dir = PathBuf::from("shaders");
|
let shader_dir = PathBuf::from("shaders");
|
||||||
|
|
||||||
let fxc = find_fxc();
|
let fxc = find_fxc();
|
||||||
@@ -88,7 +87,11 @@ fn find_fxc() -> Option<PathBuf> {
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
let fxc = entry.path().join("x64").join("fxc.exe");
|
let fxc = entry.path().join("x64").join("fxc.exe");
|
||||||
if fxc.is_file() && best.as_ref().is_none_or(|(b, _)| name.as_str() > b.as_str()) {
|
if fxc.is_file()
|
||||||
|
&& best
|
||||||
|
.as_ref()
|
||||||
|
.is_none_or(|(b, _)| name.as_str() > b.as_str())
|
||||||
|
{
|
||||||
best = Some((name, fxc));
|
best = Some((name, fxc));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+12
-4
@@ -7,8 +7,8 @@ use std::thread::{self, JoinHandle};
|
|||||||
|
|
||||||
use anyhow::{bail, Context, Result};
|
use anyhow::{bail, Context, Result};
|
||||||
use windows::Win32::Media::Audio::{
|
use windows::Win32::Media::Audio::{
|
||||||
eConsole, eRender, IAudioCaptureClient, IAudioClient, IMMDeviceEnumerator,
|
eConsole, eRender, IAudioCaptureClient, IAudioClient, IMMDeviceEnumerator, MMDeviceEnumerator,
|
||||||
MMDeviceEnumerator, WAVEFORMATEX, WAVEFORMATEXTENSIBLE,
|
WAVEFORMATEX, WAVEFORMATEXTENSIBLE,
|
||||||
};
|
};
|
||||||
use windows::Win32::System::Com::{
|
use windows::Win32::System::Com::{
|
||||||
CoCreateInstance, CoInitializeEx, CoTaskMemFree, CLSCTX_ALL, COINIT_APARTMENTTHREADED,
|
CoCreateInstance, CoInitializeEx, CoTaskMemFree, CLSCTX_ALL, COINIT_APARTMENTTHREADED,
|
||||||
@@ -125,7 +125,8 @@ fn parse_format(fmt: &WAVEFORMATEX) -> Result<(u32, u16, u16, bool)> {
|
|||||||
false
|
false
|
||||||
} else if w_format_tag == WAVE_FORMAT_EXTENSIBLE {
|
} else if w_format_tag == WAVE_FORMAT_EXTENSIBLE {
|
||||||
// SAFETY: When wFormatTag is WAVE_FORMAT_EXTENSIBLE, the struct is actually WAVEFORMATEXTENSIBLE.
|
// SAFETY: When wFormatTag is WAVE_FORMAT_EXTENSIBLE, the struct is actually WAVEFORMATEXTENSIBLE.
|
||||||
let ext = unsafe { &*std::ptr::from_ref::<WAVEFORMATEX>(fmt).cast::<WAVEFORMATEXTENSIBLE>() };
|
let ext =
|
||||||
|
unsafe { &*std::ptr::from_ref::<WAVEFORMATEX>(fmt).cast::<WAVEFORMATEXTENSIBLE>() };
|
||||||
// SAFETY: WAVEFORMATEXTENSIBLE contains repr(packed) fields; read_unaligned is required.
|
// SAFETY: WAVEFORMATEXTENSIBLE contains repr(packed) fields; read_unaligned is required.
|
||||||
let sub_fmt = unsafe { std::ptr::read_unaligned(std::ptr::addr_of!(ext.SubFormat)) };
|
let sub_fmt = unsafe { std::ptr::read_unaligned(std::ptr::addr_of!(ext.SubFormat)) };
|
||||||
sub_fmt == windows::core::GUID::from_u128(0x00000003_0000_0010_8000_00aa00389b71)
|
sub_fmt == windows::core::GUID::from_u128(0x00000003_0000_0010_8000_00aa00389b71)
|
||||||
@@ -226,7 +227,14 @@ fn capture_thread(
|
|||||||
// Notify parent that init succeeded.
|
// Notify parent that init succeeded.
|
||||||
drop(init_tx.send(Ok((sample_rate, channels, started_at))));
|
drop(init_tx.send(Ok((sample_rate, channels, started_at))));
|
||||||
|
|
||||||
let result = capture_loop(&running, &capture_client, channels, bits_per_sample, is_float, &mut writer);
|
let result = capture_loop(
|
||||||
|
&running,
|
||||||
|
&capture_client,
|
||||||
|
channels,
|
||||||
|
bits_per_sample,
|
||||||
|
is_float,
|
||||||
|
&mut writer,
|
||||||
|
);
|
||||||
|
|
||||||
// SAFETY: Stops the audio capture stream before tearing down.
|
// SAFETY: Stops the audio capture stream before tearing down.
|
||||||
unsafe {
|
unsafe {
|
||||||
|
|||||||
+13
-12
@@ -147,10 +147,8 @@ where
|
|||||||
.context("invalid dest path for temp archive")?;
|
.context("invalid dest path for temp archive")?;
|
||||||
let scratch_dir = app_dir.join("temp");
|
let scratch_dir = app_dir.join("temp");
|
||||||
fs::create_dir_all(&scratch_dir).context("creating temp dir for archive")?;
|
fs::create_dir_all(&scratch_dir).context("creating temp dir for archive")?;
|
||||||
let archive_path = scratch_dir.join(format!(
|
let archive_path =
|
||||||
"ffmpeg-archive-{}.tmp",
|
scratch_dir.join(format!("ffmpeg-archive-{}.tmp", source.name.to_lowercase()));
|
||||||
source.name.to_lowercase()
|
|
||||||
));
|
|
||||||
|
|
||||||
if let Some(ref hash) = expected {
|
if let Some(ref hash) = expected {
|
||||||
download_verified(
|
download_verified(
|
||||||
@@ -163,7 +161,12 @@ where
|
|||||||
.await
|
.await
|
||||||
.with_context(|| format!("downloading {}", asset.browser_download_url))?;
|
.with_context(|| format!("downloading {}", asset.browser_download_url))?;
|
||||||
} else {
|
} else {
|
||||||
download_plain(&client, &asset.browser_download_url, &archive_path, on_progress)
|
download_plain(
|
||||||
|
&client,
|
||||||
|
&asset.browser_download_url,
|
||||||
|
&archive_path,
|
||||||
|
on_progress,
|
||||||
|
)
|
||||||
.await
|
.await
|
||||||
.with_context(|| format!("downloading {}", asset.browser_download_url))?;
|
.with_context(|| format!("downloading {}", asset.browser_download_url))?;
|
||||||
}
|
}
|
||||||
@@ -244,12 +247,8 @@ async fn pick_asset(client: &reqwest::Client, source: &Source) -> Result<(Github
|
|||||||
.await?
|
.await?
|
||||||
.error_for_status()?;
|
.error_for_status()?;
|
||||||
let body = resp.text().await?;
|
let body = resp.text().await?;
|
||||||
let release: GithubRelease =
|
let release: GithubRelease = serde_json::from_str(&body).context("parsing release metadata")?;
|
||||||
serde_json::from_str(&body).context("parsing release metadata")?;
|
let version = release.tag_name.trim_start_matches('v').to_string();
|
||||||
let version = release
|
|
||||||
.tag_name
|
|
||||||
.trim_start_matches('v')
|
|
||||||
.to_string();
|
|
||||||
let asset = release
|
let asset = release
|
||||||
.assets
|
.assets
|
||||||
.into_iter()
|
.into_iter()
|
||||||
@@ -344,7 +343,9 @@ fn extract_ffmpeg_from_7z(archive_path: &Path, dest: &Path) -> Result<()> {
|
|||||||
bail!("ffmpeg.exe not found inside the 7z archive");
|
bail!("ffmpeg.exe not found inside the 7z archive");
|
||||||
};
|
};
|
||||||
install_from(dest, |staging| {
|
install_from(dest, |staging| {
|
||||||
fs::copy(&src, staging).map(|_| ()).context("write ffmpeg.exe from 7z")
|
fs::copy(&src, staging)
|
||||||
|
.map(|_| ())
|
||||||
|
.context("write ffmpeg.exe from 7z")
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+76
-42
@@ -14,11 +14,11 @@ use windows::Win32::Graphics::Direct3D11::{
|
|||||||
ID3D11Texture2D, ID3D11VertexShader, D3D11_BIND_RENDER_TARGET, D3D11_BIND_SHADER_RESOURCE,
|
ID3D11Texture2D, ID3D11VertexShader, D3D11_BIND_RENDER_TARGET, D3D11_BIND_SHADER_RESOURCE,
|
||||||
D3D11_BIND_VERTEX_BUFFER, D3D11_BUFFER_DESC, D3D11_CPU_ACCESS_READ, D3D11_CULL_NONE,
|
D3D11_BIND_VERTEX_BUFFER, D3D11_BUFFER_DESC, D3D11_CPU_ACCESS_READ, D3D11_CULL_NONE,
|
||||||
D3D11_FILL_SOLID, D3D11_FILTER_MIN_MAG_MIP_POINT, D3D11_INPUT_ELEMENT_DESC,
|
D3D11_FILL_SOLID, D3D11_FILTER_MIN_MAG_MIP_POINT, D3D11_INPUT_ELEMENT_DESC,
|
||||||
D3D11_INPUT_PER_VERTEX_DATA, D3D11_MAP_READ, D3D11_MAPPED_SUBRESOURCE, D3D11_RASTERIZER_DESC,
|
D3D11_INPUT_PER_VERTEX_DATA, D3D11_MAPPED_SUBRESOURCE, D3D11_MAP_READ, D3D11_RASTERIZER_DESC,
|
||||||
D3D11_RENDER_TARGET_VIEW_DESC, D3D11_RTV_DIMENSION_TEXTURE2D, D3D11_SAMPLER_DESC,
|
D3D11_RENDER_TARGET_VIEW_DESC, D3D11_RTV_DIMENSION_TEXTURE2D, D3D11_SAMPLER_DESC,
|
||||||
D3D11_SHADER_RESOURCE_VIEW_DESC, D3D11_SUBRESOURCE_DATA, D3D11_TEXTURE2D_DESC,
|
D3D11_SHADER_RESOURCE_VIEW_DESC, D3D11_SUBRESOURCE_DATA, D3D11_TEX2D_RTV, D3D11_TEX2D_SRV,
|
||||||
D3D11_TEXTURE_ADDRESS_CLAMP, D3D11_TEX2D_RTV, D3D11_TEX2D_SRV, D3D11_USAGE_DEFAULT,
|
D3D11_TEXTURE2D_DESC, D3D11_TEXTURE_ADDRESS_CLAMP, D3D11_USAGE_DEFAULT, D3D11_USAGE_IMMUTABLE,
|
||||||
D3D11_USAGE_IMMUTABLE, D3D11_USAGE_STAGING, D3D11_VIEWPORT,
|
D3D11_USAGE_STAGING, D3D11_VIEWPORT,
|
||||||
};
|
};
|
||||||
use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT_B8G8R8A8_UNORM, DXGI_SAMPLE_DESC};
|
use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT_B8G8R8A8_UNORM, DXGI_SAMPLE_DESC};
|
||||||
use windows_capture::capture::{
|
use windows_capture::capture::{
|
||||||
@@ -150,7 +150,10 @@ fn new_render_target_desc(width: u32, height: u32) -> D3D11_TEXTURE2D_DESC {
|
|||||||
MipLevels: 1,
|
MipLevels: 1,
|
||||||
ArraySize: 1,
|
ArraySize: 1,
|
||||||
Format: DXGI_FORMAT_B8G8R8A8_UNORM,
|
Format: DXGI_FORMAT_B8G8R8A8_UNORM,
|
||||||
SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 },
|
SampleDesc: DXGI_SAMPLE_DESC {
|
||||||
|
Count: 1,
|
||||||
|
Quality: 0,
|
||||||
|
},
|
||||||
Usage: D3D11_USAGE_DEFAULT,
|
Usage: D3D11_USAGE_DEFAULT,
|
||||||
BindFlags: (D3D11_BIND_RENDER_TARGET.0 | D3D11_BIND_SHADER_RESOURCE.0) as u32,
|
BindFlags: (D3D11_BIND_RENDER_TARGET.0 | D3D11_BIND_SHADER_RESOURCE.0) as u32,
|
||||||
CPUAccessFlags: 0,
|
CPUAccessFlags: 0,
|
||||||
@@ -176,7 +179,10 @@ fn new_staging_desc(width: u32, height: u32) -> D3D11_TEXTURE2D_DESC {
|
|||||||
MipLevels: 1,
|
MipLevels: 1,
|
||||||
ArraySize: 1,
|
ArraySize: 1,
|
||||||
Format: DXGI_FORMAT_B8G8R8A8_UNORM,
|
Format: DXGI_FORMAT_B8G8R8A8_UNORM,
|
||||||
SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 },
|
SampleDesc: DXGI_SAMPLE_DESC {
|
||||||
|
Count: 1,
|
||||||
|
Quality: 0,
|
||||||
|
},
|
||||||
Usage: D3D11_USAGE_STAGING,
|
Usage: D3D11_USAGE_STAGING,
|
||||||
BindFlags: 0,
|
BindFlags: 0,
|
||||||
CPUAccessFlags: D3D11_CPU_ACCESS_READ.0 as u32,
|
CPUAccessFlags: D3D11_CPU_ACCESS_READ.0 as u32,
|
||||||
@@ -211,30 +217,11 @@ fn new_vertex_buffer() -> (D3D11_BUFFER_DESC, D3D11_SUBRESOURCE_DATA) {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
impl TonemapPipeline {
|
/// Vertex-input description matching the vertex shader's signature: position at
|
||||||
fn new(device: &ID3D11Device, width: u32, height: u32) -> Result<Self> {
|
/// offset 0, texture coordinates at 8. `CreateInputLayout` validates it against
|
||||||
// build.rs emits empty .cso files when fxc was missing at build time.
|
/// the compiled bytecode, so a mismatch fails loudly rather than reading garbage.
|
||||||
// Without this the only symptom is an opaque CreateVertexShader failure
|
fn new_input_elements() -> [D3D11_INPUT_ELEMENT_DESC; 2] {
|
||||||
// on the first frame of every recording.
|
[
|
||||||
if FULLSCREEN_VS.is_empty() || TONEMAP_PS.is_empty() {
|
|
||||||
bail!(
|
|
||||||
"shader bytecode is empty - rebuild with the Windows SDK installed so build.rs can run fxc"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Vertex shader: fullscreen-triangle pass-through (no vertex buffer).
|
|
||||||
let mut vs = None;
|
|
||||||
unsafe {
|
|
||||||
// SAFETY: `device` is the live ID3D11Device owned by the capture
|
|
||||||
// frame. FULLSCREEN_VS is bytecode embedded at build time, and the
|
|
||||||
// out-param points at a local Option the call writes through.
|
|
||||||
device.CreateVertexShader(FULLSCREEN_VS, None, Some(&raw mut vs))?;
|
|
||||||
}
|
|
||||||
let vs = vs.ok_or_else(|| anyhow!("CreateVertexShader returned null"))?;
|
|
||||||
|
|
||||||
// Input layout matching the VS signature (POSITION float2, TEXCOORD float2).
|
|
||||||
// Validated against the VS bytecode by CreateInputLayout.
|
|
||||||
let input_elements = [
|
|
||||||
D3D11_INPUT_ELEMENT_DESC {
|
D3D11_INPUT_ELEMENT_DESC {
|
||||||
SemanticName: windows::core::PCSTR(c"POSITION".as_ptr().cast()),
|
SemanticName: windows::core::PCSTR(c"POSITION".as_ptr().cast()),
|
||||||
SemanticIndex: 0,
|
SemanticIndex: 0,
|
||||||
@@ -253,7 +240,38 @@ impl TonemapPipeline {
|
|||||||
InputSlotClass: D3D11_INPUT_PER_VERTEX_DATA,
|
InputSlotClass: D3D11_INPUT_PER_VERTEX_DATA,
|
||||||
InstanceDataStepRate: 0,
|
InstanceDataStepRate: 0,
|
||||||
},
|
},
|
||||||
];
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
/// build.rs emits empty .cso files when fxc was missing at build time. Checked
|
||||||
|
/// once per pipeline rather than left to fail inside `CreateVertexShader`, which
|
||||||
|
/// reports it as an opaque HRESULT on the first frame of every recording.
|
||||||
|
fn ensure_shaders_compiled() -> Result<()> {
|
||||||
|
if FULLSCREEN_VS.is_empty() || TONEMAP_PS.is_empty() {
|
||||||
|
bail!(
|
||||||
|
"shader bytecode is empty - rebuild with the Windows SDK installed so build.rs can run fxc"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
impl TonemapPipeline {
|
||||||
|
fn new(device: &ID3D11Device, width: u32, height: u32) -> Result<Self> {
|
||||||
|
ensure_shaders_compiled()?;
|
||||||
|
|
||||||
|
// Vertex shader: fullscreen-triangle pass-through (no vertex buffer).
|
||||||
|
let mut vs = None;
|
||||||
|
unsafe {
|
||||||
|
// SAFETY: `device` is the live ID3D11Device owned by the capture
|
||||||
|
// frame. FULLSCREEN_VS is bytecode embedded at build time, and the
|
||||||
|
// out-param points at a local Option the call writes through.
|
||||||
|
device.CreateVertexShader(FULLSCREEN_VS, None, Some(&raw mut vs))?;
|
||||||
|
}
|
||||||
|
let vs = vs.ok_or_else(|| anyhow!("CreateVertexShader returned null"))?;
|
||||||
|
|
||||||
|
// Input layout matching the VS signature (POSITION float2, TEXCOORD float2).
|
||||||
|
// Validated against the VS bytecode by CreateInputLayout.
|
||||||
|
let input_elements = new_input_elements();
|
||||||
let mut input_layout = None;
|
let mut input_layout = None;
|
||||||
unsafe {
|
unsafe {
|
||||||
// SAFETY: the element descriptions and the vertex-shader bytecode
|
// SAFETY: the element descriptions and the vertex-shader bytecode
|
||||||
@@ -265,16 +283,22 @@ impl TonemapPipeline {
|
|||||||
Some(&raw mut input_layout),
|
Some(&raw mut input_layout),
|
||||||
)?;
|
)?;
|
||||||
}
|
}
|
||||||
let input_layout = input_layout.ok_or_else(|| anyhow!("CreateInputLayout returned null"))?;
|
let input_layout =
|
||||||
|
input_layout.ok_or_else(|| anyhow!("CreateInputLayout returned null"))?;
|
||||||
|
|
||||||
let (vb_desc, vb_init) = new_vertex_buffer();
|
let (vb_desc, vb_init) = new_vertex_buffer();
|
||||||
let mut vertex_buffer = None;
|
let mut vertex_buffer = None;
|
||||||
unsafe {
|
unsafe {
|
||||||
// SAFETY: both descriptions are stack locals that outlive the call,
|
// SAFETY: both descriptions are stack locals that outlive the call,
|
||||||
// and vb_init.pSysMem points at the `verts` array declared above.
|
// and vb_init.pSysMem points at the `verts` array declared above.
|
||||||
device.CreateBuffer(&raw const vb_desc, Some(&raw const vb_init), Some(&raw mut vertex_buffer))?;
|
device.CreateBuffer(
|
||||||
|
&raw const vb_desc,
|
||||||
|
Some(&raw const vb_init),
|
||||||
|
Some(&raw mut vertex_buffer),
|
||||||
|
)?;
|
||||||
}
|
}
|
||||||
let vertex_buffer = vertex_buffer.ok_or_else(|| anyhow!("CreateBuffer vb returned null"))?;
|
let vertex_buffer =
|
||||||
|
vertex_buffer.ok_or_else(|| anyhow!("CreateBuffer vb returned null"))?;
|
||||||
|
|
||||||
// Pixel shader: Hable tonemap + bt709 OETF.
|
// Pixel shader: Hable tonemap + bt709 OETF.
|
||||||
let mut ps = None;
|
let mut ps = None;
|
||||||
@@ -310,14 +334,19 @@ impl TonemapPipeline {
|
|||||||
// out-param is a local Option.
|
// out-param is a local Option.
|
||||||
device.CreateTexture2D(&raw const rt_desc, None, Some(&raw mut render_target))?;
|
device.CreateTexture2D(&raw const rt_desc, None, Some(&raw mut render_target))?;
|
||||||
}
|
}
|
||||||
let render_target = render_target.ok_or_else(|| anyhow!("CreateTexture2D rt returned null"))?;
|
let render_target =
|
||||||
|
render_target.ok_or_else(|| anyhow!("CreateTexture2D rt returned null"))?;
|
||||||
|
|
||||||
let view_desc = new_render_target_view_desc();
|
let view_desc = new_render_target_view_desc();
|
||||||
let mut rtv = None;
|
let mut rtv = None;
|
||||||
unsafe {
|
unsafe {
|
||||||
// SAFETY: render_target was just created on this device and
|
// SAFETY: render_target was just created on this device and
|
||||||
// view_desc describes a valid subresource of it.
|
// view_desc describes a valid subresource of it.
|
||||||
device.CreateRenderTargetView(&render_target, Some(&raw const view_desc), Some(&raw mut rtv))?;
|
device.CreateRenderTargetView(
|
||||||
|
&render_target,
|
||||||
|
Some(&raw const view_desc),
|
||||||
|
Some(&raw mut rtv),
|
||||||
|
)?;
|
||||||
}
|
}
|
||||||
let rtv = rtv.ok_or_else(|| anyhow!("CreateRenderTargetView returned null"))?;
|
let rtv = rtv.ok_or_else(|| anyhow!("CreateRenderTargetView returned null"))?;
|
||||||
|
|
||||||
@@ -369,7 +398,10 @@ impl TonemapPipeline {
|
|||||||
// Resize - rebuild the RT/staging at the new dimensions.
|
// Resize - rebuild the RT/staging at the new dimensions.
|
||||||
tracing::info!(
|
tracing::info!(
|
||||||
"tonemap pipeline resize: {}x{} -> {}x{}",
|
"tonemap pipeline resize: {}x{} -> {}x{}",
|
||||||
self.width, self.height, desc.Width, desc.Height
|
self.width,
|
||||||
|
self.height,
|
||||||
|
desc.Width,
|
||||||
|
desc.Height
|
||||||
);
|
);
|
||||||
*self = Self::new(device, desc.Width, desc.Height)?;
|
*self = Self::new(device, desc.Width, desc.Height)?;
|
||||||
}
|
}
|
||||||
@@ -545,7 +577,9 @@ impl GraphicsCaptureApiHandler for CaptureHandler {
|
|||||||
|
|
||||||
tracing::info!(
|
tracing::info!(
|
||||||
"capture: size={}x{} pipe_fps={}",
|
"capture: size={}x{} pipe_fps={}",
|
||||||
setup.width, setup.height, setup.pipe_fps
|
setup.width,
|
||||||
|
setup.height,
|
||||||
|
setup.pipe_fps
|
||||||
);
|
);
|
||||||
|
|
||||||
let mut cmd = Command::new(&setup.ffmpeg_path);
|
let mut cmd = Command::new(&setup.ffmpeg_path);
|
||||||
@@ -622,12 +656,12 @@ impl GraphicsCaptureApiHandler for CaptureHandler {
|
|||||||
.ok_or_else(|| anyhow!("tonemap pipeline missing after initialization"))?;
|
.ok_or_else(|| anyhow!("tonemap pipeline missing after initialization"))?;
|
||||||
pipeline.process(device, context, src, stdin)?;
|
pipeline.process(device, context, src, stdin)?;
|
||||||
|
|
||||||
self.frame_count.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
self.frame_count
|
||||||
|
.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
impl Drop for CaptureHandler {
|
impl Drop for CaptureHandler {
|
||||||
fn drop(&mut self) {
|
fn drop(&mut self) {
|
||||||
drop(self.stdin.take());
|
drop(self.stdin.take());
|
||||||
@@ -777,8 +811,8 @@ pub(crate) fn start(
|
|||||||
setup,
|
setup,
|
||||||
);
|
);
|
||||||
|
|
||||||
let control = CaptureHandler::start_free_threaded(settings)
|
let control =
|
||||||
.map_err(|e| anyhow!("capture start: {e}"))?;
|
CaptureHandler::start_free_threaded(settings).map_err(|e| anyhow!("capture start: {e}"))?;
|
||||||
|
|
||||||
Ok(CaptureSession {
|
Ok(CaptureSession {
|
||||||
output_path,
|
output_path,
|
||||||
|
|||||||
@@ -97,9 +97,6 @@ impl ClickRecorder {
|
|||||||
if let Some(t) = self.thread.take() {
|
if let Some(t) = self.thread.take() {
|
||||||
drop(t.join());
|
drop(t.join());
|
||||||
}
|
}
|
||||||
self.clicks
|
self.clicks.lock().map(|v| v.clone()).unwrap_or_default()
|
||||||
.lock()
|
|
||||||
.map(|v| v.clone())
|
|
||||||
.unwrap_or_default()
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+17
-8
@@ -157,7 +157,9 @@ impl Default for CaptureConfig {
|
|||||||
|
|
||||||
impl Default for UpdatesConfig {
|
impl Default for UpdatesConfig {
|
||||||
fn default() -> Self {
|
fn default() -> Self {
|
||||||
Self { check_on_launch: true }
|
Self {
|
||||||
|
check_on_launch: true,
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -213,9 +215,7 @@ impl Config {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub fn needs_first_run(&self) -> bool {
|
pub fn needs_first_run(&self) -> bool {
|
||||||
self.hotkeys.start.is_none()
|
self.hotkeys.start.is_none() || self.hotkeys.stop.is_none() || self.hotkeys.pause.is_none()
|
||||||
|| self.hotkeys.stop.is_none()
|
|
||||||
|| self.hotkeys.pause.is_none()
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -230,16 +230,23 @@ pub(crate) fn config_path(app_dir: &Path) -> PathBuf {
|
|||||||
/// name has no timestamp and is kept as the most recent safety net).
|
/// name has no timestamp and is kept as the most recent safety net).
|
||||||
fn sweep_stale_backups(config_path: &Path) {
|
fn sweep_stale_backups(config_path: &Path) {
|
||||||
const MAX_AGE_SECS: u64 = 30 * 24 * 3600;
|
const MAX_AGE_SECS: u64 = 30 * 24 * 3600;
|
||||||
let Some(dir) = config_path.parent() else { return };
|
let Some(dir) = config_path.parent() else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
let now = std::time::SystemTime::now()
|
let now = std::time::SystemTime::now()
|
||||||
.duration_since(std::time::UNIX_EPOCH)
|
.duration_since(std::time::UNIX_EPOCH)
|
||||||
.map_or(0, |d| d.as_secs());
|
.map_or(0, |d| d.as_secs());
|
||||||
let Ok(entries) = std::fs::read_dir(dir) else { return };
|
let Ok(entries) = std::fs::read_dir(dir) else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
for entry in entries.flatten() {
|
for entry in entries.flatten() {
|
||||||
let name = entry.file_name();
|
let name = entry.file_name();
|
||||||
let Some(name) = name.to_str() else { continue };
|
let Some(name) = name.to_str() else { continue };
|
||||||
// Match config-{digits}.toml.bak - extract the unix secs and age it out.
|
// Match config-{digits}.toml.bak - extract the unix secs and age it out.
|
||||||
if let Some(rest) = name.strip_prefix("config-").and_then(|s| s.strip_suffix(".toml.bak")) {
|
if let Some(rest) = name
|
||||||
|
.strip_prefix("config-")
|
||||||
|
.and_then(|s| s.strip_suffix(".toml.bak"))
|
||||||
|
{
|
||||||
if let Ok(ts) = rest.parse::<u64>() {
|
if let Ok(ts) = rest.parse::<u64>() {
|
||||||
if now.saturating_sub(ts) > MAX_AGE_SECS {
|
if now.saturating_sub(ts) > MAX_AGE_SECS {
|
||||||
drop(std::fs::remove_file(entry.path()));
|
drop(std::fs::remove_file(entry.path()));
|
||||||
@@ -273,7 +280,9 @@ mod tests {
|
|||||||
stop: Some("F10".to_string()),
|
stop: Some("F10".to_string()),
|
||||||
pause: Some("F11".to_string()),
|
pause: Some("F11".to_string()),
|
||||||
},
|
},
|
||||||
updates: UpdatesConfig { check_on_launch: false },
|
updates: UpdatesConfig {
|
||||||
|
check_on_launch: false,
|
||||||
|
},
|
||||||
output_dir: Some(PathBuf::from("./custom")),
|
output_dir: Some(PathBuf::from("./custom")),
|
||||||
theme: Theme::Light,
|
theme: Theme::Light,
|
||||||
};
|
};
|
||||||
|
|||||||
+228
-93
@@ -147,12 +147,7 @@ fn trim_offset(req: &TranscodeRequest) -> f64 {
|
|||||||
req.trim_start_secs.filter(|s| *s > 0.001).unwrap_or(0.0)
|
req.trim_start_secs.filter(|s| *s > 0.001).unwrap_or(0.0)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn click_filters(
|
fn click_filters(clicks: &[Click], clip_w: u32, clip_h: u32, time_offset: f64) -> Option<String> {
|
||||||
clicks: &[Click],
|
|
||||||
clip_w: u32,
|
|
||||||
clip_h: u32,
|
|
||||||
time_offset: f64,
|
|
||||||
) -> Option<String> {
|
|
||||||
if clicks.is_empty() {
|
if clicks.is_empty() {
|
||||||
return None;
|
return None;
|
||||||
}
|
}
|
||||||
@@ -326,10 +321,7 @@ fn probe_encoders(ffmpeg: &Path) -> Result<HashSet<String>> {
|
|||||||
Ok(set)
|
Ok(set)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn pick_audio_codec<'a>(
|
fn pick_audio_codec<'a>(encoders: &HashSet<String>, candidates: &[&'a str]) -> Result<&'a str> {
|
||||||
encoders: &HashSet<String>,
|
|
||||||
candidates: &[&'a str],
|
|
||||||
) -> Result<&'a str> {
|
|
||||||
for c in candidates {
|
for c in candidates {
|
||||||
if encoders.contains(*c) {
|
if encoders.contains(*c) {
|
||||||
return Ok(c);
|
return Ok(c);
|
||||||
@@ -379,7 +371,12 @@ impl CodecAvailability {
|
|||||||
/// Returns all-true when ffmpeg is not installed yet (the bootstrap screen
|
/// Returns all-true when ffmpeg is not installed yet (the bootstrap screen
|
||||||
/// is still up). Settings will re-query after the user installs ffmpeg.
|
/// is still up). Settings will re-query after the user installs ffmpeg.
|
||||||
pub(crate) fn all_unknown() -> Self {
|
pub(crate) fn all_unknown() -> Self {
|
||||||
Self { h264: true, h265: true, vp9: true, av1: true }
|
Self {
|
||||||
|
h264: true,
|
||||||
|
h265: true,
|
||||||
|
vp9: true,
|
||||||
|
av1: true,
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -410,6 +407,17 @@ fn video_bitrate_kbps(req: &TranscodeRequest) -> Result<u64> {
|
|||||||
Ok(kbps.max(16))
|
Ok(kbps.max(16))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Chain the crop and the click highlights into the single `-vf` argument the
|
||||||
|
/// two video passes share.
|
||||||
|
fn combined_video_filter(crop: Option<&String>, clicks: Option<&String>) -> Option<String> {
|
||||||
|
match (crop, clicks) {
|
||||||
|
(Some(c), Some(k)) => Some(format!("{c},{k}")),
|
||||||
|
(Some(c), None) => Some(c.clone()),
|
||||||
|
(None, Some(k)) => Some(k.clone()),
|
||||||
|
(None, None) => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
fn two_pass_video(
|
fn two_pass_video(
|
||||||
ffmpeg: &Path,
|
ffmpeg: &Path,
|
||||||
req: &TranscodeRequest,
|
req: &TranscodeRequest,
|
||||||
@@ -427,13 +435,13 @@ fn two_pass_video(
|
|||||||
let null_target = if cfg!(windows) { "NUL" } else { "/dev/null" };
|
let null_target = if cfg!(windows) { "NUL" } else { "/dev/null" };
|
||||||
|
|
||||||
let crop = crop_filter(req.crop);
|
let crop = crop_filter(req.crop);
|
||||||
let clicks = click_filters(&req.clicks, req.clip_width, req.clip_height, trim_offset(req));
|
let clicks = click_filters(
|
||||||
let combined_vf: Option<String> = match (&crop, &clicks) {
|
&req.clicks,
|
||||||
(Some(c), Some(k)) => Some(format!("{c},{k}")),
|
req.clip_width,
|
||||||
(Some(c), None) => Some(c.clone()),
|
req.clip_height,
|
||||||
(None, Some(k)) => Some(k.clone()),
|
trim_offset(req),
|
||||||
(None, None) => None,
|
);
|
||||||
};
|
let combined_vf = combined_video_filter(crop.as_ref(), clicks.as_ref());
|
||||||
|
|
||||||
let mut pass1 = Command::new(ffmpeg);
|
let mut pass1 = Command::new(ffmpeg);
|
||||||
pass1
|
pass1
|
||||||
@@ -478,7 +486,12 @@ fn two_pass_video(
|
|||||||
if let Some(ref t) = tx {
|
if let Some(ref t) = tx {
|
||||||
// The receiver is gone only if the UI navigated away; the encode is
|
// The receiver is gone only if the UI navigated away; the encode is
|
||||||
// unaffected, so the send error is deliberately discarded.
|
// unaffected, so the send error is deliberately discarded.
|
||||||
t.send(EncodeProgress { pass: 1, total_passes: 2, percent: 100.0 }).ok();
|
t.send(EncodeProgress {
|
||||||
|
pass: 1,
|
||||||
|
total_passes: 2,
|
||||||
|
percent: 100.0,
|
||||||
|
})
|
||||||
|
.ok();
|
||||||
}
|
}
|
||||||
|
|
||||||
let mut pass2 = Command::new(ffmpeg);
|
let mut pass2 = Command::new(ffmpeg);
|
||||||
@@ -588,7 +601,8 @@ fn calibrate_via_sample(
|
|||||||
let aspect = aspect_ratio(req.clip_width, req.clip_height);
|
let aspect = aspect_ratio(req.clip_width, req.clip_height);
|
||||||
let sample_h = round_u32(f64::from(est_width) / aspect);
|
let sample_h = round_u32(f64::from(est_width) / aspect);
|
||||||
let frames = (f64::from(est_fps) * sample_dur).max(1.0);
|
let frames = (f64::from(est_fps) * sample_dur).max(1.0);
|
||||||
let measured_bpp = bytes_f64(sample_bytes) / (f64::from(est_width) * f64::from(sample_h) * frames);
|
let measured_bpp =
|
||||||
|
bytes_f64(sample_bytes) / (f64::from(est_width) * f64::from(sample_h) * frames);
|
||||||
// Blend toward the assumed 0.2 constant - don't over-trust a 2s sample.
|
// Blend toward the assumed 0.2 constant - don't over-trust a 2s sample.
|
||||||
let blended_bpp = measured_bpp * 0.7 + 0.2 * 0.3;
|
let blended_bpp = measured_bpp * 0.7 + 0.2 * 0.3;
|
||||||
|
|
||||||
@@ -604,7 +618,9 @@ fn calibrate_via_sample(
|
|||||||
// Recompute target params with the corrected constant. Scale resolution
|
// Recompute target params with the corrected constant. Scale resolution
|
||||||
// by the sqrt of the ratio so file size scales roughly linearly.
|
// by the sqrt of the ratio so file size scales roughly linearly.
|
||||||
let new_width = (round_u32(f64::from(est_width) * ratio.sqrt()) / 2).max(60) * 2;
|
let new_width = (round_u32(f64::from(est_width) * ratio.sqrt()) / 2).max(60) * 2;
|
||||||
let new_fps = round_u32(f64::from(est_fps) * ratio.sqrt()).max(1).min(est_fps);
|
let new_fps = round_u32(f64::from(est_fps) * ratio.sqrt())
|
||||||
|
.max(1)
|
||||||
|
.min(est_fps);
|
||||||
Some((new_width.min(1280), new_fps))
|
Some((new_width.min(1280), new_fps))
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -625,6 +641,42 @@ fn gif_shrink_factor(mode: GifBudgetMode, ratio: f64) -> f64 {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Spend one retry's shrink factor on whichever knobs the budget mode reduces,
|
||||||
|
/// keeping the width even (the `*2` after the halving clamp).
|
||||||
|
fn shrink_gif_params(mode: GifBudgetMode, factor: f64, width: &mut u32, fps: &mut u32) {
|
||||||
|
match mode {
|
||||||
|
GifBudgetMode::Resolution => {
|
||||||
|
*width = (round_u32(f64::from(*width) * factor) / 2).clamp(60, 640) * 2;
|
||||||
|
}
|
||||||
|
GifBudgetMode::Framerate => {
|
||||||
|
*fps = round_u32(f64::from(*fps) * factor).max(1);
|
||||||
|
}
|
||||||
|
GifBudgetMode::Balanced => {
|
||||||
|
*width = (round_u32(f64::from(*width) * factor) / 2).clamp(60, 640) * 2;
|
||||||
|
*fps = round_u32(f64::from(*fps) * factor).max(1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Refine the retry loop's starting dimensions from a short sample encode, and
|
||||||
|
/// log what the sample suggested. None when the clip is too short to sample or
|
||||||
|
/// the sample did not reveal a meaningful gap.
|
||||||
|
fn gif_calibration(
|
||||||
|
ffmpeg: &Path,
|
||||||
|
req: &TranscodeRequest,
|
||||||
|
width: u32,
|
||||||
|
fps: u32,
|
||||||
|
) -> Option<(u32, u32)> {
|
||||||
|
if req.duration_secs <= 4.0 {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let (w, f) = calibrate_via_sample(ffmpeg, req, width, fps)?;
|
||||||
|
tracing::info!(
|
||||||
|
"gif calibration: sample suggested {w}x @ {f}fps (initial was {width}x @ {fps}fps)"
|
||||||
|
);
|
||||||
|
Some((w, f))
|
||||||
|
}
|
||||||
|
|
||||||
fn encode_gif(ffmpeg: &Path, req: &TranscodeRequest) -> Result<()> {
|
fn encode_gif(ffmpeg: &Path, req: &TranscodeRequest) -> Result<()> {
|
||||||
let budget_input = GifBudgetInput {
|
let budget_input = GifBudgetInput {
|
||||||
gif_colors: req.gif_colors,
|
gif_colors: req.gif_colors,
|
||||||
@@ -633,20 +685,16 @@ fn encode_gif(ffmpeg: &Path, req: &TranscodeRequest) -> Result<()> {
|
|||||||
duration_secs: req.duration_secs,
|
duration_secs: req.duration_secs,
|
||||||
gif_budget_mode: req.gif_budget_mode,
|
gif_budget_mode: req.gif_budget_mode,
|
||||||
};
|
};
|
||||||
let (mut scale_width, mut effective_fps) = gif_params(&budget_input, req.clip_width, req.clip_height);
|
let (mut scale_width, mut effective_fps) =
|
||||||
|
gif_params(&budget_input, req.clip_width, req.clip_height);
|
||||||
|
|
||||||
// Calibrate the bytes/pixel constant by encoding a short sample first.
|
// Calibrate the bytes/pixel constant by encoding a short sample first.
|
||||||
// The default 0.2 bytes/pixel assumption varies 3-5x by content; measuring
|
// The default 0.2 bytes/pixel assumption varies 3-5x by content; measuring
|
||||||
// it on this specific clip gives the retry loop a much better starting
|
// it on this specific clip gives the retry loop a much better starting
|
||||||
// point and typically cuts retry count from 4-8 down to 1-2.
|
// point and typically cuts retry count from 4-8 down to 1-2.
|
||||||
if req.duration_secs > 4.0 {
|
if let Some((w, f)) = gif_calibration(ffmpeg, req, scale_width, effective_fps) {
|
||||||
if let Some((calibrated_w, calibrated_fps)) = calibrate_via_sample(ffmpeg, req, scale_width, effective_fps) {
|
scale_width = w;
|
||||||
tracing::info!(
|
effective_fps = f;
|
||||||
"gif calibration: sample suggested {calibrated_w}x @ {calibrated_fps}fps (initial was {scale_width}x @ {effective_fps}fps)"
|
|
||||||
);
|
|
||||||
scale_width = calibrated_w;
|
|
||||||
effective_fps = calibrated_fps;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
let target = req.target_bytes;
|
let target = req.target_bytes;
|
||||||
@@ -661,7 +709,11 @@ fn encode_gif(ffmpeg: &Path, req: &TranscodeRequest) -> Result<()> {
|
|||||||
let mut prev_actual: Option<u64> = None;
|
let mut prev_actual: Option<u64> = None;
|
||||||
|
|
||||||
for attempt in 0..max_retries {
|
for attempt in 0..max_retries {
|
||||||
if req.cancel.as_ref().is_some_and(|c| c.load(Ordering::Relaxed)) {
|
if req
|
||||||
|
.cancel
|
||||||
|
.as_ref()
|
||||||
|
.is_some_and(|c| c.load(Ordering::Relaxed))
|
||||||
|
{
|
||||||
bail!("export cancelled");
|
bail!("export cancelled");
|
||||||
}
|
}
|
||||||
// Last resort: use minimal settings to hit the target
|
// Last resort: use minimal settings to hit the target
|
||||||
@@ -671,8 +723,12 @@ fn encode_gif(ffmpeg: &Path, req: &TranscodeRequest) -> Result<()> {
|
|||||||
}
|
}
|
||||||
let pass_start = std::time::Instant::now();
|
let pass_start = std::time::Instant::now();
|
||||||
encode_gif_pass(
|
encode_gif_pass(
|
||||||
ffmpeg, req, scale_width, effective_fps,
|
ffmpeg,
|
||||||
(u8::try_from(attempt).unwrap_or(0)) + 1, max_attempts,
|
req,
|
||||||
|
scale_width,
|
||||||
|
effective_fps,
|
||||||
|
(u8::try_from(attempt).unwrap_or(0)) + 1,
|
||||||
|
max_attempts,
|
||||||
)?;
|
)?;
|
||||||
tracing::info!(
|
tracing::info!(
|
||||||
attempt = attempt + 1,
|
attempt = attempt + 1,
|
||||||
@@ -680,8 +736,7 @@ fn encode_gif(ffmpeg: &Path, req: &TranscodeRequest) -> Result<()> {
|
|||||||
"gif pass finished"
|
"gif pass finished"
|
||||||
);
|
);
|
||||||
|
|
||||||
let actual = std::fs::metadata(&req.output)
|
let actual = std::fs::metadata(&req.output).map_or(0, |m| m.len());
|
||||||
.map_or(0, |m| m.len());
|
|
||||||
|
|
||||||
if actual == 0 {
|
if actual == 0 {
|
||||||
bail!("gif output is empty");
|
bail!("gif output is empty");
|
||||||
@@ -693,7 +748,9 @@ fn encode_gif(ffmpeg: &Path, req: &TranscodeRequest) -> Result<()> {
|
|||||||
if ratio >= 1.0 {
|
if ratio >= 1.0 {
|
||||||
tracing::info!(
|
tracing::info!(
|
||||||
"gif encode done on attempt {}: {} bytes (target {})",
|
"gif encode done on attempt {}: {} bytes (target {})",
|
||||||
attempt + 1, actual, target
|
attempt + 1,
|
||||||
|
actual,
|
||||||
|
target
|
||||||
);
|
);
|
||||||
return Ok(());
|
return Ok(());
|
||||||
}
|
}
|
||||||
@@ -725,19 +782,12 @@ fn encode_gif(ffmpeg: &Path, req: &TranscodeRequest) -> Result<()> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
match req.gif_budget_mode {
|
shrink_gif_params(
|
||||||
GifBudgetMode::Resolution => {
|
req.gif_budget_mode,
|
||||||
// Halve before clamping so the *2 keeps the width even.
|
factor,
|
||||||
scale_width = (round_u32(f64::from(scale_width) * factor) / 2).clamp(60, 640) * 2;
|
&mut scale_width,
|
||||||
}
|
&mut effective_fps,
|
||||||
GifBudgetMode::Framerate => {
|
);
|
||||||
effective_fps = round_u32(f64::from(effective_fps) * factor).max(1);
|
|
||||||
}
|
|
||||||
GifBudgetMode::Balanced => {
|
|
||||||
scale_width = (round_u32(f64::from(scale_width) * factor) / 2).clamp(60, 640) * 2;
|
|
||||||
effective_fps = round_u32(f64::from(effective_fps) * factor).max(1);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
tracing::info!(
|
tracing::info!(
|
||||||
"gif retry {}: was {} bytes (target {}), adjusting to {}x @ {}fps (factor={:.2})",
|
"gif retry {}: was {} bytes (target {}), adjusting to {}x @ {}fps (factor={:.2})",
|
||||||
@@ -773,7 +823,12 @@ fn encode_gif_pass(
|
|||||||
let crop_prefix = crop_filter(req.crop)
|
let crop_prefix = crop_filter(req.crop)
|
||||||
.map(|c| format!("{c},"))
|
.map(|c| format!("{c},"))
|
||||||
.unwrap_or_default();
|
.unwrap_or_default();
|
||||||
let click_prefix = click_filters(&req.clicks, req.clip_width, req.clip_height, trim_offset(req))
|
let click_prefix = click_filters(
|
||||||
|
&req.clicks,
|
||||||
|
req.clip_width,
|
||||||
|
req.clip_height,
|
||||||
|
trim_offset(req),
|
||||||
|
)
|
||||||
.map(|c| format!("{c},"))
|
.map(|c| format!("{c},"))
|
||||||
.unwrap_or_default();
|
.unwrap_or_default();
|
||||||
let select_prefix = select_filter_for_deleted(&req.deleted_frame_indices)
|
let select_prefix = select_filter_for_deleted(&req.deleted_frame_indices)
|
||||||
@@ -800,7 +855,10 @@ fn encode_gif_pass(
|
|||||||
d = dither,
|
d = dither,
|
||||||
);
|
);
|
||||||
|
|
||||||
tracing::info!("gif encode: fps={effective_fps} scale={scale_width} colors={} filter={filter_complex}", req.gif_colors);
|
tracing::info!(
|
||||||
|
"gif encode: fps={effective_fps} scale={scale_width} colors={} filter={filter_complex}",
|
||||||
|
req.gif_colors
|
||||||
|
);
|
||||||
|
|
||||||
let mut encode = Command::new(ffmpeg);
|
let mut encode = Command::new(ffmpeg);
|
||||||
encode
|
encode
|
||||||
@@ -850,7 +908,9 @@ pub(crate) fn gif_params(input: &GifBudgetInput, clip_width: u32, clip_height: u
|
|||||||
// Fewer colors = better compression. Adjust proportionally to the sqrt of the color
|
// Fewer colors = better compression. Adjust proportionally to the sqrt of the color
|
||||||
// fraction (LZW code width tracks palette depth roughly logarithmically).
|
// fraction (LZW code width tracks palette depth roughly logarithmically).
|
||||||
// 256 colors = 1.0x, 128 = ~0.71x, 64 = 0.5x, 32 = ~0.35x, 16 = 0.25x, 2 = ~0.13x
|
// 256 colors = 1.0x, 128 = ~0.71x, 64 = 0.5x, 32 = ~0.35x, 16 = 0.25x, 2 = ~0.13x
|
||||||
let color_factor = (f64::from(input.gif_colors) / 256.0).sqrt().clamp(0.15, 1.0);
|
let color_factor = (f64::from(input.gif_colors) / 256.0)
|
||||||
|
.sqrt()
|
||||||
|
.clamp(0.15, 1.0);
|
||||||
let bytes_per_pixel_per_frame = 0.2 * color_factor;
|
let bytes_per_pixel_per_frame = 0.2 * color_factor;
|
||||||
let target_bytes = bytes_f64(input.target_bytes);
|
let target_bytes = bytes_f64(input.target_bytes);
|
||||||
let requested_fps = f64::from(input.fps);
|
let requested_fps = f64::from(input.fps);
|
||||||
@@ -977,7 +1037,8 @@ pub(crate) fn render_gif_preview(
|
|||||||
clean_stale_palettes(palette_path.parent().unwrap_or(Path::new(".")));
|
clean_stale_palettes(palette_path.parent().unwrap_or(Path::new(".")));
|
||||||
let palette_filter = format!(
|
let palette_filter = format!(
|
||||||
"{},palettegen=stats_mode=diff:max_colors={}",
|
"{},palettegen=stats_mode=diff:max_colors={}",
|
||||||
gif_rgb_scale_filter(target_width), gif_colors
|
gif_rgb_scale_filter(target_width),
|
||||||
|
gif_colors
|
||||||
);
|
);
|
||||||
let mut gen = Command::new(ffmpeg);
|
let mut gen = Command::new(ffmpeg);
|
||||||
gen.arg("-y")
|
gen.arg("-y")
|
||||||
@@ -994,10 +1055,12 @@ pub(crate) fn render_gif_preview(
|
|||||||
// Apply palette to the target frame
|
// Apply palette to the target frame
|
||||||
let use_filter = format!(
|
let use_filter = format!(
|
||||||
"{}[x];[x][1:v]paletteuse=dither={}",
|
"{}[x];[x][1:v]paletteuse=dither={}",
|
||||||
gif_rgb_scale_filter(target_width), gif_dither
|
gif_rgb_scale_filter(target_width),
|
||||||
|
gif_dither
|
||||||
);
|
);
|
||||||
let mut encode = Command::new(ffmpeg);
|
let mut encode = Command::new(ffmpeg);
|
||||||
encode.arg("-y")
|
encode
|
||||||
|
.arg("-y")
|
||||||
.arg("-hide_banner")
|
.arg("-hide_banner")
|
||||||
.args(["-ss", &format!("{midpoint_secs}")])
|
.args(["-ss", &format!("{midpoint_secs}")])
|
||||||
.arg("-i")
|
.arg("-i")
|
||||||
@@ -1017,10 +1080,13 @@ pub(crate) fn render_gif_preview(
|
|||||||
|
|
||||||
/// Build a stable cache key for a GIF preview palette from the inputs that
|
/// Build a stable cache key for a GIF preview palette from the inputs that
|
||||||
/// actually affect palettegen output. Same inputs -> same palette.
|
/// actually affect palettegen output. Same inputs -> same palette.
|
||||||
fn palette_cache_key(gif_colors: u16, target_width: u32, sample_start: f64, sample_dur: f64) -> String {
|
fn palette_cache_key(
|
||||||
format!(
|
gif_colors: u16,
|
||||||
"c{gif_colors}-w{target_width}-s{sample_start:.3}-d{sample_dur:.3}"
|
target_width: u32,
|
||||||
)
|
sample_start: f64,
|
||||||
|
sample_dur: f64,
|
||||||
|
) -> String {
|
||||||
|
format!("c{gif_colors}-w{target_width}-s{sample_start:.3}-d{sample_dur:.3}")
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Remove old `preview-palette-*.png` files so only the current key remains.
|
/// Remove old `preview-palette-*.png` files so only the current key remains.
|
||||||
@@ -1056,9 +1122,7 @@ pub(crate) fn extract_thumbnails(
|
|||||||
let crop_prefix = crop_filter(crop)
|
let crop_prefix = crop_filter(crop)
|
||||||
.map(|c| format!("{c},"))
|
.map(|c| format!("{c},"))
|
||||||
.unwrap_or_default();
|
.unwrap_or_default();
|
||||||
let filter = format!(
|
let filter = format!("{crop_prefix}fps={fps},scale=120:-1:flags=lanczos");
|
||||||
"{crop_prefix}fps={fps},scale=120:-1:flags=lanczos"
|
|
||||||
);
|
|
||||||
let pattern = out_dir.join("thumb-%05d.png");
|
let pattern = out_dir.join("thumb-%05d.png");
|
||||||
|
|
||||||
let mut cmd = Command::new(ffmpeg);
|
let mut cmd = Command::new(ffmpeg);
|
||||||
@@ -1123,8 +1187,8 @@ pub(crate) fn concat_pcm(segments: &[PathBuf], output: &Path) -> Result<()> {
|
|||||||
}
|
}
|
||||||
let mut out = std::fs::File::create(output).context("creating audio concat file")?;
|
let mut out = std::fs::File::create(output).context("creating audio concat file")?;
|
||||||
for seg in segments {
|
for seg in segments {
|
||||||
let mut f = std::fs::File::open(seg)
|
let mut f =
|
||||||
.with_context(|| format!("opening {}", seg.display()))?;
|
std::fs::File::open(seg).with_context(|| format!("opening {}", seg.display()))?;
|
||||||
std::io::copy(&mut f, &mut out).context("copying audio segment")?;
|
std::io::copy(&mut f, &mut out).context("copying audio segment")?;
|
||||||
}
|
}
|
||||||
out.flush()?;
|
out.flush()?;
|
||||||
@@ -1133,7 +1197,9 @@ pub(crate) fn concat_pcm(segments: &[PathBuf], output: &Path) -> Result<()> {
|
|||||||
|
|
||||||
struct TempFileGuard(PathBuf);
|
struct TempFileGuard(PathBuf);
|
||||||
impl Drop for TempFileGuard {
|
impl Drop for TempFileGuard {
|
||||||
fn drop(&mut self) { drop(std::fs::remove_file(&self.0)); }
|
fn drop(&mut self) {
|
||||||
|
drop(std::fs::remove_file(&self.0));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) fn concat_segments(ffmpeg: &Path, segments: &[PathBuf], output: &Path) -> Result<()> {
|
pub(crate) fn concat_segments(ffmpeg: &Path, segments: &[PathBuf], output: &Path) -> Result<()> {
|
||||||
@@ -1208,8 +1274,15 @@ fn run_with_progress(
|
|||||||
// "key=value" lines terminated by "progress=continue" / "progress=end".
|
// "key=value" lines terminated by "progress=continue" / "progress=end".
|
||||||
cmd.arg("-progress").arg("pipe:1");
|
cmd.arg("-progress").arg("pipe:1");
|
||||||
let output = run_impl(
|
let output = run_impl(
|
||||||
cmd, label, pass, total_passes, duration_secs, fps,
|
cmd,
|
||||||
progress_tx.cloned(), cancel.cloned(), true,
|
label,
|
||||||
|
pass,
|
||||||
|
total_passes,
|
||||||
|
duration_secs,
|
||||||
|
fps,
|
||||||
|
progress_tx.cloned(),
|
||||||
|
cancel.cloned(),
|
||||||
|
true,
|
||||||
)?;
|
)?;
|
||||||
if !output.status.success() {
|
if !output.status.success() {
|
||||||
bail!(ffmpeg_failure_message(label, output.status, &output.stderr));
|
bail!(ffmpeg_failure_message(label, output.status, &output.stderr));
|
||||||
@@ -1221,8 +1294,7 @@ fn ffmpeg_failure_message(label: &str, status: std::process::ExitStatus, stderr:
|
|||||||
let text = String::from_utf8_lossy(stderr);
|
let text = String::from_utf8_lossy(stderr);
|
||||||
let head: String = text.lines().take(12).collect::<Vec<_>>().join("\n");
|
let head: String = text.lines().take(12).collect::<Vec<_>>().join("\n");
|
||||||
let lower = text.to_ascii_lowercase();
|
let lower = text.to_ascii_lowercase();
|
||||||
let hint = if lower.contains("unknown encoder")
|
let hint = if lower.contains("unknown encoder") || lower.contains("error while opening encoder")
|
||||||
|| lower.contains("error while opening encoder")
|
|
||||||
{
|
{
|
||||||
Some("selected codec is not available in this ffmpeg build")
|
Some("selected codec is not available in this ffmpeg build")
|
||||||
} else if lower.contains("permission denied") {
|
} else if lower.contains("permission denied") {
|
||||||
@@ -1242,6 +1314,19 @@ fn ffmpeg_failure_message(label: &str, status: std::process::ExitStatus, stderr:
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Render an ffmpeg invocation for the log. A failed encode is only diagnosable
|
||||||
|
/// from the exact argument list, and the arg vector is not printable on its own.
|
||||||
|
fn describe_command(label: &str, cmd: &Command) -> String {
|
||||||
|
let mut printable = OsString::from(label);
|
||||||
|
printable.push(": ");
|
||||||
|
printable.push(cmd.get_program());
|
||||||
|
for arg in cmd.get_args() {
|
||||||
|
printable.push(" ");
|
||||||
|
printable.push(arg);
|
||||||
|
}
|
||||||
|
printable.to_string_lossy().into_owned()
|
||||||
|
}
|
||||||
|
|
||||||
// Consumes the progress sender and the cancel flag: both are moved into the
|
// Consumes the progress sender and the cancel flag: both are moved into the
|
||||||
// reader threads this spawns, so borrowing them here would not typecheck.
|
// reader threads this spawns, so borrowing them here would not typecheck.
|
||||||
// The argument count matches run_with_progress, its only caller.
|
// The argument count matches run_with_progress, its only caller.
|
||||||
@@ -1266,18 +1351,15 @@ fn run_impl(
|
|||||||
) -> Result<std::process::Output> {
|
) -> Result<std::process::Output> {
|
||||||
use std::process::Stdio;
|
use std::process::Stdio;
|
||||||
|
|
||||||
let mut printable = OsString::from(label);
|
tracing::debug!("{}", describe_command(label, cmd));
|
||||||
printable.push(": ");
|
|
||||||
printable.push(cmd.get_program());
|
|
||||||
for arg in cmd.get_args() {
|
|
||||||
printable.push(" ");
|
|
||||||
printable.push(arg);
|
|
||||||
}
|
|
||||||
tracing::debug!("{}", printable.to_string_lossy());
|
|
||||||
|
|
||||||
// When we asked ffmpeg for `-progress pipe:1`, stdout carries the stable
|
// When we asked ffmpeg for `-progress pipe:1`, stdout carries the stable
|
||||||
// key=value stream; stderr still carries errors. Otherwise null stdout.
|
// key=value stream; stderr still carries errors. Otherwise null stdout.
|
||||||
let stdout_cfg = if read_stdout { Stdio::piped() } else { Stdio::null() };
|
let stdout_cfg = if read_stdout {
|
||||||
|
Stdio::piped()
|
||||||
|
} else {
|
||||||
|
Stdio::null()
|
||||||
|
};
|
||||||
let mut child = cmd
|
let mut child = cmd
|
||||||
.stdout(stdout_cfg)
|
.stdout(stdout_cfg)
|
||||||
.stderr(Stdio::piped())
|
.stderr(Stdio::piped())
|
||||||
@@ -1285,7 +1367,11 @@ fn run_impl(
|
|||||||
.with_context(|| format!("spawning ffmpeg for {label}"))?;
|
.with_context(|| format!("spawning ffmpeg for {label}"))?;
|
||||||
|
|
||||||
let stderr = child.stderr.take();
|
let stderr = child.stderr.take();
|
||||||
let stdout = if read_stdout { child.stdout.take() } else { None };
|
let stdout = if read_stdout {
|
||||||
|
child.stdout.take()
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
};
|
||||||
let tx = progress_tx.clone();
|
let tx = progress_tx.clone();
|
||||||
|
|
||||||
// Progress reader: parse the key=value stream from stdout. Each update
|
// Progress reader: parse the key=value stream from stdout. Each update
|
||||||
@@ -1343,15 +1429,22 @@ fn run_impl(
|
|||||||
if c.load(Ordering::Relaxed) {
|
if c.load(Ordering::Relaxed) {
|
||||||
drop(child.kill());
|
drop(child.kill());
|
||||||
drop(child.wait());
|
drop(child.wait());
|
||||||
if let Some(h) = stdout_handle.take() { drop(h.join()); }
|
if let Some(h) = stdout_handle.take() {
|
||||||
if let Some(h) = stderr_handle.take() { drop(h.join()); }
|
drop(h.join());
|
||||||
|
}
|
||||||
|
if let Some(h) = stderr_handle.take() {
|
||||||
|
drop(h.join());
|
||||||
|
}
|
||||||
bail!("export cancelled");
|
bail!("export cancelled");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
match child.try_wait() {
|
match child.try_wait() {
|
||||||
Ok(Some(status)) => {
|
Ok(Some(status)) => {
|
||||||
if let Some(h) = stdout_handle.take() { drop(h.join()); }
|
if let Some(h) = stdout_handle.take() {
|
||||||
let stderr_bytes = stderr_handle.take()
|
drop(h.join());
|
||||||
|
}
|
||||||
|
let stderr_bytes = stderr_handle
|
||||||
|
.take()
|
||||||
.and_then(|h| h.join().ok())
|
.and_then(|h| h.join().ok())
|
||||||
.unwrap_or_default();
|
.unwrap_or_default();
|
||||||
return Ok(std::process::Output {
|
return Ok(std::process::Output {
|
||||||
@@ -1457,13 +1550,19 @@ mod tests {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn parse_progress_kv_out_time_us() {
|
fn parse_progress_kv_out_time_us() {
|
||||||
assert_eq!(parse_progress_kv("out_time_us=5000000"), Some(("out_time_us", 5_000_000.0)));
|
assert_eq!(
|
||||||
|
parse_progress_kv("out_time_us=5000000"),
|
||||||
|
Some(("out_time_us", 5_000_000.0))
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn parse_progress_kv_progress_continue_returns_zero() {
|
fn parse_progress_kv_progress_continue_returns_zero() {
|
||||||
// "continue" is non-numeric, so value parses to 0.0; the key is what matters.
|
// "continue" is non-numeric, so value parses to 0.0; the key is what matters.
|
||||||
assert_eq!(parse_progress_kv("progress=continue"), Some(("progress", 0.0)));
|
assert_eq!(
|
||||||
|
parse_progress_kv("progress=continue"),
|
||||||
|
Some(("progress", 0.0))
|
||||||
|
);
|
||||||
assert_eq!(parse_progress_kv("progress=end"), Some(("progress", 0.0)));
|
assert_eq!(parse_progress_kv("progress=end"), Some(("progress", 0.0)));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1492,7 +1591,12 @@ mod tests {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn crop_filter_output() {
|
fn crop_filter_output() {
|
||||||
let rect = CaptureRect { x: 10, y: 20, width: 100, height: 200 };
|
let rect = CaptureRect {
|
||||||
|
x: 10,
|
||||||
|
y: 20,
|
||||||
|
width: 100,
|
||||||
|
height: 200,
|
||||||
|
};
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
crop_filter(Some(rect)),
|
crop_filter(Some(rect)),
|
||||||
Some("crop=100:200:10:20".to_string())
|
Some("crop=100:200:10:20".to_string())
|
||||||
@@ -1503,7 +1607,12 @@ mod tests {
|
|||||||
#[test]
|
#[test]
|
||||||
fn click_filters_capped_at_max() {
|
fn click_filters_capped_at_max() {
|
||||||
let clicks: Vec<Click> = (0..100)
|
let clicks: Vec<Click> = (0..100)
|
||||||
.map(|i| Click { time_secs: f64::from(i), x: i, y: i, button: crate::clicks::MouseButton::Left })
|
.map(|i| Click {
|
||||||
|
time_secs: f64::from(i),
|
||||||
|
x: i,
|
||||||
|
y: i,
|
||||||
|
button: crate::clicks::MouseButton::Left,
|
||||||
|
})
|
||||||
.collect();
|
.collect();
|
||||||
let filter = click_filters(&clicks, 1920, 1080, 0.0).unwrap();
|
let filter = click_filters(&clicks, 1920, 1080, 0.0).unwrap();
|
||||||
let count = filter.matches("drawbox").count();
|
let count = filter.matches("drawbox").count();
|
||||||
@@ -1515,7 +1624,10 @@ mod tests {
|
|||||||
let frame = (1920u32, 1080u32);
|
let frame = (1920u32, 1080u32);
|
||||||
// Near each edge, and one dead-centre.
|
// Near each edge, and one dead-centre.
|
||||||
assert_eq!(click_box(2, 2, frame.0, frame.1), Some((0, 0)));
|
assert_eq!(click_box(2, 2, frame.0, frame.1), Some((0, 0)));
|
||||||
assert_eq!(click_box(1919, 1079, frame.0, frame.1), Some((1920 - BOX_SIZE, 1080 - BOX_SIZE)));
|
assert_eq!(
|
||||||
|
click_box(1919, 1079, frame.0, frame.1),
|
||||||
|
Some((1920 - BOX_SIZE, 1080 - BOX_SIZE))
|
||||||
|
);
|
||||||
assert_eq!(click_box(960, 540, frame.0, frame.1), Some((948, 528)));
|
assert_eq!(click_box(960, 540, frame.0, frame.1), Some((948, 528)));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1534,8 +1646,18 @@ mod tests {
|
|||||||
#[test]
|
#[test]
|
||||||
fn click_filters_drops_clicks_off_frame() {
|
fn click_filters_drops_clicks_off_frame() {
|
||||||
let clicks = vec![
|
let clicks = vec![
|
||||||
Click { time_secs: 0.5, x: -620, y: 115, button: crate::clicks::MouseButton::Left },
|
Click {
|
||||||
Click { time_secs: 0.9, x: 500, y: 400, button: crate::clicks::MouseButton::Left },
|
time_secs: 0.5,
|
||||||
|
x: -620,
|
||||||
|
y: 115,
|
||||||
|
button: crate::clicks::MouseButton::Left,
|
||||||
|
},
|
||||||
|
Click {
|
||||||
|
time_secs: 0.9,
|
||||||
|
x: 500,
|
||||||
|
y: 400,
|
||||||
|
button: crate::clicks::MouseButton::Left,
|
||||||
|
},
|
||||||
];
|
];
|
||||||
let filter = click_filters(&clicks, 1920, 1080, 0.0).unwrap();
|
let filter = click_filters(&clicks, 1920, 1080, 0.0).unwrap();
|
||||||
assert_eq!(filter.matches("drawbox").count(), 1);
|
assert_eq!(filter.matches("drawbox").count(), 1);
|
||||||
@@ -1550,7 +1672,12 @@ mod tests {
|
|||||||
/// same amount or it fires late by the length of the trim.
|
/// same amount or it fires late by the length of the trim.
|
||||||
#[test]
|
#[test]
|
||||||
fn click_times_are_rebased_by_the_trim() {
|
fn click_times_are_rebased_by_the_trim() {
|
||||||
let clicks = vec![Click { time_secs: 6.0, x: 500, y: 400, button: crate::clicks::MouseButton::Left }];
|
let clicks = vec![Click {
|
||||||
|
time_secs: 6.0,
|
||||||
|
x: 500,
|
||||||
|
y: 400,
|
||||||
|
button: crate::clicks::MouseButton::Left,
|
||||||
|
}];
|
||||||
let untrimmed = click_filters(&clicks, 1920, 1080, 0.0).unwrap();
|
let untrimmed = click_filters(&clicks, 1920, 1080, 0.0).unwrap();
|
||||||
assert!(untrimmed.contains("between(t,5.950,6.250)"));
|
assert!(untrimmed.contains("between(t,5.950,6.250)"));
|
||||||
let trimmed = click_filters(&clicks, 1920, 1080, 5.0).unwrap();
|
let trimmed = click_filters(&clicks, 1920, 1080, 5.0).unwrap();
|
||||||
@@ -1561,7 +1688,12 @@ mod tests {
|
|||||||
/// A click that happened before the trimmed window has nothing left to draw.
|
/// A click that happened before the trimmed window has nothing left to draw.
|
||||||
#[test]
|
#[test]
|
||||||
fn clicks_before_the_trim_are_dropped() {
|
fn clicks_before_the_trim_are_dropped() {
|
||||||
let clicks = vec![Click { time_secs: 1.0, x: 500, y: 400, button: crate::clicks::MouseButton::Left }];
|
let clicks = vec![Click {
|
||||||
|
time_secs: 1.0,
|
||||||
|
x: 500,
|
||||||
|
y: 400,
|
||||||
|
button: crate::clicks::MouseButton::Left,
|
||||||
|
}];
|
||||||
assert!(click_filters(&clicks, 1920, 1080, 5.0).is_none());
|
assert!(click_filters(&clicks, 1920, 1080, 5.0).is_none());
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1584,7 +1716,10 @@ mod tests {
|
|||||||
let f = gif_shrink_factor(GifBudgetMode::Balanced, 0.25);
|
let f = gif_shrink_factor(GifBudgetMode::Balanced, 0.25);
|
||||||
let lo = 0.25_f64;
|
let lo = 0.25_f64;
|
||||||
let hi = 0.5_f64; // sqrt(0.25)
|
let hi = 0.5_f64; // sqrt(0.25)
|
||||||
assert!(f > lo && f < hi, "balanced factor {f} should sit between linear {lo} and sqrt {hi}");
|
assert!(
|
||||||
|
f > lo && f < hi,
|
||||||
|
"balanced factor {f} should sit between linear {lo} and sqrt {hi}"
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
|
|||||||
+228
-134
@@ -30,9 +30,9 @@ use std::sync::{Arc, Mutex};
|
|||||||
|
|
||||||
use anyhow::{anyhow, Context as _, Result};
|
use anyhow::{anyhow, Context as _, Result};
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
|
use std::str::FromStr;
|
||||||
use tauri::{AppHandle, Emitter, Manager, State};
|
use tauri::{AppHandle, Emitter, Manager, State};
|
||||||
use tauri_plugin_global_shortcut::{GlobalShortcutExt, Shortcut, ShortcutState};
|
use tauri_plugin_global_shortcut::{GlobalShortcutExt, Shortcut, ShortcutState};
|
||||||
use std::str::FromStr;
|
|
||||||
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt, EnvFilter};
|
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt, EnvFilter};
|
||||||
|
|
||||||
use crate::bootstrap::FfmpegStatus;
|
use crate::bootstrap::FfmpegStatus;
|
||||||
@@ -320,10 +320,7 @@ async fn download_ffmpeg(app: AppHandle, state: State<'_, AppState>) -> Result<(
|
|||||||
let app_dir = state.app_dir.clone();
|
let app_dir = state.app_dir.clone();
|
||||||
let app_handle = app.clone();
|
let app_handle = app.clone();
|
||||||
bootstrap::download(&app_dir, move |downloaded, total| {
|
bootstrap::download(&app_dir, move |downloaded, total| {
|
||||||
drop(app_handle.emit(
|
drop(app_handle.emit("ffmpeg-progress", DownloadProgress { downloaded, total }));
|
||||||
"ffmpeg-progress",
|
|
||||||
DownloadProgress { downloaded, total },
|
|
||||||
));
|
|
||||||
})
|
})
|
||||||
.await
|
.await
|
||||||
.map_err(|e| format!("{e:#}"))
|
.map_err(|e| format!("{e:#}"))
|
||||||
@@ -394,7 +391,12 @@ fn clear_temp_segments(app_dir: &Path, keep_previews: bool) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Pad or trim a raw f32le PCM file so its duration matches `target_secs`.
|
/// Pad or trim a raw f32le PCM file so its duration matches `target_secs`.
|
||||||
fn adjust_audio_length(path: &Path, sample_rate: u32, channels: u16, target_secs: f64) -> Result<()> {
|
fn adjust_audio_length(
|
||||||
|
path: &Path,
|
||||||
|
sample_rate: u32,
|
||||||
|
channels: u16,
|
||||||
|
target_secs: f64,
|
||||||
|
) -> Result<()> {
|
||||||
use std::io::Write;
|
use std::io::Write;
|
||||||
let bytes_per_sec = f64::from(sample_rate) * f64::from(channels) * 4.0;
|
let bytes_per_sec = f64::from(sample_rate) * f64::from(channels) * 4.0;
|
||||||
let target_bytes = encode::round_u64(target_secs * bytes_per_sec);
|
let target_bytes = encode::round_u64(target_secs * bytes_per_sec);
|
||||||
@@ -469,7 +471,8 @@ fn pad_audio_head(path: &Path, sample_rate: u32, channels: u16, head_secs: f64)
|
|||||||
}
|
}
|
||||||
tracing::debug!(
|
tracing::debug!(
|
||||||
"padded audio head with {:.1}ms ({} bytes) of silence",
|
"padded audio head with {:.1}ms ({} bytes) of silence",
|
||||||
head_secs * 1000.0, pad_bytes
|
head_secs * 1000.0,
|
||||||
|
pad_bytes
|
||||||
);
|
);
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
@@ -566,7 +569,10 @@ fn start_capture(
|
|||||||
clear_temp_segments(&state.app_dir, true);
|
clear_temp_segments(&state.app_dir, true);
|
||||||
|
|
||||||
let crop = request.as_ref().and_then(|r| r.crop);
|
let crop = request.as_ref().and_then(|r| r.crop);
|
||||||
let fps = request.as_ref().and_then(|r| r.fps).unwrap_or(cfg.capture.default_fps);
|
let fps = request
|
||||||
|
.as_ref()
|
||||||
|
.and_then(|r| r.fps)
|
||||||
|
.unwrap_or(cfg.capture.default_fps);
|
||||||
let output = segment_path(&state.app_dir, 1);
|
let output = segment_path(&state.app_dir, 1);
|
||||||
|
|
||||||
let ffmpeg = bootstrap::ffmpeg_path(&state.app_dir);
|
let ffmpeg = bootstrap::ffmpeg_path(&state.app_dir);
|
||||||
@@ -574,8 +580,7 @@ fn start_capture(
|
|||||||
return Err("ffmpeg.exe not found - run the encoder setup first".to_string());
|
return Err("ffmpeg.exe not found - run the encoder setup first".to_string());
|
||||||
}
|
}
|
||||||
|
|
||||||
let (monitor_w, monitor_h) =
|
let (monitor_w, monitor_h) = capture::primary_monitor_dims().map_err(|e| format!("{e:#}"))?;
|
||||||
capture::primary_monitor_dims().map_err(|e| format!("{e:#}"))?;
|
|
||||||
|
|
||||||
let session = capture::start(
|
let session = capture::start(
|
||||||
output,
|
output,
|
||||||
@@ -639,7 +644,11 @@ fn pause_capture(state: State<'_, AppState>) -> Result<(), String> {
|
|||||||
let fixed_path = raw_path.with_extension("fixed.mp4");
|
let fixed_path = raw_path.with_extension("fixed.mp4");
|
||||||
capture::fix_intermediate_fps(&ffmpeg, &raw_path, &fixed_path, elapsed, frames, pipe_fps)
|
capture::fix_intermediate_fps(&ffmpeg, &raw_path, &fixed_path, elapsed, frames, pipe_fps)
|
||||||
.map_err(|e| format!("fixing fps: {e:#}"))?;
|
.map_err(|e| format!("fixing fps: {e:#}"))?;
|
||||||
let path = if fixed_path.exists() { fixed_path } else { raw_path };
|
let path = if fixed_path.exists() {
|
||||||
|
fixed_path
|
||||||
|
} else {
|
||||||
|
raw_path
|
||||||
|
};
|
||||||
|
|
||||||
let audio_path = lock(&state.audio).take().map(audio::AudioSession::stop);
|
let audio_path = lock(&state.audio).take().map(audio::AudioSession::stop);
|
||||||
|
|
||||||
@@ -649,9 +658,7 @@ fn pause_capture(state: State<'_, AppState>) -> Result<(), String> {
|
|||||||
.unwrap_or_default();
|
.unwrap_or_default();
|
||||||
|
|
||||||
let mut ss = lock(&state.session);
|
let mut ss = lock(&state.session);
|
||||||
let ss = ss
|
let ss = ss.as_mut().ok_or_else(|| "no session state".to_string())?;
|
||||||
.as_mut()
|
|
||||||
.ok_or_else(|| "no session state".to_string())?;
|
|
||||||
let offset = *ss.segment_start_offsets.last().unwrap_or(&0.0);
|
let offset = *ss.segment_start_offsets.last().unwrap_or(&0.0);
|
||||||
for c in new_clicks {
|
for c in new_clicks {
|
||||||
ss.clicks.push(clicks::Click {
|
ss.clicks.push(clicks::Click {
|
||||||
@@ -681,12 +688,7 @@ fn resume_capture(app: AppHandle, state: State<'_, AppState>) -> Result<(), Stri
|
|||||||
let ss = ss
|
let ss = ss
|
||||||
.as_ref()
|
.as_ref()
|
||||||
.ok_or_else(|| "no session to resume".to_string())?;
|
.ok_or_else(|| "no session to resume".to_string())?;
|
||||||
(
|
(ss.capture_cursor, ss.audio, ss.crop, ss.segments.len() + 1)
|
||||||
ss.capture_cursor,
|
|
||||||
ss.audio,
|
|
||||||
ss.crop,
|
|
||||||
ss.segments.len() + 1,
|
|
||||||
)
|
|
||||||
};
|
};
|
||||||
|
|
||||||
let (fps, quality) = {
|
let (fps, quality) = {
|
||||||
@@ -719,13 +721,12 @@ fn resume_capture(app: AppHandle, state: State<'_, AppState>) -> Result<(), Stri
|
|||||||
/// without ending the recording. Stops the current session, appends its
|
/// without ending the recording. Stops the current session, appends its
|
||||||
/// pcm segment to the session, and starts a new one with a fresh file.
|
/// pcm segment to the session, and starts a new one with a fresh file.
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
fn restart_audio_capture(
|
fn restart_audio_capture(app: AppHandle, state: State<'_, AppState>) -> Result<(), String> {
|
||||||
app: AppHandle,
|
|
||||||
state: State<'_, AppState>,
|
|
||||||
) -> Result<(), String> {
|
|
||||||
let audio_enabled = {
|
let audio_enabled = {
|
||||||
let ss = lock(&state.session);
|
let ss = lock(&state.session);
|
||||||
let ss = ss.as_ref().ok_or_else(|| "no session in progress".to_string())?;
|
let ss = ss
|
||||||
|
.as_ref()
|
||||||
|
.ok_or_else(|| "no session in progress".to_string())?;
|
||||||
if !ss.audio {
|
if !ss.audio {
|
||||||
return Err("audio is not enabled for this recording".to_string());
|
return Err("audio is not enabled for this recording".to_string());
|
||||||
}
|
}
|
||||||
@@ -736,7 +737,9 @@ fn restart_audio_capture(
|
|||||||
// or click recording - they keep running.
|
// or click recording - they keep running.
|
||||||
let next_idx = {
|
let next_idx = {
|
||||||
let mut ss = lock(&state.session);
|
let mut ss = lock(&state.session);
|
||||||
let ss = ss.as_mut().ok_or_else(|| "no session in progress".to_string())?;
|
let ss = ss
|
||||||
|
.as_mut()
|
||||||
|
.ok_or_else(|| "no session in progress".to_string())?;
|
||||||
if let Some(a) = lock(&state.audio).take() {
|
if let Some(a) = lock(&state.audio).take() {
|
||||||
ss.audio_segments.push(a.stop());
|
ss.audio_segments.push(a.stop());
|
||||||
}
|
}
|
||||||
@@ -780,7 +783,11 @@ fn stop_capture(state: State<'_, AppState>) -> Result<RecordedClip, String> {
|
|||||||
let fixed_path = raw_path.with_extension("fixed.mp4");
|
let fixed_path = raw_path.with_extension("fixed.mp4");
|
||||||
capture::fix_intermediate_fps(&ffmpeg, &raw_path, &fixed_path, elapsed, frames, pipe_fps)
|
capture::fix_intermediate_fps(&ffmpeg, &raw_path, &fixed_path, elapsed, frames, pipe_fps)
|
||||||
.map_err(|e| format!("fixing fps: {e:#}"))?;
|
.map_err(|e| format!("fixing fps: {e:#}"))?;
|
||||||
let final_path = if fixed_path.exists() { fixed_path } else { raw_path };
|
let final_path = if fixed_path.exists() {
|
||||||
|
fixed_path
|
||||||
|
} else {
|
||||||
|
raw_path
|
||||||
|
};
|
||||||
ss.segments.push(final_path);
|
ss.segments.push(final_path);
|
||||||
ss.total_recorded_secs += elapsed;
|
ss.total_recorded_secs += elapsed;
|
||||||
}
|
}
|
||||||
@@ -845,22 +852,12 @@ fn stop_capture(state: State<'_, AppState>) -> Result<RecordedClip, String> {
|
|||||||
if audio_start > video_start {
|
if audio_start > video_start {
|
||||||
let head_offset_secs = audio_start.duration_since(video_start).as_secs_f64();
|
let head_offset_secs = audio_start.duration_since(video_start).as_secs_f64();
|
||||||
if head_offset_secs > 0.001 {
|
if head_offset_secs > 0.001 {
|
||||||
pad_audio_head(
|
pad_audio_head(&audio_concat, sample_rate, channels, head_offset_secs)
|
||||||
&audio_concat,
|
|
||||||
sample_rate,
|
|
||||||
channels,
|
|
||||||
head_offset_secs,
|
|
||||||
)
|
|
||||||
.map_err(|e| format!("padding audio head: {e:#}"))?;
|
.map_err(|e| format!("padding audio head: {e:#}"))?;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
adjust_audio_length(
|
adjust_audio_length(&audio_concat, sample_rate, channels, ss.total_recorded_secs)
|
||||||
&audio_concat,
|
|
||||||
sample_rate,
|
|
||||||
channels,
|
|
||||||
ss.total_recorded_secs,
|
|
||||||
)
|
|
||||||
.map_err(|e| format!("adjusting audio length: {e:#}"))?;
|
.map_err(|e| format!("adjusting audio length: {e:#}"))?;
|
||||||
encode::mux_with_audio(
|
encode::mux_with_audio(
|
||||||
&ffmpeg,
|
&ffmpeg,
|
||||||
@@ -929,11 +926,7 @@ pub struct ExportRequest {
|
|||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
fn default_output_path(state: State<'_, AppState>, format: Format) -> String {
|
fn default_output_path(state: State<'_, AppState>, format: Format) -> String {
|
||||||
let dir = output_dir(&state.app_dir, &lock(&state.config));
|
let dir = output_dir(&state.app_dir, &lock(&state.config));
|
||||||
dir.join(format!(
|
dir.join(format!("bytesize-{}.{}", timestamp_slug(), ext_for(format)))
|
||||||
"bytesize-{}.{}",
|
|
||||||
timestamp_slug(),
|
|
||||||
ext_for(format)
|
|
||||||
))
|
|
||||||
.to_string_lossy()
|
.to_string_lossy()
|
||||||
.into_owned()
|
.into_owned()
|
||||||
}
|
}
|
||||||
@@ -960,10 +953,7 @@ pub struct PreviewRequest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[tauri::command(async)]
|
#[tauri::command(async)]
|
||||||
fn render_preview(
|
fn render_preview(state: State<'_, AppState>, request: PreviewRequest) -> Result<PathBuf, String> {
|
||||||
state: State<'_, AppState>,
|
|
||||||
request: PreviewRequest,
|
|
||||||
) -> Result<PathBuf, String> {
|
|
||||||
let clip = lock(&state.last_clip)
|
let clip = lock(&state.last_clip)
|
||||||
.clone()
|
.clone()
|
||||||
.ok_or_else(|| "no recorded clip available".to_string())?;
|
.ok_or_else(|| "no recorded clip available".to_string())?;
|
||||||
@@ -995,11 +985,24 @@ fn render_preview(
|
|||||||
GifDither::None => "none",
|
GifDither::None => "none",
|
||||||
};
|
};
|
||||||
encode::render_gif_preview(
|
encode::render_gif_preview(
|
||||||
&ffmpeg, &clip.temp_path, &preview_path, midpoint, target_width,
|
&ffmpeg,
|
||||||
request.gif_colors.unwrap_or(256), dither_str, clip.duration_secs,
|
&clip.temp_path,
|
||||||
).map_err(|e| format!("{e:#}"))?;
|
&preview_path,
|
||||||
|
midpoint,
|
||||||
|
target_width,
|
||||||
|
request.gif_colors.unwrap_or(256),
|
||||||
|
dither_str,
|
||||||
|
clip.duration_secs,
|
||||||
|
)
|
||||||
|
.map_err(|e| format!("{e:#}"))?;
|
||||||
} else {
|
} else {
|
||||||
encode::render_preview(&ffmpeg, &clip.temp_path, &preview_path, midpoint, target_width)
|
encode::render_preview(
|
||||||
|
&ffmpeg,
|
||||||
|
&clip.temp_path,
|
||||||
|
&preview_path,
|
||||||
|
midpoint,
|
||||||
|
target_width,
|
||||||
|
)
|
||||||
.map_err(|e| format!("{e:#}"))?;
|
.map_err(|e| format!("{e:#}"))?;
|
||||||
}
|
}
|
||||||
Ok(preview_path)
|
Ok(preview_path)
|
||||||
@@ -1040,16 +1043,28 @@ fn estimate_gif_params(request: PreviewRequest) -> GifEstimate {
|
|||||||
let height = encode::gif_height_for_width(w, request.clip_width, request.clip_height);
|
let height = encode::gif_height_for_width(w, request.clip_width, request.clip_height);
|
||||||
let dims_label = format!("{w}x{height} @ {fps}fps");
|
let dims_label = format!("{w}x{height} @ {fps}fps");
|
||||||
|
|
||||||
GifEstimate { width: w, fps, height, dims_label }
|
GifEstimate {
|
||||||
|
width: w,
|
||||||
|
fps,
|
||||||
|
height,
|
||||||
|
dims_label,
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Geometric grid from 100KB to 200MB, used to sample the GIF size estimator
|
/// Geometric grid from 100KB to 200MB, used to sample the GIF size estimator
|
||||||
/// across a range of targets so the frontend can interpolate locally.
|
/// across a range of targets so the frontend can interpolate locally.
|
||||||
const GIF_ESTIMATE_GRID: &[u64] = &[
|
const GIF_ESTIMATE_GRID: &[u64] = &[
|
||||||
100_000, 200_000, 500_000,
|
100_000,
|
||||||
1_048_576, 2_097_152, 5_242_880,
|
200_000,
|
||||||
10_485_760, 20_971_520, 52_428_800,
|
500_000,
|
||||||
104_857_600, 209_715_200,
|
1_048_576,
|
||||||
|
2_097_152,
|
||||||
|
5_242_880,
|
||||||
|
10_485_760,
|
||||||
|
20_971_520,
|
||||||
|
52_428_800,
|
||||||
|
104_857_600,
|
||||||
|
209_715_200,
|
||||||
];
|
];
|
||||||
|
|
||||||
/// The size-table scan sweeps target sizes itself, so it needs only the inputs
|
/// The size-table scan sweeps target sizes itself, so it needs only the inputs
|
||||||
@@ -1091,7 +1106,12 @@ fn estimate_gif_params_table(request: GifTableRequest) -> GifEstimateTable {
|
|||||||
};
|
};
|
||||||
let (w, f) = encode::gif_params(&budget, request.clip_width, request.clip_height);
|
let (w, f) = encode::gif_params(&budget, request.clip_width, request.clip_height);
|
||||||
let h = encode::gif_height_for_width(w, request.clip_width, request.clip_height);
|
let h = encode::gif_height_for_width(w, request.clip_width, request.clip_height);
|
||||||
points.push(GifEstimatePoint { target_bytes: target, width: w, fps: f, height: h });
|
points.push(GifEstimatePoint {
|
||||||
|
target_bytes: target,
|
||||||
|
width: w,
|
||||||
|
fps: f,
|
||||||
|
height: h,
|
||||||
|
});
|
||||||
}
|
}
|
||||||
GifEstimateTable { points }
|
GifEstimateTable { points }
|
||||||
}
|
}
|
||||||
@@ -1150,12 +1170,21 @@ mod tests {
|
|||||||
|
|
||||||
// Mid-session: drop the recording artifacts, keep the live previews.
|
// Mid-session: drop the recording artifacts, keep the live previews.
|
||||||
clear_temp_segments(&dir, true);
|
clear_temp_segments(&dir, true);
|
||||||
assert!(!temp.join("audio-concat.pcm.padtmp").exists(), "padtmp should be swept");
|
assert!(
|
||||||
|
!temp.join("audio-concat.pcm.padtmp").exists(),
|
||||||
|
"padtmp should be swept"
|
||||||
|
);
|
||||||
assert!(!temp.join("segment-001.mp4").exists());
|
assert!(!temp.join("segment-001.mp4").exists());
|
||||||
assert!(!temp.join("audio-001.pcm").exists());
|
assert!(!temp.join("audio-001.pcm").exists());
|
||||||
assert!(!temp.join("ffmpeg2pass-0.log").exists(), "pass stats should be swept");
|
assert!(
|
||||||
|
!temp.join("ffmpeg2pass-0.log").exists(),
|
||||||
|
"pass stats should be swept"
|
||||||
|
);
|
||||||
assert!(!temp.join("ffmpeg2pass-0.log.mbtree").exists());
|
assert!(!temp.join("ffmpeg2pass-0.log.mbtree").exists());
|
||||||
assert!(temp.join("preview.png").exists(), "preview must survive a new capture");
|
assert!(
|
||||||
|
temp.join("preview.png").exists(),
|
||||||
|
"preview must survive a new capture"
|
||||||
|
);
|
||||||
assert!(temp.join("raw-preview.png").exists());
|
assert!(temp.join("raw-preview.png").exists());
|
||||||
|
|
||||||
// Exit/startup: everything goes.
|
// Exit/startup: everything goes.
|
||||||
@@ -1167,7 +1196,8 @@ mod tests {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn estimate_balanced_matches_gif_params() { // The frontend uses estimate_gif_params for the on-screen dims label.
|
fn estimate_balanced_matches_gif_params() {
|
||||||
|
// The frontend uses estimate_gif_params for the on-screen dims label.
|
||||||
// The backend uses gif_params for the actual encode. The two must agree.
|
// The backend uses gif_params for the actual encode. The two must agree.
|
||||||
let req = make_request(8 * 1024 * 1024, 30, GifBudgetMode::Balanced);
|
let req = make_request(8 * 1024 * 1024, 30, GifBudgetMode::Balanced);
|
||||||
let est = estimate_gif_params(req);
|
let est = estimate_gif_params(req);
|
||||||
@@ -1187,7 +1217,10 @@ mod tests {
|
|||||||
let expected_height = encode::gif_height_for_width(encode_w, 1920, 1080);
|
let expected_height = encode::gif_height_for_width(encode_w, 1920, 1080);
|
||||||
assert_eq!(est.height, expected_height);
|
assert_eq!(est.height, expected_height);
|
||||||
// dims_label should be "{w}x{h} @ {fps}fps"
|
// dims_label should be "{w}x{h} @ {fps}fps"
|
||||||
assert_eq!(est.dims_label, format!("{}x{} @ {}fps", encode_w, est.height, encode_fps));
|
assert_eq!(
|
||||||
|
est.dims_label,
|
||||||
|
format!("{}x{} @ {}fps", encode_w, est.height, encode_fps)
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
@@ -1201,10 +1234,7 @@ mod tests {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[tauri::command(async)]
|
#[tauri::command(async)]
|
||||||
fn extract_thumbnails(
|
fn extract_thumbnails(state: State<'_, AppState>, fps: u32) -> Result<Vec<PathBuf>, String> {
|
||||||
state: State<'_, AppState>,
|
|
||||||
fps: u32,
|
|
||||||
) -> Result<Vec<PathBuf>, String> {
|
|
||||||
let clip = lock(&state.last_clip)
|
let clip = lock(&state.last_clip)
|
||||||
.clone()
|
.clone()
|
||||||
.ok_or_else(|| "no recorded clip available".to_string())?;
|
.ok_or_else(|| "no recorded clip available".to_string())?;
|
||||||
@@ -1218,10 +1248,7 @@ fn extract_thumbnails(
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[tauri::command(async)]
|
#[tauri::command(async)]
|
||||||
fn render_raw_preview(
|
fn render_raw_preview(state: State<'_, AppState>, timestamp: f64) -> Result<PathBuf, String> {
|
||||||
state: State<'_, AppState>,
|
|
||||||
timestamp: f64,
|
|
||||||
) -> Result<PathBuf, String> {
|
|
||||||
let clip = lock(&state.last_clip)
|
let clip = lock(&state.last_clip)
|
||||||
.clone()
|
.clone()
|
||||||
.ok_or_else(|| "no recorded clip available".to_string())?;
|
.ok_or_else(|| "no recorded clip available".to_string())?;
|
||||||
@@ -1230,7 +1257,13 @@ fn render_raw_preview(
|
|||||||
return Err("ffmpeg.exe not found".to_string());
|
return Err("ffmpeg.exe not found".to_string());
|
||||||
}
|
}
|
||||||
let out_path = temp_dir(&state.app_dir).join("raw-preview.png");
|
let out_path = temp_dir(&state.app_dir).join("raw-preview.png");
|
||||||
encode::render_preview(&ffmpeg, &clip.temp_path, &out_path, timestamp, clip.width.min(1280))
|
encode::render_preview(
|
||||||
|
&ffmpeg,
|
||||||
|
&clip.temp_path,
|
||||||
|
&out_path,
|
||||||
|
timestamp,
|
||||||
|
clip.width.min(1280),
|
||||||
|
)
|
||||||
.map_err(|e| format!("{e:#}"))?;
|
.map_err(|e| format!("{e:#}"))?;
|
||||||
Ok(out_path)
|
Ok(out_path)
|
||||||
}
|
}
|
||||||
@@ -1246,7 +1279,6 @@ pub struct ExportResult {
|
|||||||
const OVERLAY_BORDER_LOGICAL_PX: f64 = 4.0;
|
const OVERLAY_BORDER_LOGICAL_PX: f64 = 4.0;
|
||||||
const OVERLAY_TITLEBAR_LOGICAL_PX: f64 = 24.0;
|
const OVERLAY_TITLEBAR_LOGICAL_PX: f64 = 24.0;
|
||||||
|
|
||||||
|
|
||||||
/// Remove temporary recording artifacts (segments, previews, thumbs).
|
/// Remove temporary recording artifacts (segments, previews, thumbs).
|
||||||
/// Called on app exit so a discarded clip doesn't linger in `temp/`.
|
/// Called on app exit so a discarded clip doesn't linger in `temp/`.
|
||||||
fn cleanup_temp_on_exit(app: &AppHandle) {
|
fn cleanup_temp_on_exit(app: &AppHandle) {
|
||||||
@@ -1299,12 +1331,7 @@ fn overlay_should_ignore_cursor(app: &AppHandle) -> Option<bool> {
|
|||||||
let inner_right = vr - border;
|
let inner_right = vr - border;
|
||||||
let inner_bottom = vb - border;
|
let inner_bottom = vb - border;
|
||||||
|
|
||||||
Some(
|
Some(pt.x >= inner_left && pt.x < inner_right && pt.y >= inner_top && pt.y < inner_bottom)
|
||||||
pt.x >= inner_left
|
|
||||||
&& pt.x < inner_right
|
|
||||||
&& pt.y >= inner_top
|
|
||||||
&& pt.y < inner_bottom,
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn start_overlay_clickthrough_poll(
|
fn start_overlay_clickthrough_poll(
|
||||||
@@ -1323,7 +1350,9 @@ fn start_overlay_clickthrough_poll(
|
|||||||
// flips the flag and notifies.
|
// flips the flag and notifies.
|
||||||
{
|
{
|
||||||
let (lock, cvar) = &*live;
|
let (lock, cvar) = &*live;
|
||||||
let mut active = lock.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
|
let mut active = lock
|
||||||
|
.lock()
|
||||||
|
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||||
while !*active && !shutdown.load(Ordering::Relaxed) {
|
while !*active && !shutdown.load(Ordering::Relaxed) {
|
||||||
let (g, _timeout) = cvar
|
let (g, _timeout) = cvar
|
||||||
.wait_timeout(active, Duration::from_secs(1))
|
.wait_timeout(active, Duration::from_secs(1))
|
||||||
@@ -1334,8 +1363,7 @@ fn start_overlay_clickthrough_poll(
|
|||||||
|
|
||||||
let target = overlay_should_ignore_cursor(&app);
|
let target = overlay_should_ignore_cursor(&app);
|
||||||
if target != last {
|
if target != last {
|
||||||
if let (Some(overlay), Some(value)) = (app.get_webview_window("overlay"), target)
|
if let (Some(overlay), Some(value)) = (app.get_webview_window("overlay"), target) {
|
||||||
{
|
|
||||||
drop(overlay.set_ignore_cursor_events(value));
|
drop(overlay.set_ignore_cursor_events(value));
|
||||||
}
|
}
|
||||||
last = target;
|
last = target;
|
||||||
@@ -1369,9 +1397,12 @@ fn mark_overlay_excluded_from_capture(win: &tauri::WebviewWindow) -> Result<(),
|
|||||||
fn show_overlay(app: AppHandle) -> Result<(), String> {
|
fn show_overlay(app: AppHandle) -> Result<(), String> {
|
||||||
use windows::Win32::Foundation::{HWND, POINT};
|
use windows::Win32::Foundation::{HWND, POINT};
|
||||||
use windows::Win32::Graphics::Gdi::{
|
use windows::Win32::Graphics::Gdi::{
|
||||||
GetMonitorInfoW, MonitorFromPoint, MONITOR_DEFAULTTOPRIMARY, MONITOR_DEFAULTTONULL, MONITORINFO,
|
GetMonitorInfoW, MonitorFromPoint, MONITORINFO, MONITOR_DEFAULTTONULL,
|
||||||
|
MONITOR_DEFAULTTOPRIMARY,
|
||||||
|
};
|
||||||
|
use windows::Win32::UI::WindowsAndMessaging::{
|
||||||
|
SetWindowPos, HWND_TOP, SWP_NOACTIVATE, SWP_NOSIZE, SWP_NOZORDER,
|
||||||
};
|
};
|
||||||
use windows::Win32::UI::WindowsAndMessaging::{SetWindowPos, HWND_TOP, SWP_NOACTIVATE, SWP_NOSIZE, SWP_NOZORDER};
|
|
||||||
|
|
||||||
let win = app
|
let win = app
|
||||||
.get_webview_window("overlay")
|
.get_webview_window("overlay")
|
||||||
@@ -1383,14 +1414,19 @@ fn show_overlay(app: AppHandle) -> Result<(), String> {
|
|||||||
{
|
{
|
||||||
let st = app.state::<AppState>();
|
let st = app.state::<AppState>();
|
||||||
let (lock, cvar) = &*st.overlay_poll_live;
|
let (lock, cvar) = &*st.overlay_poll_live;
|
||||||
*lock.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = true;
|
*lock
|
||||||
|
.lock()
|
||||||
|
.unwrap_or_else(std::sync::PoisonError::into_inner) = true;
|
||||||
cvar.notify_one();
|
cvar.notify_one();
|
||||||
}
|
}
|
||||||
|
|
||||||
// If the overlay is off-screen (monitor disconnected), center on primary
|
// If the overlay is off-screen (monitor disconnected), center on primary
|
||||||
if let Ok(raw) = win.hwnd() {
|
if let Ok(raw) = win.hwnd() {
|
||||||
if let Some((vl, vt, vr, vb)) = visible_window_bounds(raw.0 as isize) {
|
if let Some((vl, vt, vr, vb)) = visible_window_bounds(raw.0 as isize) {
|
||||||
let center = POINT { x: i32::midpoint(vl, vr), y: i32::midpoint(vt, vb) };
|
let center = POINT {
|
||||||
|
x: i32::midpoint(vl, vr),
|
||||||
|
y: i32::midpoint(vt, vb),
|
||||||
|
};
|
||||||
// MonitorFromPoint only reads the POINT by value and returns null
|
// MonitorFromPoint only reads the POINT by value and returns null
|
||||||
// for "no monitor", which the next branch handles.
|
// for "no monitor", which the next branch handles.
|
||||||
//
|
//
|
||||||
@@ -1400,10 +1436,14 @@ fn show_overlay(app: AppHandle) -> Result<(), String> {
|
|||||||
let hwnd = HWND(raw.0.cast::<std::ffi::c_void>());
|
let hwnd = HWND(raw.0.cast::<std::ffi::c_void>());
|
||||||
// SAFETY: same value-only call; MONITOR_DEFAULTTOPRIMARY cannot
|
// SAFETY: same value-only call; MONITOR_DEFAULTTOPRIMARY cannot
|
||||||
// fail on a running desktop.
|
// fail on a running desktop.
|
||||||
let primary = unsafe { MonitorFromPoint(POINT { x: 0, y: 0 }, MONITOR_DEFAULTTOPRIMARY) };
|
let primary =
|
||||||
|
unsafe { MonitorFromPoint(POINT { x: 0, y: 0 }, MONITOR_DEFAULTTOPRIMARY) };
|
||||||
// cbSize is required by GetMonitorInfoW and is set from the
|
// cbSize is required by GetMonitorInfoW and is set from the
|
||||||
// actual struct size, so the write below stays in bounds.
|
// actual struct size, so the write below stays in bounds.
|
||||||
let mut mi = MONITORINFO { cbSize: u32::try_from(size_of::<MONITORINFO>()).unwrap_or(0), ..Default::default() };
|
let mut mi = MONITORINFO {
|
||||||
|
cbSize: u32::try_from(size_of::<MONITORINFO>()).unwrap_or(0),
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
// SAFETY: `mi` is a live local of the declared size, and the
|
// SAFETY: `mi` is a live local of the declared size, and the
|
||||||
// result is checked with as_bool() before mi is read.
|
// result is checked with as_bool() before mi is read.
|
||||||
if unsafe { GetMonitorInfoW(primary, &raw mut mi) }.as_bool() {
|
if unsafe { GetMonitorInfoW(primary, &raw mut mi) }.as_bool() {
|
||||||
@@ -1415,7 +1455,17 @@ fn show_overlay(app: AppHandle) -> Result<(), String> {
|
|||||||
drop(
|
drop(
|
||||||
// SAFETY: `hwnd` is the overlay's live handle; the flags
|
// SAFETY: `hwnd` is the overlay's live handle; the flags
|
||||||
// keep this a size-only, non-activating move.
|
// keep this a size-only, non-activating move.
|
||||||
unsafe { SetWindowPos(hwnd, Some(HWND_TOP), cx, cy, 0, 0, SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOSIZE) },
|
unsafe {
|
||||||
|
SetWindowPos(
|
||||||
|
hwnd,
|
||||||
|
Some(HWND_TOP),
|
||||||
|
cx,
|
||||||
|
cy,
|
||||||
|
0,
|
||||||
|
0,
|
||||||
|
SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOSIZE,
|
||||||
|
)
|
||||||
|
},
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1435,14 +1485,21 @@ fn hide_overlay(app: AppHandle) -> Result<(), String> {
|
|||||||
{
|
{
|
||||||
let st = app.state::<AppState>();
|
let st = app.state::<AppState>();
|
||||||
let (lock, cvar) = &*st.overlay_poll_live;
|
let (lock, cvar) = &*st.overlay_poll_live;
|
||||||
*lock.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = false;
|
*lock
|
||||||
|
.lock()
|
||||||
|
.unwrap_or_else(std::sync::PoisonError::into_inner) = false;
|
||||||
cvar.notify_one();
|
cvar.notify_one();
|
||||||
}
|
}
|
||||||
win.hide().map_err(|e| format!("hiding overlay: {e:#}"))
|
win.hide().map_err(|e| format!("hiding overlay: {e:#}"))
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
fn set_overlay_size(app: AppHandle, state: State<'_, AppState>, width: u32, height: u32) -> Result<(), String> {
|
fn set_overlay_size(
|
||||||
|
app: AppHandle,
|
||||||
|
state: State<'_, AppState>,
|
||||||
|
width: u32,
|
||||||
|
height: u32,
|
||||||
|
) -> Result<(), String> {
|
||||||
use tauri::{LogicalSize, Size};
|
use tauri::{LogicalSize, Size};
|
||||||
let win = app
|
let win = app
|
||||||
.get_webview_window("overlay")
|
.get_webview_window("overlay")
|
||||||
@@ -1460,7 +1517,11 @@ fn set_overlay_size(app: AppHandle, state: State<'_, AppState>, width: u32, heig
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
fn set_overlay_aspect(app: AppHandle, state: State<'_, AppState>, ratio: Option<f64>) -> Result<(), String> {
|
fn set_overlay_aspect(
|
||||||
|
app: AppHandle,
|
||||||
|
state: State<'_, AppState>,
|
||||||
|
ratio: Option<f64>,
|
||||||
|
) -> Result<(), String> {
|
||||||
*lock(&state.overlay_aspect_ratio) = ratio;
|
*lock(&state.overlay_aspect_ratio) = ratio;
|
||||||
if let Some(r) = ratio {
|
if let Some(r) = ratio {
|
||||||
// Enforce on current size
|
// Enforce on current size
|
||||||
@@ -1468,14 +1529,17 @@ fn set_overlay_aspect(app: AppHandle, state: State<'_, AppState>, ratio: Option<
|
|||||||
.get_webview_window("overlay")
|
.get_webview_window("overlay")
|
||||||
.ok_or_else(|| "overlay window not found".to_string())?;
|
.ok_or_else(|| "overlay window not found".to_string())?;
|
||||||
let scale = win.scale_factor().unwrap_or(1.0);
|
let scale = win.scale_factor().unwrap_or(1.0);
|
||||||
let sz = win.inner_size().map_err(|e| format!("getting window size: {e:#}"))?;
|
let sz = win
|
||||||
|
.inner_size()
|
||||||
|
.map_err(|e| format!("getting window size: {e:#}"))?;
|
||||||
let cur_w = f64::from(sz.width) / scale;
|
let cur_w = f64::from(sz.width) / scale;
|
||||||
let cur_h = f64::from(sz.height) / scale;
|
let cur_h = f64::from(sz.height) / scale;
|
||||||
let target_h = cur_w / r;
|
let target_h = cur_w / r;
|
||||||
if (target_h - cur_h).abs() > 1.0 {
|
if (target_h - cur_h).abs() > 1.0 {
|
||||||
use tauri::{LogicalSize, Size};
|
use tauri::{LogicalSize, Size};
|
||||||
let final_w = cur_w + (OVERLAY_BORDER_LOGICAL_PX * 2.0);
|
let final_w = cur_w + (OVERLAY_BORDER_LOGICAL_PX * 2.0);
|
||||||
let final_h = target_h + OVERLAY_TITLEBAR_LOGICAL_PX + (OVERLAY_BORDER_LOGICAL_PX * 2.0);
|
let final_h =
|
||||||
|
target_h + OVERLAY_TITLEBAR_LOGICAL_PX + (OVERLAY_BORDER_LOGICAL_PX * 2.0);
|
||||||
win.set_size(Size::Logical(LogicalSize::new(final_w, final_h)))
|
win.set_size(Size::Logical(LogicalSize::new(final_w, final_h)))
|
||||||
.map_err(|e| format!("setting overlay size: {e:#}"))?;
|
.map_err(|e| format!("setting overlay size: {e:#}"))?;
|
||||||
}
|
}
|
||||||
@@ -1491,7 +1555,9 @@ fn get_overlay_aspect(state: State<'_, AppState>) -> Option<f64> {
|
|||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
fn enforce_overlay_aspect(app: AppHandle, state: State<'_, AppState>) -> Result<(), String> {
|
fn enforce_overlay_aspect(app: AppHandle, state: State<'_, AppState>) -> Result<(), String> {
|
||||||
use windows::Win32::Foundation::HWND;
|
use windows::Win32::Foundation::HWND;
|
||||||
use windows::Win32::UI::WindowsAndMessaging::{SetWindowPos, HWND_TOP, SWP_NOACTIVATE, SWP_NOMOVE, SWP_NOZORDER};
|
use windows::Win32::UI::WindowsAndMessaging::{
|
||||||
|
SetWindowPos, HWND_TOP, SWP_NOACTIVATE, SWP_NOMOVE, SWP_NOZORDER,
|
||||||
|
};
|
||||||
|
|
||||||
let Some(ratio) = *lock(&state.overlay_aspect_ratio) else {
|
let Some(ratio) = *lock(&state.overlay_aspect_ratio) else {
|
||||||
return Ok(());
|
return Ok(());
|
||||||
@@ -1500,7 +1566,9 @@ fn enforce_overlay_aspect(app: AppHandle, state: State<'_, AppState>) -> Result<
|
|||||||
.get_webview_window("overlay")
|
.get_webview_window("overlay")
|
||||||
.ok_or_else(|| "overlay window not found".to_string())?;
|
.ok_or_else(|| "overlay window not found".to_string())?;
|
||||||
let scale = win.scale_factor().unwrap_or(1.0);
|
let scale = win.scale_factor().unwrap_or(1.0);
|
||||||
let sz = win.inner_size().map_err(|e| format!("getting window size: {e:#}"))?;
|
let sz = win
|
||||||
|
.inner_size()
|
||||||
|
.map_err(|e| format!("getting window size: {e:#}"))?;
|
||||||
let cur_w = f64::from(sz.width) / scale;
|
let cur_w = f64::from(sz.width) / scale;
|
||||||
let cur_h = f64::from(sz.height) / scale;
|
let cur_h = f64::from(sz.height) / scale;
|
||||||
let target_h = (cur_w / ratio).round();
|
let target_h = (cur_w / ratio).round();
|
||||||
@@ -1514,13 +1582,22 @@ fn enforce_overlay_aspect(app: AppHandle, state: State<'_, AppState>) -> Result<
|
|||||||
let border = encode::round_i32(OVERLAY_BORDER_LOGICAL_PX * scale);
|
let border = encode::round_i32(OVERLAY_BORDER_LOGICAL_PX * scale);
|
||||||
let titlebar = encode::round_i32(OVERLAY_TITLEBAR_LOGICAL_PX * scale);
|
let titlebar = encode::round_i32(OVERLAY_TITLEBAR_LOGICAL_PX * scale);
|
||||||
let outer_w = sz.width.cast_signed().max(2);
|
let outer_w = sz.width.cast_signed().max(2);
|
||||||
let outer_h = encode::round_i32(target_h * scale + f64::from(titlebar) + f64::from(border) * 2.0);
|
let outer_h =
|
||||||
|
encode::round_i32(target_h * scale + f64::from(titlebar) + f64::from(border) * 2.0);
|
||||||
// SAFETY: `hwnd` is the overlay's live handle; the flags keep the resize
|
// SAFETY: `hwnd` is the overlay's live handle; the flags keep the resize
|
||||||
// non-activating and non-reordering, and no pointers are involved.
|
// non-activating and non-reordering, and no pointers are involved.
|
||||||
unsafe {
|
unsafe {
|
||||||
SetWindowPos(hwnd, Some(HWND_TOP), 0, 0, outer_w, outer_h,
|
SetWindowPos(
|
||||||
SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOMOVE)
|
hwnd,
|
||||||
}.map_err(|e| format!("SetWindowPos: {e}"))?;
|
Some(HWND_TOP),
|
||||||
|
0,
|
||||||
|
0,
|
||||||
|
outer_w,
|
||||||
|
outer_h,
|
||||||
|
SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOMOVE,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
.map_err(|e| format!("SetWindowPos: {e}"))?;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1530,14 +1607,10 @@ fn list_windows() -> Vec<windows_list::WindowInfo> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
fn open_window_picker(
|
fn open_window_picker(app: AppHandle, state: State<'_, AppState>) -> Result<(), String> {
|
||||||
app: AppHandle,
|
|
||||||
state: State<'_, AppState>,
|
|
||||||
) -> Result<(), String> {
|
|
||||||
use tauri::{PhysicalPosition, PhysicalSize, Position, Size};
|
use tauri::{PhysicalPosition, PhysicalSize, Position, Size};
|
||||||
|
|
||||||
let (mw, mh) =
|
let (mw, mh) = capture::primary_monitor_dims().map_err(|e| format!("{e:#}"))?;
|
||||||
capture::primary_monitor_dims().map_err(|e| format!("{e:#}"))?;
|
|
||||||
|
|
||||||
let mut exclude: Vec<isize> = Vec::new();
|
let mut exclude: Vec<isize> = Vec::new();
|
||||||
for label in &["main", "overlay", "picker"] {
|
for label in &["main", "overlay", "picker"] {
|
||||||
@@ -1565,7 +1638,9 @@ fn open_window_picker(
|
|||||||
.map_err(|e| format!("setting picker position: {e:#}"))?;
|
.map_err(|e| format!("setting picker position: {e:#}"))?;
|
||||||
drop(picker.set_ignore_cursor_events(false));
|
drop(picker.set_ignore_cursor_events(false));
|
||||||
drop(picker.set_always_on_top(true));
|
drop(picker.set_always_on_top(true));
|
||||||
picker.show().map_err(|e| format!("showing picker: {e:#}"))?;
|
picker
|
||||||
|
.show()
|
||||||
|
.map_err(|e| format!("showing picker: {e:#}"))?;
|
||||||
if let Ok(h) = picker.hwnd() {
|
if let Ok(h) = picker.hwnd() {
|
||||||
use windows::Win32::Foundation::{HWND, RECT};
|
use windows::Win32::Foundation::{HWND, RECT};
|
||||||
use windows::Win32::Graphics::Dwm::{DwmGetWindowAttribute, DWMWA_EXTENDED_FRAME_BOUNDS};
|
use windows::Win32::Graphics::Dwm::{DwmGetWindowAttribute, DWMWA_EXTENDED_FRAME_BOUNDS};
|
||||||
@@ -1587,8 +1662,14 @@ fn open_window_picker(
|
|||||||
});
|
});
|
||||||
tracing::debug!(
|
tracing::debug!(
|
||||||
"picker window: GetWindowRect=({},{},{},{}) DwmBounds=({},{},{},{})",
|
"picker window: GetWindowRect=({},{},{},{}) DwmBounds=({},{},{},{})",
|
||||||
gr.left, gr.top, gr.right, gr.bottom,
|
gr.left,
|
||||||
dr.left, dr.top, dr.right, dr.bottom
|
gr.top,
|
||||||
|
gr.right,
|
||||||
|
gr.bottom,
|
||||||
|
dr.left,
|
||||||
|
dr.top,
|
||||||
|
dr.right,
|
||||||
|
dr.bottom
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1609,10 +1690,7 @@ fn open_window_picker(
|
|||||||
clippy::unnecessary_wraps,
|
clippy::unnecessary_wraps,
|
||||||
reason = "Result is part of the tauri::command contract the frontend invokes"
|
reason = "Result is part of the tauri::command contract the frontend invokes"
|
||||||
)]
|
)]
|
||||||
fn close_window_picker(
|
fn close_window_picker(app: AppHandle, state: State<'_, AppState>) -> Result<(), String> {
|
||||||
app: AppHandle,
|
|
||||||
state: State<'_, AppState>,
|
|
||||||
) -> Result<(), String> {
|
|
||||||
if let Some(session) = lock(&state.picker).take() {
|
if let Some(session) = lock(&state.picker).take() {
|
||||||
session.stop();
|
session.stop();
|
||||||
}
|
}
|
||||||
@@ -1786,11 +1864,13 @@ fn get_overlay_rect(app: AppHandle) -> Result<CaptureRect, String> {
|
|||||||
let win = app
|
let win = app
|
||||||
.get_webview_window("overlay")
|
.get_webview_window("overlay")
|
||||||
.ok_or_else(|| "overlay window not found".to_string())?;
|
.ok_or_else(|| "overlay window not found".to_string())?;
|
||||||
let scale = win.scale_factor().map_err(|e| format!("getting scale factor: {e:#}"))?;
|
let scale = win
|
||||||
|
.scale_factor()
|
||||||
|
.map_err(|e| format!("getting scale factor: {e:#}"))?;
|
||||||
let raw = win.hwnd().map_err(|e| format!("hwnd: {e}"))?;
|
let raw = win.hwnd().map_err(|e| format!("hwnd: {e}"))?;
|
||||||
|
|
||||||
let (vl, vt, vr, vb) = visible_window_bounds(raw.0 as isize)
|
let (vl, vt, vr, vb) =
|
||||||
.ok_or_else(|| "GetWindowRect failed".to_string())?;
|
visible_window_bounds(raw.0 as isize).ok_or_else(|| "GetWindowRect failed".to_string())?;
|
||||||
|
|
||||||
let border_phys = encode::round_i32(OVERLAY_BORDER_LOGICAL_PX * scale);
|
let border_phys = encode::round_i32(OVERLAY_BORDER_LOGICAL_PX * scale);
|
||||||
let titlebar_phys = encode::round_i32(OVERLAY_TITLEBAR_LOGICAL_PX * scale);
|
let titlebar_phys = encode::round_i32(OVERLAY_TITLEBAR_LOGICAL_PX * scale);
|
||||||
@@ -1821,7 +1901,8 @@ fn reveal_in_explorer(path: String) -> Result<(), String> {
|
|||||||
|
|
||||||
let canonical = std::fs::canonicalize(&path).ok();
|
let canonical = std::fs::canonicalize(&path).ok();
|
||||||
let normalized = canonical
|
let normalized = canonical
|
||||||
.as_ref().map_or_else(|| path.clone(), |p| p.to_string_lossy().into_owned());
|
.as_ref()
|
||||||
|
.map_or_else(|| path.clone(), |p| p.to_string_lossy().into_owned());
|
||||||
let stripped = normalized
|
let stripped = normalized
|
||||||
.strip_prefix(r"\\?\")
|
.strip_prefix(r"\\?\")
|
||||||
.unwrap_or(&normalized)
|
.unwrap_or(&normalized)
|
||||||
@@ -1889,8 +1970,12 @@ fn read_log_tail(log_dir: &Path) -> String {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
let Some((_, path)) = newest else { return String::new() };
|
let Some((_, path)) = newest else {
|
||||||
let Ok(data) = std::fs::read(&path) else { return String::new() };
|
return String::new();
|
||||||
|
};
|
||||||
|
let Ok(data) = std::fs::read(&path) else {
|
||||||
|
return String::new();
|
||||||
|
};
|
||||||
// saturating_sub keeps start at or below data.len(), so the tail slice
|
// saturating_sub keeps start at or below data.len(), so the tail slice
|
||||||
// always exists; get() just makes that explicit.
|
// always exists; get() just makes that explicit.
|
||||||
let start = data.len().saturating_sub(TAIL_BYTES);
|
let start = data.len().saturating_sub(TAIL_BYTES);
|
||||||
@@ -1976,7 +2061,11 @@ impl Drop for ExportGuard {
|
|||||||
reason = "one export transaction; the request translation feeds directly into the encode call"
|
reason = "one export transaction; the request translation feeds directly into the encode call"
|
||||||
)]
|
)]
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
async fn export(app: AppHandle, state: State<'_, AppState>, request: ExportRequest) -> Result<ExportResult, String> {
|
async fn export(
|
||||||
|
app: AppHandle,
|
||||||
|
state: State<'_, AppState>,
|
||||||
|
request: ExportRequest,
|
||||||
|
) -> Result<ExportResult, String> {
|
||||||
if state.exporting.swap(true, Ordering::SeqCst) {
|
if state.exporting.swap(true, Ordering::SeqCst) {
|
||||||
return Err("an export is already running".to_string());
|
return Err("an export is already running".to_string());
|
||||||
}
|
}
|
||||||
@@ -1987,7 +2076,12 @@ async fn export(app: AppHandle, state: State<'_, AppState>, request: ExportReque
|
|||||||
let clip = lock(&state.last_clip)
|
let clip = lock(&state.last_clip)
|
||||||
.clone()
|
.clone()
|
||||||
.ok_or_else(|| "no recorded clip available".to_string())?;
|
.ok_or_else(|| "no recorded clip available".to_string())?;
|
||||||
(cfg, clip, state.app_dir.clone(), state.export_cancel.clone())
|
(
|
||||||
|
cfg,
|
||||||
|
clip,
|
||||||
|
state.app_dir.clone(),
|
||||||
|
state.export_cancel.clone(),
|
||||||
|
)
|
||||||
};
|
};
|
||||||
|
|
||||||
let ffmpeg = bootstrap::ffmpeg_path(&app_dir);
|
let ffmpeg = bootstrap::ffmpeg_path(&app_dir);
|
||||||
@@ -2007,8 +2101,7 @@ async fn export(app: AppHandle, state: State<'_, AppState>, request: ExportReque
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
if let Some(parent) = out_path.parent() {
|
if let Some(parent) = out_path.parent() {
|
||||||
std::fs::create_dir_all(parent)
|
std::fs::create_dir_all(parent).map_err(|e| format!("creating output dir: {e:#}"))?;
|
||||||
.map_err(|e| format!("creating output dir: {e:#}"))?;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
let trim_start = request.trim_start_secs.filter(|s| *s > 0.001);
|
let trim_start = request.trim_start_secs.filter(|s| *s > 0.001);
|
||||||
@@ -2025,12 +2118,7 @@ async fn export(app: AppHandle, state: State<'_, AppState>, request: ExportReque
|
|||||||
let (src_w, src_origin) = if let Some(c) = clip.crop {
|
let (src_w, src_origin) = if let Some(c) = clip.crop {
|
||||||
(c.width, (c.x, c.y))
|
(c.width, (c.x, c.y))
|
||||||
} else {
|
} else {
|
||||||
(
|
(clip.monitor_width.max(1), (0, 0))
|
||||||
clip
|
|
||||||
.monitor_width
|
|
||||||
.max(1),
|
|
||||||
(0, 0),
|
|
||||||
)
|
|
||||||
};
|
};
|
||||||
let scale = f64::from(clip.width) / f64::from(src_w);
|
let scale = f64::from(clip.width) / f64::from(src_w);
|
||||||
let transformed_clicks: Vec<clicks::Click> = clip
|
let transformed_clicks: Vec<clicks::Click> = clip
|
||||||
@@ -2103,8 +2191,7 @@ async fn export(app: AppHandle, state: State<'_, AppState>, request: ExportReque
|
|||||||
.map_err(|e| format!("encode task panicked: {e:#}"))?;
|
.map_err(|e| format!("encode task panicked: {e:#}"))?;
|
||||||
result.map_err(|e| format!("{e:#}"))?;
|
result.map_err(|e| format!("{e:#}"))?;
|
||||||
|
|
||||||
let size_bytes = std::fs::metadata(&out_path)
|
let size_bytes = std::fs::metadata(&out_path).map_or(0, |m| m.len());
|
||||||
.map_or(0, |m| m.len());
|
|
||||||
Ok(ExportResult {
|
Ok(ExportResult {
|
||||||
met_target: size_bytes <= request.target_bytes,
|
met_target: size_bytes <= request.target_bytes,
|
||||||
target_bytes: request.target_bytes,
|
target_bytes: request.target_bytes,
|
||||||
@@ -2148,7 +2235,9 @@ pub fn run() {
|
|||||||
let file_layer = tracing_subscriber::fmt::layer()
|
let file_layer = tracing_subscriber::fmt::layer()
|
||||||
.with_writer(file_writer)
|
.with_writer(file_writer)
|
||||||
.with_ansi(false);
|
.with_ansi(false);
|
||||||
let registry = tracing_subscriber::registry().with(env_filter).with(file_layer);
|
let registry = tracing_subscriber::registry()
|
||||||
|
.with(env_filter)
|
||||||
|
.with(file_layer);
|
||||||
#[cfg(debug_assertions)]
|
#[cfg(debug_assertions)]
|
||||||
let registry = registry.with(tracing_subscriber::fmt::layer().with_writer(std::io::stdout));
|
let registry = registry.with(tracing_subscriber::fmt::layer().with_writer(std::io::stdout));
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
@@ -2166,8 +2255,13 @@ pub fn run() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
tracing::error!("could not create webview data dir at {}: {e}", webview_dir.display());
|
tracing::error!(
|
||||||
tracing::error!("WebView2 will fall back to the system default - portability may be broken");
|
"could not create webview data dir at {}: {e}",
|
||||||
|
webview_dir.display()
|
||||||
|
);
|
||||||
|
tracing::error!(
|
||||||
|
"WebView2 will fall back to the system default - portability may be broken"
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -4,8 +4,7 @@ use anyhow::{bail, Context, Result};
|
|||||||
use futures_util::StreamExt;
|
use futures_util::StreamExt;
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
const GITEA_LATEST: &str =
|
const GITEA_LATEST: &str = "https://git.lashman.live/api/v1/repos/lashman/bytesize/releases/latest";
|
||||||
"https://git.lashman.live/api/v1/repos/lashman/bytesize/releases/latest";
|
|
||||||
|
|
||||||
/// Everything the updater will fetch has to live under this prefix. The download
|
/// Everything the updater will fetch has to live under this prefix. The download
|
||||||
/// URL arrives from the frontend, and an unconstrained one there would let
|
/// URL arrives from the frontend, and an unconstrained one there would let
|
||||||
@@ -61,7 +60,12 @@ pub(crate) async fn check_for_update() -> Result<Option<UpdateInfo>> {
|
|||||||
.assets
|
.assets
|
||||||
.iter()
|
.iter()
|
||||||
.find(|a| a.name.eq_ignore_ascii_case("ByteSize.exe"))
|
.find(|a| a.name.eq_ignore_ascii_case("ByteSize.exe"))
|
||||||
.or_else(|| release.assets.iter().find(|a| a.name.to_lowercase().ends_with(".exe")))
|
.or_else(|| {
|
||||||
|
release
|
||||||
|
.assets
|
||||||
|
.iter()
|
||||||
|
.find(|a| a.name.to_lowercase().ends_with(".exe"))
|
||||||
|
})
|
||||||
.map(|a| a.browser_download_url.clone());
|
.map(|a| a.browser_download_url.clone());
|
||||||
Ok(Some(UpdateInfo {
|
Ok(Some(UpdateInfo {
|
||||||
version: latest,
|
version: latest,
|
||||||
|
|||||||
@@ -7,8 +7,8 @@ use serde::Serialize;
|
|||||||
use tauri::{AppHandle, Emitter};
|
use tauri::{AppHandle, Emitter};
|
||||||
use windows::core::BOOL;
|
use windows::core::BOOL;
|
||||||
use windows::Win32::Foundation::{HWND, LPARAM, POINT, RECT};
|
use windows::Win32::Foundation::{HWND, LPARAM, POINT, RECT};
|
||||||
use windows::Win32::UI::Input::KeyboardAndMouse::GetAsyncKeyState;
|
|
||||||
use windows::Win32::Graphics::Dwm::{DwmGetWindowAttribute, DWMWA_EXTENDED_FRAME_BOUNDS};
|
use windows::Win32::Graphics::Dwm::{DwmGetWindowAttribute, DWMWA_EXTENDED_FRAME_BOUNDS};
|
||||||
|
use windows::Win32::UI::Input::KeyboardAndMouse::GetAsyncKeyState;
|
||||||
use windows::Win32::UI::WindowsAndMessaging::{
|
use windows::Win32::UI::WindowsAndMessaging::{
|
||||||
EnumWindows, GetClassNameW, GetCursorPos, GetWindowLongW, GetWindowRect, IsIconic,
|
EnumWindows, GetClassNameW, GetCursorPos, GetWindowLongW, GetWindowRect, IsIconic,
|
||||||
IsWindowVisible, GWL_EXSTYLE, WS_EX_TOOLWINDOW,
|
IsWindowVisible, GWL_EXSTYLE, WS_EX_TOOLWINDOW,
|
||||||
|
|||||||
Reference in New Issue
Block a user