From 7d89a332ff284f58266e8817e365d1fd46b2ed8b Mon Sep 17 00:00:00 2001 From: yumoqing Date: Sun, 28 Jun 2026 21:46:38 +0800 Subject: [PATCH] fix: omit -t flag when duration=0; use SIGINT for graceful stop --- .../StreamRecorderKit/FFmpegRecorder.swift | 19 +++++++++++++++---- 1 file changed, 15 insertions(+), 4 deletions(-) diff --git a/Sources/StreamRecorderKit/FFmpegRecorder.swift b/Sources/StreamRecorderKit/FFmpegRecorder.swift index 0898b64..a02c2b5 100644 --- a/Sources/StreamRecorderKit/FFmpegRecorder.swift +++ b/Sources/StreamRecorderKit/FFmpegRecorder.swift @@ -21,6 +21,7 @@ public final class FFmpegRecorder: StreamRecorderEngine { private var process: Process? private var duration: Double = 0 + private var stopRequested = false public init() {} @@ -46,14 +47,20 @@ public final class FFmpegRecorder: StreamRecorderEngine { // 启动 ffmpeg 进程 let proc = Process() proc.executableURL = URL(fileURLWithPath: ffmpegPath) - proc.arguments = [ + var args = [ "-y", "-i", resolvedURL.absoluteString, - "-t", String(duration), + ] + // duration=0 表示无限录制,不传 -t 参数 + if duration > 0 { + args += ["-t", String(duration)] + } + args += [ "-c", "copy", "-movflags", "+faststart", outputPath ] + proc.arguments = args let stderrPipe = Pipe() proc.standardError = stderrPipe @@ -102,7 +109,7 @@ public final class FFmpegRecorder: StreamRecorderEngine { stderrPipe.fileHandleForReading.readabilityHandler = nil isRecording = false - guard proc.terminationStatus == 0 else { + guard proc.terminationStatus == 0 || stopRequested else { throw RecordingError.processFailed(Int(proc.terminationStatus)) } @@ -117,7 +124,11 @@ public final class FFmpegRecorder: StreamRecorderEngine { } public func stop() { - process?.terminate() + stopRequested = true + // 发送 SIGINT (Ctrl+C) 让 ffmpeg 优雅关闭并写出文件头 + if let pid = process?.processIdentifier { + kill(pid, SIGINT) + } isRecording = false }