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,
|
||||
reason = "a build script without OUT_DIR cannot produce a usable build"
|
||||
)]
|
||||
let out_dir = PathBuf::from(
|
||||
std::env::var("OUT_DIR").expect("OUT_DIR is set by cargo for build scripts"),
|
||||
);
|
||||
let out_dir =
|
||||
PathBuf::from(std::env::var("OUT_DIR").expect("OUT_DIR is set by cargo for build scripts"));
|
||||
let shader_dir = PathBuf::from("shaders");
|
||||
|
||||
let fxc = find_fxc();
|
||||
@@ -88,7 +87,11 @@ fn find_fxc() -> Option<PathBuf> {
|
||||
continue;
|
||||
}
|
||||
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));
|
||||
}
|
||||
}
|
||||
|
||||
+12
-4
@@ -7,8 +7,8 @@ use std::thread::{self, JoinHandle};
|
||||
|
||||
use anyhow::{bail, Context, Result};
|
||||
use windows::Win32::Media::Audio::{
|
||||
eConsole, eRender, IAudioCaptureClient, IAudioClient, IMMDeviceEnumerator,
|
||||
MMDeviceEnumerator, WAVEFORMATEX, WAVEFORMATEXTENSIBLE,
|
||||
eConsole, eRender, IAudioCaptureClient, IAudioClient, IMMDeviceEnumerator, MMDeviceEnumerator,
|
||||
WAVEFORMATEX, WAVEFORMATEXTENSIBLE,
|
||||
};
|
||||
use windows::Win32::System::Com::{
|
||||
CoCreateInstance, CoInitializeEx, CoTaskMemFree, CLSCTX_ALL, COINIT_APARTMENTTHREADED,
|
||||
@@ -125,7 +125,8 @@ fn parse_format(fmt: &WAVEFORMATEX) -> Result<(u32, u16, u16, bool)> {
|
||||
false
|
||||
} else if w_format_tag == WAVE_FORMAT_EXTENSIBLE {
|
||||
// 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.
|
||||
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)
|
||||
@@ -226,7 +227,14 @@ fn capture_thread(
|
||||
// Notify parent that init succeeded.
|
||||
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.
|
||||
unsafe {
|
||||
|
||||
+13
-12
@@ -147,10 +147,8 @@ where
|
||||
.context("invalid dest path for temp archive")?;
|
||||
let scratch_dir = app_dir.join("temp");
|
||||
fs::create_dir_all(&scratch_dir).context("creating temp dir for archive")?;
|
||||
let archive_path = scratch_dir.join(format!(
|
||||
"ffmpeg-archive-{}.tmp",
|
||||
source.name.to_lowercase()
|
||||
));
|
||||
let archive_path =
|
||||
scratch_dir.join(format!("ffmpeg-archive-{}.tmp", source.name.to_lowercase()));
|
||||
|
||||
if let Some(ref hash) = expected {
|
||||
download_verified(
|
||||
@@ -163,7 +161,12 @@ where
|
||||
.await
|
||||
.with_context(|| format!("downloading {}", asset.browser_download_url))?;
|
||||
} else {
|
||||
download_plain(&client, &asset.browser_download_url, &archive_path, on_progress)
|
||||
download_plain(
|
||||
&client,
|
||||
&asset.browser_download_url,
|
||||
&archive_path,
|
||||
on_progress,
|
||||
)
|
||||
.await
|
||||
.with_context(|| format!("downloading {}", asset.browser_download_url))?;
|
||||
}
|
||||
@@ -244,12 +247,8 @@ async fn pick_asset(client: &reqwest::Client, source: &Source) -> Result<(Github
|
||||
.await?
|
||||
.error_for_status()?;
|
||||
let body = resp.text().await?;
|
||||
let release: GithubRelease =
|
||||
serde_json::from_str(&body).context("parsing release metadata")?;
|
||||
let version = release
|
||||
.tag_name
|
||||
.trim_start_matches('v')
|
||||
.to_string();
|
||||
let release: GithubRelease = serde_json::from_str(&body).context("parsing release metadata")?;
|
||||
let version = release.tag_name.trim_start_matches('v').to_string();
|
||||
let asset = release
|
||||
.assets
|
||||
.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");
|
||||
};
|
||||
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,
|
||||
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_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_SHADER_RESOURCE_VIEW_DESC, D3D11_SUBRESOURCE_DATA, D3D11_TEXTURE2D_DESC,
|
||||
D3D11_TEXTURE_ADDRESS_CLAMP, D3D11_TEX2D_RTV, D3D11_TEX2D_SRV, D3D11_USAGE_DEFAULT,
|
||||
D3D11_USAGE_IMMUTABLE, D3D11_USAGE_STAGING, D3D11_VIEWPORT,
|
||||
D3D11_SHADER_RESOURCE_VIEW_DESC, D3D11_SUBRESOURCE_DATA, D3D11_TEX2D_RTV, D3D11_TEX2D_SRV,
|
||||
D3D11_TEXTURE2D_DESC, D3D11_TEXTURE_ADDRESS_CLAMP, D3D11_USAGE_DEFAULT, D3D11_USAGE_IMMUTABLE,
|
||||
D3D11_USAGE_STAGING, D3D11_VIEWPORT,
|
||||
};
|
||||
use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT_B8G8R8A8_UNORM, DXGI_SAMPLE_DESC};
|
||||
use windows_capture::capture::{
|
||||
@@ -150,7 +150,10 @@ fn new_render_target_desc(width: u32, height: u32) -> D3D11_TEXTURE2D_DESC {
|
||||
MipLevels: 1,
|
||||
ArraySize: 1,
|
||||
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,
|
||||
BindFlags: (D3D11_BIND_RENDER_TARGET.0 | D3D11_BIND_SHADER_RESOURCE.0) as u32,
|
||||
CPUAccessFlags: 0,
|
||||
@@ -176,7 +179,10 @@ fn new_staging_desc(width: u32, height: u32) -> D3D11_TEXTURE2D_DESC {
|
||||
MipLevels: 1,
|
||||
ArraySize: 1,
|
||||
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,
|
||||
BindFlags: 0,
|
||||
CPUAccessFlags: D3D11_CPU_ACCESS_READ.0 as u32,
|
||||
@@ -211,30 +217,11 @@ fn new_vertex_buffer() -> (D3D11_BUFFER_DESC, D3D11_SUBRESOURCE_DATA) {
|
||||
)
|
||||
}
|
||||
|
||||
impl TonemapPipeline {
|
||||
fn new(device: &ID3D11Device, width: u32, height: u32) -> Result<Self> {
|
||||
// build.rs emits empty .cso files when fxc was missing at build time.
|
||||
// Without this the only symptom is an opaque CreateVertexShader failure
|
||||
// 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 = [
|
||||
/// Vertex-input description matching the vertex shader's signature: position at
|
||||
/// offset 0, texture coordinates at 8. `CreateInputLayout` validates it against
|
||||
/// the compiled bytecode, so a mismatch fails loudly rather than reading garbage.
|
||||
fn new_input_elements() -> [D3D11_INPUT_ELEMENT_DESC; 2] {
|
||||
[
|
||||
D3D11_INPUT_ELEMENT_DESC {
|
||||
SemanticName: windows::core::PCSTR(c"POSITION".as_ptr().cast()),
|
||||
SemanticIndex: 0,
|
||||
@@ -253,7 +240,38 @@ impl TonemapPipeline {
|
||||
InputSlotClass: D3D11_INPUT_PER_VERTEX_DATA,
|
||||
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;
|
||||
unsafe {
|
||||
// SAFETY: the element descriptions and the vertex-shader bytecode
|
||||
@@ -265,16 +283,22 @@ impl TonemapPipeline {
|
||||
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 mut vertex_buffer = None;
|
||||
unsafe {
|
||||
// SAFETY: both descriptions are stack locals that outlive the call,
|
||||
// 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.
|
||||
let mut ps = None;
|
||||
@@ -310,14 +334,19 @@ impl TonemapPipeline {
|
||||
// out-param is a local Option.
|
||||
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 mut rtv = None;
|
||||
unsafe {
|
||||
// SAFETY: render_target was just created on this device and
|
||||
// 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"))?;
|
||||
|
||||
@@ -369,7 +398,10 @@ impl TonemapPipeline {
|
||||
// Resize - rebuild the RT/staging at the new dimensions.
|
||||
tracing::info!(
|
||||
"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)?;
|
||||
}
|
||||
@@ -545,7 +577,9 @@ impl GraphicsCaptureApiHandler for CaptureHandler {
|
||||
|
||||
tracing::info!(
|
||||
"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);
|
||||
@@ -622,12 +656,12 @@ impl GraphicsCaptureApiHandler for CaptureHandler {
|
||||
.ok_or_else(|| anyhow!("tonemap pipeline missing after initialization"))?;
|
||||
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(())
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
impl Drop for CaptureHandler {
|
||||
fn drop(&mut self) {
|
||||
drop(self.stdin.take());
|
||||
@@ -777,8 +811,8 @@ pub(crate) fn start(
|
||||
setup,
|
||||
);
|
||||
|
||||
let control = CaptureHandler::start_free_threaded(settings)
|
||||
.map_err(|e| anyhow!("capture start: {e}"))?;
|
||||
let control =
|
||||
CaptureHandler::start_free_threaded(settings).map_err(|e| anyhow!("capture start: {e}"))?;
|
||||
|
||||
Ok(CaptureSession {
|
||||
output_path,
|
||||
|
||||
@@ -97,9 +97,6 @@ impl ClickRecorder {
|
||||
if let Some(t) = self.thread.take() {
|
||||
drop(t.join());
|
||||
}
|
||||
self.clicks
|
||||
.lock()
|
||||
.map(|v| v.clone())
|
||||
.unwrap_or_default()
|
||||
self.clicks.lock().map(|v| v.clone()).unwrap_or_default()
|
||||
}
|
||||
}
|
||||
|
||||
+17
-8
@@ -157,7 +157,9 @@ impl Default for CaptureConfig {
|
||||
|
||||
impl Default for UpdatesConfig {
|
||||
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 {
|
||||
self.hotkeys.start.is_none()
|
||||
|| self.hotkeys.stop.is_none()
|
||||
|| self.hotkeys.pause.is_none()
|
||||
self.hotkeys.start.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).
|
||||
fn sweep_stale_backups(config_path: &Path) {
|
||||
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()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.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() {
|
||||
let name = entry.file_name();
|
||||
let Some(name) = name.to_str() else { continue };
|
||||
// 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 now.saturating_sub(ts) > MAX_AGE_SECS {
|
||||
drop(std::fs::remove_file(entry.path()));
|
||||
@@ -273,7 +280,9 @@ mod tests {
|
||||
stop: Some("F10".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")),
|
||||
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)
|
||||
}
|
||||
|
||||
fn click_filters(
|
||||
clicks: &[Click],
|
||||
clip_w: u32,
|
||||
clip_h: u32,
|
||||
time_offset: f64,
|
||||
) -> Option<String> {
|
||||
fn click_filters(clicks: &[Click], clip_w: u32, clip_h: u32, time_offset: f64) -> Option<String> {
|
||||
if clicks.is_empty() {
|
||||
return None;
|
||||
}
|
||||
@@ -326,10 +321,7 @@ fn probe_encoders(ffmpeg: &Path) -> Result<HashSet<String>> {
|
||||
Ok(set)
|
||||
}
|
||||
|
||||
fn pick_audio_codec<'a>(
|
||||
encoders: &HashSet<String>,
|
||||
candidates: &[&'a str],
|
||||
) -> Result<&'a str> {
|
||||
fn pick_audio_codec<'a>(encoders: &HashSet<String>, candidates: &[&'a str]) -> Result<&'a str> {
|
||||
for c in candidates {
|
||||
if encoders.contains(*c) {
|
||||
return Ok(c);
|
||||
@@ -379,7 +371,12 @@ impl CodecAvailability {
|
||||
/// Returns all-true when ffmpeg is not installed yet (the bootstrap screen
|
||||
/// is still up). Settings will re-query after the user installs ffmpeg.
|
||||
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))
|
||||
}
|
||||
|
||||
/// 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(
|
||||
ffmpeg: &Path,
|
||||
req: &TranscodeRequest,
|
||||
@@ -427,13 +435,13 @@ fn two_pass_video(
|
||||
let null_target = if cfg!(windows) { "NUL" } else { "/dev/null" };
|
||||
|
||||
let crop = crop_filter(req.crop);
|
||||
let clicks = click_filters(&req.clicks, req.clip_width, req.clip_height, trim_offset(req));
|
||||
let combined_vf: 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,
|
||||
};
|
||||
let clicks = click_filters(
|
||||
&req.clicks,
|
||||
req.clip_width,
|
||||
req.clip_height,
|
||||
trim_offset(req),
|
||||
);
|
||||
let combined_vf = combined_video_filter(crop.as_ref(), clicks.as_ref());
|
||||
|
||||
let mut pass1 = Command::new(ffmpeg);
|
||||
pass1
|
||||
@@ -478,7 +486,12 @@ fn two_pass_video(
|
||||
if let Some(ref t) = tx {
|
||||
// The receiver is gone only if the UI navigated away; the encode is
|
||||
// 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);
|
||||
@@ -588,7 +601,8 @@ fn calibrate_via_sample(
|
||||
let aspect = aspect_ratio(req.clip_width, req.clip_height);
|
||||
let sample_h = round_u32(f64::from(est_width) / aspect);
|
||||
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.
|
||||
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
|
||||
// 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_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))
|
||||
}
|
||||
|
||||
@@ -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<()> {
|
||||
let budget_input = GifBudgetInput {
|
||||
gif_colors: req.gif_colors,
|
||||
@@ -633,20 +685,16 @@ fn encode_gif(ffmpeg: &Path, req: &TranscodeRequest) -> Result<()> {
|
||||
duration_secs: req.duration_secs,
|
||||
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.
|
||||
// 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
|
||||
// point and typically cuts retry count from 4-8 down to 1-2.
|
||||
if req.duration_secs > 4.0 {
|
||||
if let Some((calibrated_w, calibrated_fps)) = calibrate_via_sample(ffmpeg, req, scale_width, effective_fps) {
|
||||
tracing::info!(
|
||||
"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;
|
||||
}
|
||||
if let Some((w, f)) = gif_calibration(ffmpeg, req, scale_width, effective_fps) {
|
||||
scale_width = w;
|
||||
effective_fps = f;
|
||||
}
|
||||
|
||||
let target = req.target_bytes;
|
||||
@@ -661,7 +709,11 @@ fn encode_gif(ffmpeg: &Path, req: &TranscodeRequest) -> Result<()> {
|
||||
let mut prev_actual: Option<u64> = None;
|
||||
|
||||
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");
|
||||
}
|
||||
// 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();
|
||||
encode_gif_pass(
|
||||
ffmpeg, req, scale_width, effective_fps,
|
||||
(u8::try_from(attempt).unwrap_or(0)) + 1, max_attempts,
|
||||
ffmpeg,
|
||||
req,
|
||||
scale_width,
|
||||
effective_fps,
|
||||
(u8::try_from(attempt).unwrap_or(0)) + 1,
|
||||
max_attempts,
|
||||
)?;
|
||||
tracing::info!(
|
||||
attempt = attempt + 1,
|
||||
@@ -680,8 +736,7 @@ fn encode_gif(ffmpeg: &Path, req: &TranscodeRequest) -> Result<()> {
|
||||
"gif pass finished"
|
||||
);
|
||||
|
||||
let actual = std::fs::metadata(&req.output)
|
||||
.map_or(0, |m| m.len());
|
||||
let actual = std::fs::metadata(&req.output).map_or(0, |m| m.len());
|
||||
|
||||
if actual == 0 {
|
||||
bail!("gif output is empty");
|
||||
@@ -693,7 +748,9 @@ fn encode_gif(ffmpeg: &Path, req: &TranscodeRequest) -> Result<()> {
|
||||
if ratio >= 1.0 {
|
||||
tracing::info!(
|
||||
"gif encode done on attempt {}: {} bytes (target {})",
|
||||
attempt + 1, actual, target
|
||||
attempt + 1,
|
||||
actual,
|
||||
target
|
||||
);
|
||||
return Ok(());
|
||||
}
|
||||
@@ -725,19 +782,12 @@ fn encode_gif(ffmpeg: &Path, req: &TranscodeRequest) -> Result<()> {
|
||||
}
|
||||
}
|
||||
|
||||
match req.gif_budget_mode {
|
||||
GifBudgetMode::Resolution => {
|
||||
// Halve before clamping so the *2 keeps the width even.
|
||||
scale_width = (round_u32(f64::from(scale_width) * factor) / 2).clamp(60, 640) * 2;
|
||||
}
|
||||
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);
|
||||
}
|
||||
}
|
||||
shrink_gif_params(
|
||||
req.gif_budget_mode,
|
||||
factor,
|
||||
&mut scale_width,
|
||||
&mut effective_fps,
|
||||
);
|
||||
|
||||
tracing::info!(
|
||||
"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)
|
||||
.map(|c| format!("{c},"))
|
||||
.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},"))
|
||||
.unwrap_or_default();
|
||||
let select_prefix = select_filter_for_deleted(&req.deleted_frame_indices)
|
||||
@@ -800,7 +855,10 @@ fn encode_gif_pass(
|
||||
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);
|
||||
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
|
||||
// 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
|
||||
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 target_bytes = bytes_f64(input.target_bytes);
|
||||
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(".")));
|
||||
let palette_filter = format!(
|
||||
"{},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);
|
||||
gen.arg("-y")
|
||||
@@ -994,10 +1055,12 @@ pub(crate) fn render_gif_preview(
|
||||
// Apply palette to the target frame
|
||||
let use_filter = format!(
|
||||
"{}[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);
|
||||
encode.arg("-y")
|
||||
encode
|
||||
.arg("-y")
|
||||
.arg("-hide_banner")
|
||||
.args(["-ss", &format!("{midpoint_secs}")])
|
||||
.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
|
||||
/// 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 {
|
||||
format!(
|
||||
"c{gif_colors}-w{target_width}-s{sample_start:.3}-d{sample_dur:.3}"
|
||||
)
|
||||
fn palette_cache_key(
|
||||
gif_colors: u16,
|
||||
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.
|
||||
@@ -1056,9 +1122,7 @@ pub(crate) fn extract_thumbnails(
|
||||
let crop_prefix = crop_filter(crop)
|
||||
.map(|c| format!("{c},"))
|
||||
.unwrap_or_default();
|
||||
let filter = format!(
|
||||
"{crop_prefix}fps={fps},scale=120:-1:flags=lanczos"
|
||||
);
|
||||
let filter = format!("{crop_prefix}fps={fps},scale=120:-1:flags=lanczos");
|
||||
let pattern = out_dir.join("thumb-%05d.png");
|
||||
|
||||
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")?;
|
||||
for seg in segments {
|
||||
let mut f = std::fs::File::open(seg)
|
||||
.with_context(|| format!("opening {}", seg.display()))?;
|
||||
let mut f =
|
||||
std::fs::File::open(seg).with_context(|| format!("opening {}", seg.display()))?;
|
||||
std::io::copy(&mut f, &mut out).context("copying audio segment")?;
|
||||
}
|
||||
out.flush()?;
|
||||
@@ -1133,7 +1197,9 @@ pub(crate) fn concat_pcm(segments: &[PathBuf], output: &Path) -> Result<()> {
|
||||
|
||||
struct TempFileGuard(PathBuf);
|
||||
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<()> {
|
||||
@@ -1208,8 +1274,15 @@ fn run_with_progress(
|
||||
// "key=value" lines terminated by "progress=continue" / "progress=end".
|
||||
cmd.arg("-progress").arg("pipe:1");
|
||||
let output = run_impl(
|
||||
cmd, label, pass, total_passes, duration_secs, fps,
|
||||
progress_tx.cloned(), cancel.cloned(), true,
|
||||
cmd,
|
||||
label,
|
||||
pass,
|
||||
total_passes,
|
||||
duration_secs,
|
||||
fps,
|
||||
progress_tx.cloned(),
|
||||
cancel.cloned(),
|
||||
true,
|
||||
)?;
|
||||
if !output.status.success() {
|
||||
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 head: String = text.lines().take(12).collect::<Vec<_>>().join("\n");
|
||||
let lower = text.to_ascii_lowercase();
|
||||
let hint = if lower.contains("unknown encoder")
|
||||
|| lower.contains("error while opening encoder")
|
||||
let hint = if lower.contains("unknown encoder") || lower.contains("error while opening encoder")
|
||||
{
|
||||
Some("selected codec is not available in this ffmpeg build")
|
||||
} 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
|
||||
// reader threads this spawns, so borrowing them here would not typecheck.
|
||||
// The argument count matches run_with_progress, its only caller.
|
||||
@@ -1266,18 +1351,15 @@ fn run_impl(
|
||||
) -> Result<std::process::Output> {
|
||||
use std::process::Stdio;
|
||||
|
||||
let mut printable = OsString::from(label);
|
||||
printable.push(": ");
|
||||
printable.push(cmd.get_program());
|
||||
for arg in cmd.get_args() {
|
||||
printable.push(" ");
|
||||
printable.push(arg);
|
||||
}
|
||||
tracing::debug!("{}", printable.to_string_lossy());
|
||||
tracing::debug!("{}", describe_command(label, cmd));
|
||||
|
||||
// When we asked ffmpeg for `-progress pipe:1`, stdout carries the stable
|
||||
// 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
|
||||
.stdout(stdout_cfg)
|
||||
.stderr(Stdio::piped())
|
||||
@@ -1285,7 +1367,11 @@ fn run_impl(
|
||||
.with_context(|| format!("spawning ffmpeg for {label}"))?;
|
||||
|
||||
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();
|
||||
|
||||
// Progress reader: parse the key=value stream from stdout. Each update
|
||||
@@ -1343,15 +1429,22 @@ fn run_impl(
|
||||
if c.load(Ordering::Relaxed) {
|
||||
drop(child.kill());
|
||||
drop(child.wait());
|
||||
if let Some(h) = stdout_handle.take() { drop(h.join()); }
|
||||
if let Some(h) = stderr_handle.take() { drop(h.join()); }
|
||||
if let Some(h) = stdout_handle.take() {
|
||||
drop(h.join());
|
||||
}
|
||||
if let Some(h) = stderr_handle.take() {
|
||||
drop(h.join());
|
||||
}
|
||||
bail!("export cancelled");
|
||||
}
|
||||
}
|
||||
match child.try_wait() {
|
||||
Ok(Some(status)) => {
|
||||
if let Some(h) = stdout_handle.take() { drop(h.join()); }
|
||||
let stderr_bytes = stderr_handle.take()
|
||||
if let Some(h) = stdout_handle.take() {
|
||||
drop(h.join());
|
||||
}
|
||||
let stderr_bytes = stderr_handle
|
||||
.take()
|
||||
.and_then(|h| h.join().ok())
|
||||
.unwrap_or_default();
|
||||
return Ok(std::process::Output {
|
||||
@@ -1457,13 +1550,19 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
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]
|
||||
fn parse_progress_kv_progress_continue_returns_zero() {
|
||||
// "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)));
|
||||
}
|
||||
|
||||
@@ -1492,7 +1591,12 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
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!(
|
||||
crop_filter(Some(rect)),
|
||||
Some("crop=100:200:10:20".to_string())
|
||||
@@ -1503,7 +1607,12 @@ mod tests {
|
||||
#[test]
|
||||
fn click_filters_capped_at_max() {
|
||||
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();
|
||||
let filter = click_filters(&clicks, 1920, 1080, 0.0).unwrap();
|
||||
let count = filter.matches("drawbox").count();
|
||||
@@ -1515,7 +1624,10 @@ mod tests {
|
||||
let frame = (1920u32, 1080u32);
|
||||
// Near each edge, and one dead-centre.
|
||||
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)));
|
||||
}
|
||||
|
||||
@@ -1534,8 +1646,18 @@ mod tests {
|
||||
#[test]
|
||||
fn click_filters_drops_clicks_off_frame() {
|
||||
let clicks = vec![
|
||||
Click { 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 },
|
||||
Click {
|
||||
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();
|
||||
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.
|
||||
#[test]
|
||||
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();
|
||||
assert!(untrimmed.contains("between(t,5.950,6.250)"));
|
||||
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.
|
||||
#[test]
|
||||
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());
|
||||
}
|
||||
|
||||
@@ -1584,7 +1716,10 @@ mod tests {
|
||||
let f = gif_shrink_factor(GifBudgetMode::Balanced, 0.25);
|
||||
let lo = 0.25_f64;
|
||||
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]
|
||||
|
||||
+228
-134
@@ -30,9 +30,9 @@ use std::sync::{Arc, Mutex};
|
||||
|
||||
use anyhow::{anyhow, Context as _, Result};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::str::FromStr;
|
||||
use tauri::{AppHandle, Emitter, Manager, State};
|
||||
use tauri_plugin_global_shortcut::{GlobalShortcutExt, Shortcut, ShortcutState};
|
||||
use std::str::FromStr;
|
||||
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt, EnvFilter};
|
||||
|
||||
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_handle = app.clone();
|
||||
bootstrap::download(&app_dir, move |downloaded, total| {
|
||||
drop(app_handle.emit(
|
||||
"ffmpeg-progress",
|
||||
DownloadProgress { downloaded, total },
|
||||
));
|
||||
drop(app_handle.emit("ffmpeg-progress", DownloadProgress { downloaded, total }));
|
||||
})
|
||||
.await
|
||||
.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`.
|
||||
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;
|
||||
let bytes_per_sec = f64::from(sample_rate) * f64::from(channels) * 4.0;
|
||||
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!(
|
||||
"padded audio head with {:.1}ms ({} bytes) of silence",
|
||||
head_secs * 1000.0, pad_bytes
|
||||
head_secs * 1000.0,
|
||||
pad_bytes
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
@@ -566,7 +569,10 @@ fn start_capture(
|
||||
clear_temp_segments(&state.app_dir, true);
|
||||
|
||||
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 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());
|
||||
}
|
||||
|
||||
let (monitor_w, monitor_h) =
|
||||
capture::primary_monitor_dims().map_err(|e| format!("{e:#}"))?;
|
||||
let (monitor_w, monitor_h) = capture::primary_monitor_dims().map_err(|e| format!("{e:#}"))?;
|
||||
|
||||
let session = capture::start(
|
||||
output,
|
||||
@@ -639,7 +644,11 @@ fn pause_capture(state: State<'_, AppState>) -> Result<(), String> {
|
||||
let fixed_path = raw_path.with_extension("fixed.mp4");
|
||||
capture::fix_intermediate_fps(&ffmpeg, &raw_path, &fixed_path, elapsed, frames, pipe_fps)
|
||||
.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);
|
||||
|
||||
@@ -649,9 +658,7 @@ fn pause_capture(state: State<'_, AppState>) -> Result<(), String> {
|
||||
.unwrap_or_default();
|
||||
|
||||
let mut ss = lock(&state.session);
|
||||
let ss = ss
|
||||
.as_mut()
|
||||
.ok_or_else(|| "no session state".to_string())?;
|
||||
let ss = ss.as_mut().ok_or_else(|| "no session state".to_string())?;
|
||||
let offset = *ss.segment_start_offsets.last().unwrap_or(&0.0);
|
||||
for c in new_clicks {
|
||||
ss.clicks.push(clicks::Click {
|
||||
@@ -681,12 +688,7 @@ fn resume_capture(app: AppHandle, state: State<'_, AppState>) -> Result<(), Stri
|
||||
let ss = ss
|
||||
.as_ref()
|
||||
.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) = {
|
||||
@@ -719,13 +721,12 @@ fn resume_capture(app: AppHandle, state: State<'_, AppState>) -> Result<(), Stri
|
||||
/// without ending the recording. Stops the current session, appends its
|
||||
/// pcm segment to the session, and starts a new one with a fresh file.
|
||||
#[tauri::command]
|
||||
fn restart_audio_capture(
|
||||
app: AppHandle,
|
||||
state: State<'_, AppState>,
|
||||
) -> Result<(), String> {
|
||||
fn restart_audio_capture(app: AppHandle, state: State<'_, AppState>) -> Result<(), String> {
|
||||
let audio_enabled = {
|
||||
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 {
|
||||
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.
|
||||
let next_idx = {
|
||||
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() {
|
||||
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");
|
||||
capture::fix_intermediate_fps(&ffmpeg, &raw_path, &fixed_path, elapsed, frames, pipe_fps)
|
||||
.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.total_recorded_secs += elapsed;
|
||||
}
|
||||
@@ -845,22 +852,12 @@ fn stop_capture(state: State<'_, AppState>) -> Result<RecordedClip, String> {
|
||||
if audio_start > video_start {
|
||||
let head_offset_secs = audio_start.duration_since(video_start).as_secs_f64();
|
||||
if head_offset_secs > 0.001 {
|
||||
pad_audio_head(
|
||||
&audio_concat,
|
||||
sample_rate,
|
||||
channels,
|
||||
head_offset_secs,
|
||||
)
|
||||
pad_audio_head(&audio_concat, sample_rate, channels, head_offset_secs)
|
||||
.map_err(|e| format!("padding audio head: {e:#}"))?;
|
||||
}
|
||||
}
|
||||
}
|
||||
adjust_audio_length(
|
||||
&audio_concat,
|
||||
sample_rate,
|
||||
channels,
|
||||
ss.total_recorded_secs,
|
||||
)
|
||||
adjust_audio_length(&audio_concat, sample_rate, channels, ss.total_recorded_secs)
|
||||
.map_err(|e| format!("adjusting audio length: {e:#}"))?;
|
||||
encode::mux_with_audio(
|
||||
&ffmpeg,
|
||||
@@ -929,11 +926,7 @@ pub struct ExportRequest {
|
||||
#[tauri::command]
|
||||
fn default_output_path(state: State<'_, AppState>, format: Format) -> String {
|
||||
let dir = output_dir(&state.app_dir, &lock(&state.config));
|
||||
dir.join(format!(
|
||||
"bytesize-{}.{}",
|
||||
timestamp_slug(),
|
||||
ext_for(format)
|
||||
))
|
||||
dir.join(format!("bytesize-{}.{}", timestamp_slug(), ext_for(format)))
|
||||
.to_string_lossy()
|
||||
.into_owned()
|
||||
}
|
||||
@@ -960,10 +953,7 @@ pub struct PreviewRequest {
|
||||
}
|
||||
|
||||
#[tauri::command(async)]
|
||||
fn render_preview(
|
||||
state: State<'_, AppState>,
|
||||
request: PreviewRequest,
|
||||
) -> Result<PathBuf, String> {
|
||||
fn render_preview(state: State<'_, AppState>, request: PreviewRequest) -> Result<PathBuf, String> {
|
||||
let clip = lock(&state.last_clip)
|
||||
.clone()
|
||||
.ok_or_else(|| "no recorded clip available".to_string())?;
|
||||
@@ -995,11 +985,24 @@ fn render_preview(
|
||||
GifDither::None => "none",
|
||||
};
|
||||
encode::render_gif_preview(
|
||||
&ffmpeg, &clip.temp_path, &preview_path, midpoint, target_width,
|
||||
request.gif_colors.unwrap_or(256), dither_str, clip.duration_secs,
|
||||
).map_err(|e| format!("{e:#}"))?;
|
||||
&ffmpeg,
|
||||
&clip.temp_path,
|
||||
&preview_path,
|
||||
midpoint,
|
||||
target_width,
|
||||
request.gif_colors.unwrap_or(256),
|
||||
dither_str,
|
||||
clip.duration_secs,
|
||||
)
|
||||
.map_err(|e| format!("{e:#}"))?;
|
||||
} 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:#}"))?;
|
||||
}
|
||||
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 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
|
||||
/// across a range of targets so the frontend can interpolate locally.
|
||||
const GIF_ESTIMATE_GRID: &[u64] = &[
|
||||
100_000, 200_000, 500_000,
|
||||
1_048_576, 2_097_152, 5_242_880,
|
||||
10_485_760, 20_971_520, 52_428_800,
|
||||
104_857_600, 209_715_200,
|
||||
100_000,
|
||||
200_000,
|
||||
500_000,
|
||||
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
|
||||
@@ -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 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 }
|
||||
}
|
||||
@@ -1150,12 +1170,21 @@ mod tests {
|
||||
|
||||
// Mid-session: drop the recording artifacts, keep the live previews.
|
||||
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("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("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());
|
||||
|
||||
// Exit/startup: everything goes.
|
||||
@@ -1167,7 +1196,8 @@ mod tests {
|
||||
}
|
||||
|
||||
#[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.
|
||||
let req = make_request(8 * 1024 * 1024, 30, GifBudgetMode::Balanced);
|
||||
let est = estimate_gif_params(req);
|
||||
@@ -1187,7 +1217,10 @@ mod tests {
|
||||
let expected_height = encode::gif_height_for_width(encode_w, 1920, 1080);
|
||||
assert_eq!(est.height, expected_height);
|
||||
// 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]
|
||||
@@ -1201,10 +1234,7 @@ mod tests {
|
||||
}
|
||||
|
||||
#[tauri::command(async)]
|
||||
fn extract_thumbnails(
|
||||
state: State<'_, AppState>,
|
||||
fps: u32,
|
||||
) -> Result<Vec<PathBuf>, String> {
|
||||
fn extract_thumbnails(state: State<'_, AppState>, fps: u32) -> Result<Vec<PathBuf>, String> {
|
||||
let clip = lock(&state.last_clip)
|
||||
.clone()
|
||||
.ok_or_else(|| "no recorded clip available".to_string())?;
|
||||
@@ -1218,10 +1248,7 @@ fn extract_thumbnails(
|
||||
}
|
||||
|
||||
#[tauri::command(async)]
|
||||
fn render_raw_preview(
|
||||
state: State<'_, AppState>,
|
||||
timestamp: f64,
|
||||
) -> Result<PathBuf, String> {
|
||||
fn render_raw_preview(state: State<'_, AppState>, timestamp: f64) -> Result<PathBuf, String> {
|
||||
let clip = lock(&state.last_clip)
|
||||
.clone()
|
||||
.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());
|
||||
}
|
||||
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:#}"))?;
|
||||
Ok(out_path)
|
||||
}
|
||||
@@ -1246,7 +1279,6 @@ pub struct ExportResult {
|
||||
const OVERLAY_BORDER_LOGICAL_PX: f64 = 4.0;
|
||||
const OVERLAY_TITLEBAR_LOGICAL_PX: f64 = 24.0;
|
||||
|
||||
|
||||
/// Remove temporary recording artifacts (segments, previews, thumbs).
|
||||
/// Called on app exit so a discarded clip doesn't linger in `temp/`.
|
||||
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_bottom = vb - border;
|
||||
|
||||
Some(
|
||||
pt.x >= inner_left
|
||||
&& pt.x < inner_right
|
||||
&& pt.y >= inner_top
|
||||
&& pt.y < inner_bottom,
|
||||
)
|
||||
Some(pt.x >= inner_left && pt.x < inner_right && pt.y >= inner_top && pt.y < inner_bottom)
|
||||
}
|
||||
|
||||
fn start_overlay_clickthrough_poll(
|
||||
@@ -1323,7 +1350,9 @@ fn start_overlay_clickthrough_poll(
|
||||
// flips the flag and notifies.
|
||||
{
|
||||
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) {
|
||||
let (g, _timeout) = cvar
|
||||
.wait_timeout(active, Duration::from_secs(1))
|
||||
@@ -1334,8 +1363,7 @@ fn start_overlay_clickthrough_poll(
|
||||
|
||||
let target = overlay_should_ignore_cursor(&app);
|
||||
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));
|
||||
}
|
||||
last = target;
|
||||
@@ -1369,9 +1397,12 @@ fn mark_overlay_excluded_from_capture(win: &tauri::WebviewWindow) -> Result<(),
|
||||
fn show_overlay(app: AppHandle) -> Result<(), String> {
|
||||
use windows::Win32::Foundation::{HWND, POINT};
|
||||
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
|
||||
.get_webview_window("overlay")
|
||||
@@ -1383,14 +1414,19 @@ fn show_overlay(app: AppHandle) -> Result<(), String> {
|
||||
{
|
||||
let st = app.state::<AppState>();
|
||||
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();
|
||||
}
|
||||
|
||||
// If the overlay is off-screen (monitor disconnected), center on primary
|
||||
if let Ok(raw) = win.hwnd() {
|
||||
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
|
||||
// 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>());
|
||||
// SAFETY: same value-only call; MONITOR_DEFAULTTOPRIMARY cannot
|
||||
// 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
|
||||
// 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
|
||||
// result is checked with as_bool() before mi is read.
|
||||
if unsafe { GetMonitorInfoW(primary, &raw mut mi) }.as_bool() {
|
||||
@@ -1415,7 +1455,17 @@ fn show_overlay(app: AppHandle) -> Result<(), String> {
|
||||
drop(
|
||||
// SAFETY: `hwnd` is the overlay's live handle; the flags
|
||||
// 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 (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();
|
||||
}
|
||||
win.hide().map_err(|e| format!("hiding overlay: {e:#}"))
|
||||
}
|
||||
|
||||
#[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};
|
||||
let win = app
|
||||
.get_webview_window("overlay")
|
||||
@@ -1460,7 +1517,11 @@ fn set_overlay_size(app: AppHandle, state: State<'_, AppState>, width: u32, heig
|
||||
}
|
||||
|
||||
#[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;
|
||||
if let Some(r) = ratio {
|
||||
// Enforce on current size
|
||||
@@ -1468,14 +1529,17 @@ fn set_overlay_aspect(app: AppHandle, state: State<'_, AppState>, ratio: Option<
|
||||
.get_webview_window("overlay")
|
||||
.ok_or_else(|| "overlay window not found".to_string())?;
|
||||
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_h = f64::from(sz.height) / scale;
|
||||
let target_h = cur_w / r;
|
||||
if (target_h - cur_h).abs() > 1.0 {
|
||||
use tauri::{LogicalSize, Size};
|
||||
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)))
|
||||
.map_err(|e| format!("setting overlay size: {e:#}"))?;
|
||||
}
|
||||
@@ -1491,7 +1555,9 @@ fn get_overlay_aspect(state: State<'_, AppState>) -> Option<f64> {
|
||||
#[tauri::command]
|
||||
fn enforce_overlay_aspect(app: AppHandle, state: State<'_, AppState>) -> Result<(), String> {
|
||||
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 {
|
||||
return Ok(());
|
||||
@@ -1500,7 +1566,9 @@ fn enforce_overlay_aspect(app: AppHandle, state: State<'_, AppState>) -> Result<
|
||||
.get_webview_window("overlay")
|
||||
.ok_or_else(|| "overlay window not found".to_string())?;
|
||||
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_h = f64::from(sz.height) / scale;
|
||||
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 titlebar = encode::round_i32(OVERLAY_TITLEBAR_LOGICAL_PX * scale);
|
||||
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
|
||||
// non-activating and non-reordering, and no pointers are involved.
|
||||
unsafe {
|
||||
SetWindowPos(hwnd, Some(HWND_TOP), 0, 0, outer_w, outer_h,
|
||||
SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOMOVE)
|
||||
}.map_err(|e| format!("SetWindowPos: {e}"))?;
|
||||
SetWindowPos(
|
||||
hwnd,
|
||||
Some(HWND_TOP),
|
||||
0,
|
||||
0,
|
||||
outer_w,
|
||||
outer_h,
|
||||
SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOMOVE,
|
||||
)
|
||||
}
|
||||
.map_err(|e| format!("SetWindowPos: {e}"))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -1530,14 +1607,10 @@ fn list_windows() -> Vec<windows_list::WindowInfo> {
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
fn open_window_picker(
|
||||
app: AppHandle,
|
||||
state: State<'_, AppState>,
|
||||
) -> Result<(), String> {
|
||||
fn open_window_picker(app: AppHandle, state: State<'_, AppState>) -> Result<(), String> {
|
||||
use tauri::{PhysicalPosition, PhysicalSize, Position, Size};
|
||||
|
||||
let (mw, mh) =
|
||||
capture::primary_monitor_dims().map_err(|e| format!("{e:#}"))?;
|
||||
let (mw, mh) = capture::primary_monitor_dims().map_err(|e| format!("{e:#}"))?;
|
||||
|
||||
let mut exclude: Vec<isize> = Vec::new();
|
||||
for label in &["main", "overlay", "picker"] {
|
||||
@@ -1565,7 +1638,9 @@ fn open_window_picker(
|
||||
.map_err(|e| format!("setting picker position: {e:#}"))?;
|
||||
drop(picker.set_ignore_cursor_events(false));
|
||||
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() {
|
||||
use windows::Win32::Foundation::{HWND, RECT};
|
||||
use windows::Win32::Graphics::Dwm::{DwmGetWindowAttribute, DWMWA_EXTENDED_FRAME_BOUNDS};
|
||||
@@ -1587,8 +1662,14 @@ fn open_window_picker(
|
||||
});
|
||||
tracing::debug!(
|
||||
"picker window: GetWindowRect=({},{},{},{}) DwmBounds=({},{},{},{})",
|
||||
gr.left, gr.top, gr.right, gr.bottom,
|
||||
dr.left, dr.top, dr.right, dr.bottom
|
||||
gr.left,
|
||||
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,
|
||||
reason = "Result is part of the tauri::command contract the frontend invokes"
|
||||
)]
|
||||
fn close_window_picker(
|
||||
app: AppHandle,
|
||||
state: State<'_, AppState>,
|
||||
) -> Result<(), String> {
|
||||
fn close_window_picker(app: AppHandle, state: State<'_, AppState>) -> Result<(), String> {
|
||||
if let Some(session) = lock(&state.picker).take() {
|
||||
session.stop();
|
||||
}
|
||||
@@ -1786,11 +1864,13 @@ fn get_overlay_rect(app: AppHandle) -> Result<CaptureRect, String> {
|
||||
let win = app
|
||||
.get_webview_window("overlay")
|
||||
.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 (vl, vt, vr, vb) = visible_window_bounds(raw.0 as isize)
|
||||
.ok_or_else(|| "GetWindowRect failed".to_string())?;
|
||||
let (vl, vt, vr, vb) =
|
||||
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 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 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
|
||||
.strip_prefix(r"\\?\")
|
||||
.unwrap_or(&normalized)
|
||||
@@ -1889,8 +1970,12 @@ fn read_log_tail(log_dir: &Path) -> String {
|
||||
}
|
||||
}
|
||||
}
|
||||
let Some((_, path)) = newest else { return String::new() };
|
||||
let Ok(data) = std::fs::read(&path) else { return String::new() };
|
||||
let Some((_, path)) = newest else {
|
||||
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
|
||||
// always exists; get() just makes that explicit.
|
||||
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"
|
||||
)]
|
||||
#[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) {
|
||||
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)
|
||||
.clone()
|
||||
.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);
|
||||
@@ -2007,8 +2101,7 @@ async fn export(app: AppHandle, state: State<'_, AppState>, request: ExportReque
|
||||
}
|
||||
};
|
||||
if let Some(parent) = out_path.parent() {
|
||||
std::fs::create_dir_all(parent)
|
||||
.map_err(|e| format!("creating output dir: {e:#}"))?;
|
||||
std::fs::create_dir_all(parent).map_err(|e| format!("creating output dir: {e:#}"))?;
|
||||
}
|
||||
|
||||
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 {
|
||||
(c.width, (c.x, c.y))
|
||||
} 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 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:#}"))?;
|
||||
result.map_err(|e| format!("{e:#}"))?;
|
||||
|
||||
let size_bytes = std::fs::metadata(&out_path)
|
||||
.map_or(0, |m| m.len());
|
||||
let size_bytes = std::fs::metadata(&out_path).map_or(0, |m| m.len());
|
||||
Ok(ExportResult {
|
||||
met_target: size_bytes <= request.target_bytes,
|
||||
target_bytes: request.target_bytes,
|
||||
@@ -2148,7 +2235,9 @@ pub fn run() {
|
||||
let file_layer = tracing_subscriber::fmt::layer()
|
||||
.with_writer(file_writer)
|
||||
.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)]
|
||||
let registry = registry.with(tracing_subscriber::fmt::layer().with_writer(std::io::stdout));
|
||||
#[cfg(test)]
|
||||
@@ -2166,8 +2255,13 @@ pub fn run() {
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::error!("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");
|
||||
tracing::error!(
|
||||
"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 serde::{Deserialize, Serialize};
|
||||
|
||||
const GITEA_LATEST: &str =
|
||||
"https://git.lashman.live/api/v1/repos/lashman/bytesize/releases/latest";
|
||||
const GITEA_LATEST: &str = "https://git.lashman.live/api/v1/repos/lashman/bytesize/releases/latest";
|
||||
|
||||
/// 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
|
||||
@@ -61,7 +60,12 @@ pub(crate) async fn check_for_update() -> Result<Option<UpdateInfo>> {
|
||||
.assets
|
||||
.iter()
|
||||
.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());
|
||||
Ok(Some(UpdateInfo {
|
||||
version: latest,
|
||||
|
||||
@@ -7,8 +7,8 @@ use serde::Serialize;
|
||||
use tauri::{AppHandle, Emitter};
|
||||
use windows::core::BOOL;
|
||||
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::UI::Input::KeyboardAndMouse::GetAsyncKeyState;
|
||||
use windows::Win32::UI::WindowsAndMessaging::{
|
||||
EnumWindows, GetClassNameW, GetCursorPos, GetWindowLongW, GetWindowRect, IsIconic,
|
||||
IsWindowVisible, GWL_EXSTYLE, WS_EX_TOOLWINDOW,
|
||||
|
||||
Reference in New Issue
Block a user