pause/resume with segment concat
This commit is contained in:
@@ -236,6 +236,45 @@ fn estimate_gif_scale_width(req: &TranscodeRequest) -> u32 {
|
||||
(w / 2) * 2
|
||||
}
|
||||
|
||||
pub fn concat_segments(ffmpeg: &Path, segments: &[PathBuf], output: &Path) -> Result<()> {
|
||||
if segments.is_empty() {
|
||||
bail!("no segments to concatenate");
|
||||
}
|
||||
if segments.len() == 1 {
|
||||
std::fs::copy(&segments[0], output).context("copying single segment")?;
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let parent = output
|
||||
.parent()
|
||||
.ok_or_else(|| anyhow!("output has no parent dir"))?;
|
||||
std::fs::create_dir_all(parent).context("creating output parent dir")?;
|
||||
|
||||
let list_path = parent.join("concat-list.txt");
|
||||
let mut body = String::new();
|
||||
for seg in segments {
|
||||
let s = seg
|
||||
.to_str()
|
||||
.ok_or_else(|| anyhow!("segment path is not UTF-8"))?
|
||||
.replace('\\', "/");
|
||||
body.push_str(&format!("file '{s}'\n"));
|
||||
}
|
||||
std::fs::write(&list_path, body).context("writing concat list")?;
|
||||
|
||||
let mut cmd = Command::new(ffmpeg);
|
||||
cmd.arg("-y")
|
||||
.arg("-hide_banner")
|
||||
.args(["-f", "concat"])
|
||||
.args(["-safe", "0"])
|
||||
.arg("-i")
|
||||
.arg(&list_path)
|
||||
.args(["-c", "copy"])
|
||||
.arg(output);
|
||||
let result = run(&mut cmd, "concat");
|
||||
let _ = std::fs::remove_file(&list_path);
|
||||
result
|
||||
}
|
||||
|
||||
fn run(cmd: &mut Command, label: &str) -> Result<()> {
|
||||
let mut printable = OsString::from(label);
|
||||
printable.push(": ");
|
||||
|
||||
+138
-15
@@ -27,6 +27,17 @@ pub struct AppState {
|
||||
pub config: Mutex<Config>,
|
||||
pub capture: Mutex<Option<capture::CaptureSession>>,
|
||||
pub last_clip: Mutex<Option<RecordedClip>>,
|
||||
pub session: Mutex<Option<SessionState>>,
|
||||
}
|
||||
|
||||
pub struct SessionState {
|
||||
pub segments: Vec<PathBuf>,
|
||||
pub total_recorded_secs: f64,
|
||||
pub capture_cursor: bool,
|
||||
pub audio: bool,
|
||||
pub crop: Option<CaptureRect>,
|
||||
pub width: u32,
|
||||
pub height: u32,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
@@ -188,22 +199,43 @@ pub struct StartCaptureRequest {
|
||||
pub crop: Option<CaptureRect>,
|
||||
}
|
||||
|
||||
fn segment_path(app_dir: &Path, idx: usize) -> PathBuf {
|
||||
temp_dir(app_dir).join(format!("segment-{:03}.mp4", idx))
|
||||
}
|
||||
|
||||
fn clear_temp_segments(app_dir: &Path) {
|
||||
let temp = temp_dir(app_dir);
|
||||
if let Ok(entries) = std::fs::read_dir(&temp) {
|
||||
for entry in entries.flatten() {
|
||||
if let Some(name) = entry.file_name().to_str() {
|
||||
if name.starts_with("segment-") && name.ends_with(".mp4") {
|
||||
let _ = std::fs::remove_file(entry.path());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let _ = std::fs::remove_file(temp.join("recording.mp4"));
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
fn start_capture(
|
||||
state: State<'_, AppState>,
|
||||
request: Option<StartCaptureRequest>,
|
||||
) -> Result<(), String> {
|
||||
let mut slot = state.capture.lock().expect("capture mutex");
|
||||
{
|
||||
let slot = state.capture.lock().expect("capture mutex");
|
||||
if slot.is_some() {
|
||||
return Err("a capture is already running".to_string());
|
||||
}
|
||||
}
|
||||
let cfg = state.config.lock().expect("config mutex").clone();
|
||||
let temp = temp_dir(&state.app_dir);
|
||||
std::fs::create_dir_all(&temp).map_err(|e| format!("creating temp dir: {e}"))?;
|
||||
let output = temp.join("recording.mp4");
|
||||
let _ = std::fs::remove_file(&output);
|
||||
clear_temp_segments(&state.app_dir);
|
||||
|
||||
let crop = request.and_then(|r| r.crop);
|
||||
let output = segment_path(&state.app_dir, 1);
|
||||
|
||||
let session = capture::start(
|
||||
output,
|
||||
cfg.capture.capture_cursor,
|
||||
@@ -211,30 +243,118 @@ fn start_capture(
|
||||
crop,
|
||||
)
|
||||
.map_err(|e| format!("{e:#}"))?;
|
||||
*slot = Some(session);
|
||||
|
||||
let session_state = SessionState {
|
||||
segments: Vec::new(),
|
||||
total_recorded_secs: 0.0,
|
||||
capture_cursor: cfg.capture.capture_cursor,
|
||||
audio: cfg.capture.capture_audio,
|
||||
crop,
|
||||
width: session.width,
|
||||
height: session.height,
|
||||
};
|
||||
|
||||
*state.session.lock().expect("session mutex") = Some(session_state);
|
||||
*state.capture.lock().expect("capture mutex") = Some(session);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
fn stop_capture(state: State<'_, AppState>) -> Result<RecordedClip, String> {
|
||||
fn pause_capture(state: State<'_, AppState>) -> Result<(), String> {
|
||||
let session = state
|
||||
.capture
|
||||
.lock()
|
||||
.expect("capture mutex")
|
||||
.take()
|
||||
.ok_or_else(|| "no capture in progress".to_string())?;
|
||||
let duration_secs = session.started_at.elapsed().as_secs_f64();
|
||||
let width = session.width;
|
||||
let height = session.height;
|
||||
let crop = session.crop;
|
||||
let temp_path = session.stop().map_err(|e| format!("{e:#}"))?;
|
||||
let elapsed = session.started_at.elapsed().as_secs_f64();
|
||||
let path = session.stop().map_err(|e| format!("{e:#}"))?;
|
||||
|
||||
let mut ss = state.session.lock().expect("session mutex");
|
||||
let ss = ss
|
||||
.as_mut()
|
||||
.ok_or_else(|| "no session state".to_string())?;
|
||||
ss.segments.push(path);
|
||||
ss.total_recorded_secs += elapsed;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
fn resume_capture(state: State<'_, AppState>) -> Result<(), String> {
|
||||
{
|
||||
let slot = state.capture.lock().expect("capture mutex");
|
||||
if slot.is_some() {
|
||||
return Err("a capture is already running".to_string());
|
||||
}
|
||||
}
|
||||
let (capture_cursor, audio, crop, next_idx) = {
|
||||
let ss = state.session.lock().expect("session mutex");
|
||||
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,
|
||||
)
|
||||
};
|
||||
|
||||
let output = segment_path(&state.app_dir, next_idx);
|
||||
let session = capture::start(output, capture_cursor, audio, crop)
|
||||
.map_err(|e| format!("{e:#}"))?;
|
||||
*state.capture.lock().expect("capture mutex") = Some(session);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
fn stop_capture(state: State<'_, AppState>) -> Result<RecordedClip, String> {
|
||||
let mut ss = state
|
||||
.session
|
||||
.lock()
|
||||
.expect("session mutex")
|
||||
.take()
|
||||
.ok_or_else(|| "no session to stop".to_string())?;
|
||||
|
||||
let live = state.capture.lock().expect("capture mutex").take();
|
||||
if let Some(session) = live {
|
||||
let elapsed = session.started_at.elapsed().as_secs_f64();
|
||||
let path = session.stop().map_err(|e| format!("{e:#}"))?;
|
||||
ss.segments.push(path);
|
||||
ss.total_recorded_secs += elapsed;
|
||||
}
|
||||
|
||||
if ss.segments.is_empty() {
|
||||
return Err("no recorded segments".to_string());
|
||||
}
|
||||
|
||||
let final_path = temp_dir(&state.app_dir).join("recording.mp4");
|
||||
if ss.segments.len() == 1 {
|
||||
let only = ss.segments.remove(0);
|
||||
if only != final_path {
|
||||
std::fs::rename(&only, &final_path)
|
||||
.or_else(|_| std::fs::copy(&only, &final_path).map(|_| ()))
|
||||
.map_err(|e| format!("finalizing single segment: {e}"))?;
|
||||
let _ = std::fs::remove_file(&only);
|
||||
}
|
||||
} else {
|
||||
let ffmpeg = bootstrap::ffmpeg_path(&state.app_dir);
|
||||
if !ffmpeg.is_file() {
|
||||
return Err("ffmpeg.exe not found for concatenation".to_string());
|
||||
}
|
||||
encode::concat_segments(&ffmpeg, &ss.segments, &final_path)
|
||||
.map_err(|e| format!("concat: {e:#}"))?;
|
||||
for seg in &ss.segments {
|
||||
let _ = std::fs::remove_file(seg);
|
||||
}
|
||||
}
|
||||
|
||||
let clip = RecordedClip {
|
||||
temp_path,
|
||||
duration_secs,
|
||||
width,
|
||||
height,
|
||||
crop,
|
||||
temp_path: final_path,
|
||||
duration_secs: ss.total_recorded_secs,
|
||||
width: ss.width,
|
||||
height: ss.height,
|
||||
crop: ss.crop,
|
||||
};
|
||||
*state.last_clip.lock().expect("clip mutex") = Some(clip.clone());
|
||||
Ok(clip)
|
||||
@@ -382,6 +502,7 @@ pub fn run() {
|
||||
config: Mutex::new(cfg),
|
||||
capture: Mutex::new(None),
|
||||
last_clip: Mutex::new(None),
|
||||
session: Mutex::new(None),
|
||||
};
|
||||
|
||||
tauri::Builder::default()
|
||||
@@ -393,6 +514,8 @@ pub fn run() {
|
||||
save_config,
|
||||
download_ffmpeg,
|
||||
start_capture,
|
||||
pause_capture,
|
||||
resume_capture,
|
||||
stop_capture,
|
||||
export,
|
||||
reveal_in_explorer,
|
||||
|
||||
+40
-3
@@ -9,7 +9,7 @@
|
||||
type ExportResult,
|
||||
} from "./api"
|
||||
|
||||
type Phase = "idle" | "recording" | "editing" | "exporting" | "done"
|
||||
type Phase = "idle" | "recording" | "paused" | "editing" | "exporting" | "done"
|
||||
|
||||
let { onSettings }: { onSettings: () => void } = $props()
|
||||
|
||||
@@ -97,6 +97,27 @@
|
||||
}
|
||||
}
|
||||
|
||||
async function pauseRec() {
|
||||
clearTick()
|
||||
try {
|
||||
await api.pauseCapture()
|
||||
phase = "paused"
|
||||
} catch (e) {
|
||||
errMsg = String(e)
|
||||
tick()
|
||||
}
|
||||
}
|
||||
|
||||
async function resumeRec() {
|
||||
try {
|
||||
await api.resumeCapture()
|
||||
phase = "recording"
|
||||
tick()
|
||||
} catch (e) {
|
||||
errMsg = String(e)
|
||||
}
|
||||
}
|
||||
|
||||
function minMB(durationSecs: number): number {
|
||||
const minBytes = Math.max(50_000, durationSecs * 50_000)
|
||||
return Math.max(0.1, minBytes / 1_048_576)
|
||||
@@ -140,6 +161,7 @@
|
||||
<h1>ByteSize</h1>
|
||||
<p class="sub">
|
||||
{#if phase === "recording"}recording...
|
||||
{:else if phase === "paused"}paused
|
||||
{:else if phase === "editing"}clip ready
|
||||
{:else if phase === "exporting"}encoding...
|
||||
{:else if phase === "done"}exported
|
||||
@@ -165,10 +187,19 @@
|
||||
a region instead.
|
||||
{/if}
|
||||
</p>
|
||||
{:else if phase === "recording"}
|
||||
{:else if phase === "recording" || phase === "paused"}
|
||||
<section class="recording">
|
||||
<div class="elapsed">{elapsed.toFixed(1)}s</div>
|
||||
<div class="elapsed" class:paused={phase === "paused"}>
|
||||
{elapsed.toFixed(1)}s
|
||||
</div>
|
||||
<div class="row recording-row">
|
||||
<button class="stop big" onclick={stopRec}>stop</button>
|
||||
{#if phase === "recording"}
|
||||
<button class="big" onclick={pauseRec}>pause</button>
|
||||
{:else}
|
||||
<button class="primary big" onclick={resumeRec}>resume</button>
|
||||
{/if}
|
||||
</div>
|
||||
</section>
|
||||
{:else if phase === "editing" && clip}
|
||||
<section class="clip">
|
||||
@@ -336,6 +367,12 @@
|
||||
font-variant-numeric: tabular-nums;
|
||||
color: #4a8;
|
||||
}
|
||||
.elapsed.paused {
|
||||
color: #c93;
|
||||
}
|
||||
.recording-row {
|
||||
justify-content: center;
|
||||
}
|
||||
button {
|
||||
font: inherit;
|
||||
padding: 0.5rem 1rem;
|
||||
|
||||
@@ -89,6 +89,8 @@ export const api = {
|
||||
listen<DownloadProgress>("ffmpeg-progress", (e) => handler(e.payload)),
|
||||
startCapture: (request: StartCaptureRequest) =>
|
||||
invoke<void>("start_capture", { request }),
|
||||
pauseCapture: () => invoke<void>("pause_capture"),
|
||||
resumeCapture: () => invoke<void>("resume_capture"),
|
||||
stopCapture: () => invoke<RecordedClip>("stop_capture"),
|
||||
export: (request: ExportRequest) => invoke<ExportResult>("export", { request }),
|
||||
revealInExplorer: (path: string) => invoke<void>("reveal_in_explorer", { path }),
|
||||
|
||||
Reference in New Issue
Block a user