Files
GrowthLapse/Sources/GrowthLapse/FFmpegService.swift
T

254 lines
9.1 KiB
Swift

import Foundation
/// Cancellation belongs to this invocation, including the interval before launch.
private final class ProcessExecution: @unchecked Sendable {
private let lock = NSLock()
private let process = Process()
private var cancelled = false
func cancel() {
lock.lock()
defer { lock.unlock() }
cancelled = true
if process.isRunning { process.terminate() }
}
func execute(executable: URL, arguments: [String], directory: URL?,
onOutput: @escaping @Sendable (String) -> Void) throws -> ProcessResult {
let pipe = Pipe()
let input = try FileHandle(forReadingFrom: URL(fileURLWithPath: "/dev/null"))
defer {
try? input.close()
try? pipe.fileHandleForReading.close()
try? pipe.fileHandleForWriting.close()
}
process.executableURL = executable
process.arguments = arguments
process.currentDirectoryURL = directory
process.standardOutput = pipe
process.standardError = pipe
process.standardInput = input
lock.lock()
if cancelled {
lock.unlock()
throw CancellationError()
}
do { try process.run() } catch {
lock.unlock()
throw error
}
lock.unlock()
try? pipe.fileHandleForWriting.close()
var output = Data()
do {
while let chunk = try pipe.fileHandleForReading.read(upToCount: 65536), !chunk.isEmpty {
output.append(chunk)
if output.count > 4 * 1024 * 1024 {
output.removeFirst(output.count - 4 * 1024 * 1024)
}
onOutput(String(decoding: chunk, as: UTF8.self))
}
} catch {
cancel()
process.waitUntilExit()
throw error
}
process.waitUntilExit()
lock.lock()
let wasCancelled = cancelled
lock.unlock()
if wasCancelled { throw CancellationError() }
return ProcessResult(exitCode: process.terminationStatus,
output: String(decoding: output, as: UTF8.self))
}
}
struct ProcessResult {
let exitCode: Int32
let output: String
}
actor FFmpegService {
private var execution: ProcessExecution?
func findExecutable(named name: String) -> URL? {
let candidates = [
"/opt/homebrew/bin/\(name)",
"/usr/local/bin/\(name)",
"/usr/bin/\(name)"
]
for path in candidates where FileManager.default.isExecutableFile(atPath: path) {
return URL(fileURLWithPath: path)
}
let environmentPath = ProcessInfo.processInfo.environment["PATH"] ?? ""
for directory in environmentPath.split(separator: ":") {
let path = String(directory) + "/\(name)"
if FileManager.default.isExecutableFile(atPath: path) {
return URL(fileURLWithPath: path)
}
}
return nil
}
func validateTools(ffmpegOverride: URL? = nil, ffprobeOverride: URL? = nil) throws -> (ffmpeg: URL, ffprobe: URL) {
let ffmpeg: URL?
if let ffmpegOverride {
guard FileManager.default.isExecutableFile(atPath: ffmpegOverride.path) else {
throw VideoProcessingError.invalidToolPath("ffmpeg", ffmpegOverride.path)
}
ffmpeg = ffmpegOverride
} else {
ffmpeg = findExecutable(named: "ffmpeg")
}
let ffprobe: URL?
if let ffprobeOverride {
guard FileManager.default.isExecutableFile(atPath: ffprobeOverride.path) else {
throw VideoProcessingError.invalidToolPath("ffprobe", ffprobeOverride.path)
}
ffprobe = ffprobeOverride
} else {
ffprobe = findExecutable(named: "ffprobe")
}
guard let ffmpeg else {
throw VideoProcessingError.missingTool("ffmpeg")
}
guard let ffprobe else {
throw VideoProcessingError.missingTool("ffprobe")
}
return (ffmpeg, ffprobe)
}
func cancel() { execution?.cancel() }
func run(
executable: URL,
arguments: [String],
currentDirectory: URL? = nil,
onOutput: @escaping @Sendable (String) -> Void = { _ in }
) async throws -> ProcessResult {
try Task.checkCancellation()
guard execution == nil else {
throw VideoProcessingError.invalidSettings("Ein Werkzeugprozess läuft bereits.")
}
let current = ProcessExecution()
execution = current
defer { execution = nil }
return try await withTaskCancellationHandler {
try await withCheckedThrowingContinuation { continuation in
DispatchQueue.global(qos: .userInitiated).async {
do {
continuation.resume(returning: try current.execute(executable: executable,
arguments: arguments, directory: currentDirectory, onOutput: onOutput))
} catch { continuation.resume(throwing: error) }
}
}
} onCancel: {
current.cancel()
}
}
func validateEncoder(ffmpeg: URL, encoder: VideoEncoder, audio: Bool) async throws {
let result = try await run(executable: ffmpeg, arguments: ["-hide_banner", "-encoders"])
let name = encoder == .x264 ? "libx264" : "h264_videotoolbox"
guard result.exitCode == 0, result.output.contains(name),
!audio || result.output.contains(" aac ") else {
throw VideoProcessingError.invalidSettings("FFmpeg enthält den gewählten Video-/Audioencoder nicht. Bitte einen anderen Encoder oder FFmpeg-Build wählen.")
}
}
func availableFilters(ffmpeg: URL) async throws -> FFmpegFilterAvailability {
let result = try await run(
executable: ffmpeg,
arguments: ["-hide_banner", "-filters"]
)
guard result.exitCode == 0 else {
throw VideoProcessingError.ffmpegFailed("Filterprüfung", result.output)
}
return FFmpegFilterAvailability(
hasVidstabDetect: result.output.contains("vidstabdetect"),
hasVidstabTransform: result.output.contains("vidstabtransform"),
hasDeshake: result.output.contains("deshake"),
hasDrawtext: result.output.contains("drawtext")
)
}
}
enum VideoProcessingError: LocalizedError {
case missingTool(String)
case invalidToolPath(String, String)
case invalidSettings(String)
case noVideosFound
case ffprobeFailed(URL, String)
case ffmpegFailed(String, String)
case cancelled
var errorDescription: String? {
switch self {
case .missingTool(let tool):
return "\(tool) wurde nicht gefunden. Bitte installiere ffmpeg lokal, zum Beispiel mit Homebrew: brew install ffmpeg"
case .invalidToolPath(let tool, let path):
return "Der angegebene \(tool)-Pfad ist nicht ausführbar:\n\(path)\n\nBitte wähle die ausführbare Datei selbst aus, nicht nur den Ordner."
case .invalidSettings(let message):
return message
case .noVideosFound:
return "Im gewählten Ordner wurden keine unterstützten Videodateien gefunden."
case .ffprobeFailed(let url, let output):
let details = output.trimmingCharacters(in: .whitespacesAndNewlines)
if details.isEmpty {
return "Die Dauer von \(url.lastPathComponent) konnte nicht gelesen werden."
}
return "Die Dauer von \(url.lastPathComponent) konnte nicht gelesen werden.\n\(shortErrorDetails(details))"
case .ffmpegFailed(let step, let output):
let details = output.trimmingCharacters(in: .whitespacesAndNewlines)
if details.isEmpty {
return "ffmpeg ist bei Schritt \"\(step)\" fehlgeschlagen. Details stehen im Log."
}
return "ffmpeg ist bei Schritt \"\(step)\" fehlgeschlagen.\n\(shortErrorDetails(details))\n\nDetails stehen im Log."
case .cancelled:
return "Rendern wurde abgebrochen."
}
}
}
private func shortErrorDetails(_ output: String) -> String {
let lines = output
.replacingOccurrences(of: "\r", with: "\n")
.split(separator: "\n")
.map(String.init)
.filter { !$0.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty }
let importantLines = lines.filter { line in
let lower = line.lowercased()
return lower.contains("error")
|| lower.contains("failed")
|| lower.contains("invalid")
|| lower.contains("not found")
|| lower.contains("no such")
|| lower.contains("unable")
}
let selected: [String]
if importantLines.isEmpty {
selected = Array(lines.suffix(8))
} else {
selected = Array((importantLines.suffix(4) + lines.suffix(4)).suffix(8))
}
let text = selected.joined(separator: "\n")
if text.count <= 700 {
return text
}
let endIndex = text.index(text.startIndex, offsetBy: 700)
return String(text[..<endIndex]) + "..."
}