Skip to content

Open source CapCut alternative.

TypeScript

feat(app): on-device shorts pipeline (reframe + transcribe + media.cut)

David Le774ea77b0379
diff --git a/.github/workflows/publish-bundled-tools.yml b/.github/workflows/publish-bundled-tools.yml
index 6e01757d..a3602afb 100644
--- a/.github/workflows/publish-bundled-tools.yml
+++ b/.github/workflows/publish-bundled-tools.yml
@@ -17,7 +17,7 @@ on:
branches: [main]
paths:
- scripts/fetch-bundled-tools.sh
- - tools/pdf-fill/main.swift
+ - tools/**
permissions:
contents: write
@@ -47,13 +47,14 @@ jobs:
echo "version=$v" >> "$GITHUB_OUTPUT"
# Same cache key as the nightly build, so the two share a single ffmpeg/Rust build. The key busts
- # when the recipe or the in-repo pdf-fill source changes, which is also what triggers this workflow.
+ # when the recipe or any in-repo tool source (pdf-fill, epub-pack, reframe, …) changes, which is
+ # also what triggers this workflow.
- name: Restore bundled tools cache
id: tools-cache
uses: actions/cache@v4
with:
path: vendor/donkey-tools
- key: donkey-tools-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('scripts/fetch-bundled-tools.sh', 'tools/pdf-fill/main.swift') }}
+ key: donkey-tools-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('scripts/fetch-bundled-tools.sh', 'tools/**') }}
# Import the Developer ID cert into a throwaway keychain and stage the notary API key, so the tools
# are production-signed + notarized. Absent the secrets this no-ops to ad-hoc signing (still runnable,
diff --git a/apps/Donkey/Sources/Donkey/AppleSpeechVoiceTranscriptionRuntime.swift b/apps/Donkey/Sources/Donkey/AppleSpeechVoiceTranscriptionRuntime.swift
index 3e366eb7..76820e59 100644
--- a/apps/Donkey/Sources/Donkey/AppleSpeechVoiceTranscriptionRuntime.swift
+++ b/apps/Donkey/Sources/Donkey/AppleSpeechVoiceTranscriptionRuntime.swift
@@ -1,4 +1,5 @@
import AVFoundation
+import CoreMedia
import DonkeyAI
import Foundation
import Speech
@@ -16,6 +17,60 @@ import Speech
public struct AppleSpeechVoiceTranscriptionRuntime: LocalVoiceTranscriptionRuntime {
public init() {}
+ /// One spoken word with its measured time span (milliseconds from the start of the file). This is
+ /// the timing both Apple paths already compute per run/segment — it used to be discarded.
+ public struct TranscribedWord: Sendable {
+ public let text: String
+ public let startMS: Int
+ public let endMS: Int
+ public let confidence: Double
+ }
+
+ /// A full file transcript: the plain text plus the per-word timings the editing flow cuts against.
+ public struct FileTranscript: Sendable {
+ public let text: String
+ public let words: [TranscribedWord]
+ public let localeIdentifier: String
+ public let backend: String
+ }
+
+ /// Transcribe a local audio file on-device into text *with per-word timings*. This is the same
+ /// engine the voice path uses, but it keeps the word-level time ranges instead of flattening to a
+ /// string. The file must be one the platform audio stack can open directly (wav/m4a/mp3/caf/aiff);
+ /// for a video, extract compact audio first — a file it cannot read throws, and the caller surfaces
+ /// that so the planner extracts audio and retries. Audio never leaves the machine.
+ public func transcribeFile(
+ at fileURL: URL,
+ preferredLocale: Locale = .current
+ ) async throws -> FileTranscript {
+ if #available(macOS 26, *) {
+ let resolved = try await Self.resolvedSpeechAnalyzerLocale(preferred: preferredLocale)
+ let output = try await Self.runSpeechAnalyzer(fileURL: fileURL, locale: resolved)
+ let text = output.text.trimmingCharacters(in: .whitespacesAndNewlines)
+ guard !text.isEmpty else { throw LocalVoiceTranscriptionRuntimeError.emptyTranscript }
+ return FileTranscript(
+ text: text,
+ words: output.words,
+ localeIdentifier: resolved.identifier,
+ backend: "apple-speechanalyzer"
+ )
+ }
+
+ let result = try await Self.runLegacyRecognizer(
+ fileURL: fileURL,
+ preferred: preferredLocale,
+ timeoutMS: 120_000
+ )
+ let text = result.text.trimmingCharacters(in: .whitespacesAndNewlines)
+ guard !text.isEmpty else { throw LocalVoiceTranscriptionRuntimeError.emptyTranscript }
+ return FileTranscript(
+ text: text,
+ words: result.words,
+ localeIdentifier: result.language,
+ backend: "apple-sfspeech"
+ )
+ }
+
/// Download the on-device locale model ahead of time so the first voice command
/// doesn't pay a multi-second model install under the "Transcribing…" state.
/// Fire-and-forget; failures are ignored (the live path retries and falls back).
@@ -45,9 +100,9 @@ public struct AppleSpeechVoiceTranscriptionRuntime: LocalVoiceTranscriptionRunti
if #available(macOS 26, *) {
let resolved = try await Self.resolvedSpeechAnalyzerLocale(preferred: Locale.current)
- let text = try await Self.runSpeechAnalyzer(fileURL: fileURL, locale: resolved)
+ let output = try await Self.runSpeechAnalyzer(fileURL: fileURL, locale: resolved)
return try Self.transcript(
- text: text,
+ text: output.text,
language: resolved.identifier,
backend: "apple-speechanalyzer"
)
@@ -82,12 +137,17 @@ public struct AppleSpeechVoiceTranscriptionRuntime: LocalVoiceTranscriptionRunti
}
@available(macOS 26, *)
- private static func runSpeechAnalyzer(fileURL: URL, locale: Locale) async throws -> String {
+ private static func runSpeechAnalyzer(
+ fileURL: URL,
+ locale: Locale
+ ) async throws -> (text: String, words: [TranscribedWord]) {
+ // Ask the transcriber to attach an audio time range to every run so the result carries per-word
+ // timing, not just text. Without this option the runs come back untimed.
let transcriber = SpeechTranscriber(
locale: locale,
transcriptionOptions: [],
reportingOptions: [],
- attributeOptions: []
+ attributeOptions: [.audioTimeRange]
)
try await ensureModelInstalled(transcriber, locale: locale)
@@ -114,7 +174,24 @@ public struct AppleSpeechVoiceTranscriptionRuntime: LocalVoiceTranscriptionRunti
}
let attributed = try await collector.value
- return String(attributed.characters)
+ return (String(attributed.characters), words(from: attributed))
+ }
+
+ /// Walk the transcript's runs and turn each timed run into a word. Runs without an audio time range
+ /// (or that are pure whitespace) are skipped, so the result is the spoken words with their spans.
+ @available(macOS 26, *)
+ private static func words(from attributed: AttributedString) -> [TranscribedWord] {
+ var words: [TranscribedWord] = []
+ for run in attributed.runs {
+ guard let timeRange = run.audioTimeRange else { continue }
+ let piece = String(attributed[run.range].characters)
+ .trimmingCharacters(in: .whitespacesAndNewlines)
+ guard !piece.isEmpty else { continue }
+ let startMS = max(0, Int((timeRange.start.seconds * 1000).rounded()))
+ let endMS = max(startMS, Int((timeRange.end.seconds * 1000).rounded()))
+ words.append(TranscribedWord(text: piece, startMS: startMS, endMS: endMS, confidence: 1))
+ }
+ return words
}
@available(macOS 26, *)
@@ -134,7 +211,7 @@ public struct AppleSpeechVoiceTranscriptionRuntime: LocalVoiceTranscriptionRunti
fileURL: URL,
preferred: Locale,
timeoutMS: Int
- ) async throws -> (text: String, language: String) {
+ ) async throws -> (text: String, language: String, words: [TranscribedWord]) {
try await requestLegacyAuthorization()
guard let recognizer = SFSpeechRecognizer(locale: preferred)
@@ -150,7 +227,9 @@ public struct AppleSpeechVoiceTranscriptionRuntime: LocalVoiceTranscriptionRunti
request.requiresOnDeviceRecognition = true
request.shouldReportPartialResults = false
- let text: String = try await withCheckedThrowingContinuation { continuation in
+ // Build the Sendable pieces (text + timed words) inside the recognition handler so a
+ // non-Sendable SFTranscription never crosses into the continuation (Swift 6 data-race safety).
+ let outcome: (text: String, words: [TranscribedWord]) = try await withCheckedThrowingContinuation { continuation in
let resume = SingleResume(continuation)
let task = recognizer.recognitionTask(with: request) { result, error in
if let error {
@@ -158,14 +237,28 @@ public struct AppleSpeechVoiceTranscriptionRuntime: LocalVoiceTranscriptionRunti
return
}
guard let result, result.isFinal else { return }
- resume.succeed(result.bestTranscription.formattedString)
+ let transcription = result.bestTranscription
+ resume.succeed((transcription.formattedString, legacyWords(from: transcription)))
}
// SFSpeechRecognizer can stall without ever invoking the handler; bound it
// so a hung recognition throws and falls through to Gemini instead of
// leaving the UI stuck on "Transcribing…".
resume.start(task: task, timeoutMS: timeoutMS)
}
- return (text, recognizer.locale.identifier)
+ return (outcome.text, recognizer.locale.identifier, outcome.words)
+ }
+
+ /// Map an SFSpeech transcription's per-segment timing into words. Called inside the recognition
+ /// handler so only Sendable values cross the continuation boundary.
+ private static func legacyWords(from transcription: SFTranscription) -> [TranscribedWord] {
+ transcription.segments.compactMap { segment -> TranscribedWord? in
+ let piece = segment.substring.trimmingCharacters(in: .whitespacesAndNewlines)
+ guard !piece.isEmpty else { return nil }
+ let startMS = max(0, Int((segment.timestamp * 1000).rounded()))
+ let endMS = max(startMS, Int(((segment.timestamp + segment.duration) * 1000).rounded()))
+ let confidence = segment.confidence > 0 ? Double(segment.confidence) : 1
+ return TranscribedWord(text: piece, startMS: startMS, endMS: endMS, confidence: confidence)
+ }
}
private static func requestLegacyAuthorization() async throws {
@@ -187,14 +280,14 @@ public struct AppleSpeechVoiceTranscriptionRuntime: LocalVoiceTranscriptionRunti
/// Guards a checked continuation so the recognition handler — which can fire
/// more than once, or not at all — resumes it exactly once, and enforces a
/// timeout that cancels a stalled recognition.
- private final class SingleResume: @unchecked Sendable {
- private let continuation: CheckedContinuation<String, Error>
+ private final class SingleResume<Value: Sendable>: @unchecked Sendable {
+ private let continuation: CheckedContinuation<Value, Error>
private let lock = NSLock()
private var resumed = false
private var task: SFSpeechRecognitionTask?
private var timeoutTask: Task<Void, Never>?
- init(_ continuation: CheckedContinuation<String, Error>) {
+ init(_ continuation: CheckedContinuation<Value, Error>) {
self.continuation = continuation
}
@@ -213,11 +306,11 @@ public struct AppleSpeechVoiceTranscriptionRuntime: LocalVoiceTranscriptionRunti
lock.unlock()
}
- func succeed(_ value: String) { finish(.success(value)) }
+ func succeed(_ value: Value) { finish(.success(value)) }
func fail(_ error: Error) { finish(.failure(error)) }
- private func finish(_ result: Result<String, Error>) {
+ private func finish(_ result: Result<Value, Error>) {
lock.lock()
guard !resumed else {
lock.unlock()
diff --git a/apps/Donkey/Sources/DonkeyRuntime/BundledTools.swift b/apps/Donkey/Sources/DonkeyRuntime/BundledTools.swift
index 1d163b15..2073cc53 100644
--- a/apps/Donkey/Sources/DonkeyRuntime/BundledTools.swift
+++ b/apps/Donkey/Sources/DonkeyRuntime/BundledTools.swift
@@ -13,7 +13,7 @@ public enum BundledTools {
/// skills run them by bare name. This is the single Swift home for the list; keep it in step with the
/// fetch/publish scripts when the bundle gains or drops a tool.
public static let executableNames: Set<String> = [
- "ffmpeg", "ffprobe", "yt-dlp", "lit", "pdf-fill", "epub-pack", "qpdf", "exiftool"
+ "ffmpeg", "ffprobe", "yt-dlp", "lit", "pdf-fill", "epub-pack", "reframe", "qpdf", "exiftool"
]
/// Tools that unpack a private interpreter/runtime to a temp dir at launch and `dlopen()` it — a
diff --git a/apps/Donkey/Sources/DonkeyRuntime/MediaCutEngine.swift b/apps/Donkey/Sources/DonkeyRuntime/MediaCutEngine.swift
new file mode 100644
index 00000000..375ca9bf
--- /dev/null
+++ b/apps/Donkey/Sources/DonkeyRuntime/MediaCutEngine.swift
@@ -0,0 +1,263 @@
+import DonkeyHarness
+import Foundation
+
+/// The IO half of `media.cut`: it runs the bundled ffmpeg/ffprobe to detect silence, reads the
+/// `transcribe` JSON for fillers, asks `MediaCutPlanner` (pure, tested) for the exact spans to keep, then
+/// renders the cut by re-encoding the kept segments and concatenating them. Frame-accurate, audio and
+/// video in lockstep, and fully deterministic — the model picks WHAT to remove, never HOW.
+///
+/// The render uses `h264_videotoolbox` because Donkey's bundled ffmpeg is the LGPL build with no
+/// libx264; VideoToolbox is the hardware H.264 encoder that is present.
+public enum MediaCutEngine {
+ /// Run a cut request to completion. Blocking ffmpeg work runs off the calling actor.
+ public static func run(_ request: HarnessMediaCutRequest) async -> HarnessMediaCutResult {
+ await Task.detached(priority: .userInitiated) { runSync(request) }.value
+ }
+
+ // MARK: - Orchestration
+
+ private static func runSync(_ request: HarnessMediaCutRequest) -> HarnessMediaCutResult {
+ let inputURL = URL(fileURLWithPath: request.inputPath)
+ let failed: (String) -> HarnessMediaCutResult = { reason in
+ HarnessMediaCutResult(outputPath: "", removedSpanCount: 0, inputDurationSec: 0, outputDurationSec: 0, failureReason: reason)
+ }
+
+ guard let toolsDir = DonkeyCommandBackends.bundledToolsDirectory else {
+ return failed("the media tools are still installing — try again in a moment")
+ }
+ let ffmpeg = toolsDir.appendingPathComponent("ffmpeg")
+ let ffprobe = toolsDir.appendingPathComponent("ffprobe")
+ guard FileManager.default.isExecutableFile(atPath: ffmpeg.path),
+ FileManager.default.isExecutableFile(atPath: ffprobe.path) else {
+ return failed("the media tools are still installing — try again in a moment")
+ }
+
+ guard let duration = probeDuration(ffprobe, inputURL), duration > 0 else {
+ return failed("could not read the file's duration — is \(inputURL.lastPathComponent) a real media file?")
+ }
+ let streams = probeStreams(ffprobe, inputURL)
+ guard streams.hasVideo || streams.hasAudio else {
+ return failed("the file has no audio or video stream to edit")
+ }
+
+ let parameters = MediaCutPlanner.Parameters()
+ var removals: [MediaTimeSpan] = []
+
+ if request.removeSilence {
+ let detect = runProcess(
+ ffmpeg,
+ ["-hide_banner", "-nostats", "-i", inputURL.path, "-af", "silencedetect=noise=-30dB:d=0.5", "-f", "null", "-"],
+ timeout: max(120, duration)
+ )
+ // silencedetect logs to stderr.
+ removals += MediaCutPlanner.silenceSpans(fromSilenceDetect: detect.stderr, keepPauseSec: parameters.keepPauseSec)
+ }
+
+ if request.removeFillers {
+ guard let path = request.transcriptPath, let data = try? Data(contentsOf: URL(fileURLWithPath: path)) else {
+ return failed("could not read the transcript JSON for filler detection")
+ }
+ let lexicon = request.fillerWords.isEmpty
+ ? MediaCutPlanner.defaultFillerLexicon
+ : Set(request.fillerWords.map { $0.lowercased() })
+ removals += MediaCutPlanner.fillerSpans(fromTranscriptJSON: data, lexicon: lexicon, padSec: parameters.fillerPadSec)
+ }
+
+ if let explicit = request.explicitRemovals {
+ removals += MediaCutPlanner.explicitSpans(fromList: explicit)
+ }
+
+ let keeps = MediaCutPlanner.keepSegments(removing: removals, duration: duration, parameters: parameters)
+ if keeps.isEmpty {
+ return failed("the spans to remove cover the entire file — nothing would be left")
+ }
+ let cutCount = removedRegionCount(keeps: keeps, duration: duration)
+ if cutCount == 0 {
+ // Nothing matched (or every match fell below the floors): a clean no-op, source left as-is.
+ return HarnessMediaCutResult(
+ outputPath: inputURL.path,
+ removedSpanCount: 0,
+ inputDurationSec: duration,
+ outputDurationSec: duration,
+ failureReason: nil
+ )
+ }
+
+ let outputURL = resolveOutputURL(request: request, input: inputURL)
+ let graph = MediaCutPlanner.filterGraph(keeping: keeps, hasVideo: streams.hasVideo, hasAudio: streams.hasAudio)
+ let scriptURL = FileManager.default.temporaryDirectory
+ .appendingPathComponent("donkey-mediacut-\(UUID().uuidString).txt")
+ do {
+ try graph.write(to: scriptURL, atomically: true, encoding: .utf8)
+ } catch {
+ return failed("could not stage the cut filtergraph: \(error.localizedDescription)")
+ }
+ defer { try? FileManager.default.removeItem(at: scriptURL) }
+
+ let renderArgs = renderArguments(
+ input: inputURL,
+ output: outputURL,
+ script: scriptURL,
+ streams: streams,
+ videoBitrate: streams.hasVideo ? probeVideoBitrate(ffprobe, inputURL) : nil
+ )
+ let render = runProcess(ffmpeg, renderArgs, timeout: max(180, min(duration * 2, 1800)))
+ guard render.exitCode == 0, FileManager.default.fileExists(atPath: outputURL.path) else {
+ let tail = String(render.stderr.suffix(400))
+ return failed("ffmpeg render failed (exit \(render.exitCode)): \(tail)")
+ }
+
+ let outputDuration = probeDuration(ffprobe, outputURL) ?? 0
+ return HarnessMediaCutResult(
+ outputPath: outputURL.path,
+ removedSpanCount: cutCount,
+ inputDurationSec: duration,
+ outputDurationSec: outputDuration,
+ failureReason: nil
+ )
+ }
+
+ // MARK: - ffprobe helpers
+
+ private static func probeDuration(_ ffprobe: URL, _ url: URL) -> Double? {
+ let result = runProcess(
+ ffprobe,
+ ["-v", "error", "-show_entries", "format=duration", "-of", "default=noprint_wrappers=1:nokey=1", url.path],
+ timeout: 30
+ )
+ return Double(result.stdout.trimmingCharacters(in: .whitespacesAndNewlines))
+ }
+
+ private static func probeStreams(_ ffprobe: URL, _ url: URL) -> (hasVideo: Bool, hasAudio: Bool) {
+ let result = runProcess(
+ ffprobe,
+ ["-v", "error", "-show_entries", "stream=codec_type", "-of", "default=noprint_wrappers=1:nokey=1", url.path],
+ timeout: 30
+ )
+ let types = Set(result.stdout.split(whereSeparator: { $0 == "\n" || $0 == "\r" }).map { String($0).trimmingCharacters(in: .whitespaces) })
+ return (types.contains("video"), types.contains("audio"))
+ }
+
+ private static func probeVideoBitrate(_ ffprobe: URL, _ url: URL) -> String? {
+ let result = runProcess(
+ ffprobe,
+ ["-v", "error", "-select_streams", "v:0", "-show_entries", "stream=bit_rate", "-of", "default=noprint_wrappers=1:nokey=1", url.path],
+ timeout: 30
+ )
+ let value = result.stdout.trimmingCharacters(in: .whitespacesAndNewlines)
+ return (Int(value) != nil) ? value : nil
+ }
+
+ // MARK: - Render
+
+ private static func renderArguments(
+ input: URL,
+ output: URL,
+ script: URL,
+ streams: (hasVideo: Bool, hasAudio: Bool),
+ videoBitrate: String?
+ ) -> [String] {
+ var args = ["-y", "-hide_banner", "-i", input.path, "-filter_complex_script", script.path]
+ if streams.hasVideo { args += ["-map", "[v]"] }
+ if streams.hasAudio { args += ["-map", "[a]"] }
+ if streams.hasVideo {
+ args += ["-c:v", "h264_videotoolbox"]
+ if let videoBitrate { args += ["-b:v", videoBitrate] }
+ }
+ if streams.hasAudio {
+ args += ["-c:a", "aac", "-b:a", "192k"]
+ }
+ args += ["-movflags", "+faststart", output.path]
+ return args
+ }
+
+ /// Default output path: `<name>-tightened.<ext>` beside the source, unless the caller named one.
+ private static func resolveOutputURL(request: HarnessMediaCutRequest, input: URL) -> URL {
+ if let outputPath = request.outputPath, !outputPath.isEmpty {
+ return URL(fileURLWithPath: outputPath)
+ }
+ let ext = input.pathExtension
+ let stem = input.deletingPathExtension().lastPathComponent
+ let directory = input.deletingLastPathComponent()
+ let base = directory.appendingPathComponent("\(stem)-tightened")
+ return ext.isEmpty ? base : base.appendingPathExtension(ext)
+ }
+
+ /// Count the removed regions implied by the kept segments — the leading gap, each internal gap, and a
+ /// trailing gap. Zero means the keeps cover the whole file (nothing was actually cut).
+ private static func removedRegionCount(keeps: [MediaTimeSpan], duration: Double) -> Int {
+ let epsilon = 1e-3
+ var count = 0
+ var cursor = 0.0
+ for keep in keeps {
+ if keep.start - cursor > epsilon { count += 1 }
+ cursor = keep.end
+ }
+ if duration - cursor > epsilon { count += 1 }
+ return count
+ }
+
+ // MARK: - Process
+
+ private struct ProcessOutput {
+ var exitCode: Int32
+ var stdout: String
+ var stderr: String
+ var timedOut: Bool
+ }
+
+ private final class DataBox: @unchecked Sendable {
+ var data = Data()
+ }
+
+ /// Run a bundled tool directly (no shell), draining stdout/stderr on background queues so a large
+ /// stderr (silencedetect, ffmpeg progress) never deadlocks the pipe, bounded by `timeout`.
+ private static func runProcess(_ executable: URL, _ arguments: [String], timeout: TimeInterval) -> ProcessOutput {
+ let process = Process()
+ process.executableURL = executable
+ process.arguments = arguments
+ process.environment = DonkeyCommandBackends.shellEnvironment()
+ process.currentDirectoryURL = FileManager.default.homeDirectoryForCurrentUser
+
+ let outPipe = Pipe()
+ let errPipe = Pipe()
+ process.standardOutput = outPipe
+ process.standardError = errPipe
+
+ let finished = DispatchSemaphore(value: 0)
+ process.terminationHandler = { _ in finished.signal() }
+
+ do {
+ try process.run()
+ } catch {
+ return ProcessOutput(exitCode: 127, stdout: "", stderr: error.localizedDescription, timedOut: false)
+ }
+
+ let outBox = DataBox()
+ let errBox = DataBox()
+ let reads = DispatchGroup()
+ reads.enter()
+ DispatchQueue.global().async { outBox.data = outPipe.fileHandleForReading.readDataToEndOfFile(); reads.leave() }
+ reads.enter()
+ DispatchQueue.global().async { errBox.data = errPipe.fileHandleForReading.readDataToEndOfFile(); reads.leave() }
+
+ var timedOut = false
+ if finished.wait(timeout: .now() + timeout) == .timedOut {
+ timedOut = true
+ process.terminate()
+ if finished.wait(timeout: .now() + 1.0) == .timedOut {
+ kill(process.processIdentifier, SIGKILL)
+ finished.wait()
+ }
+ }
+ // The write ends close on exit, so these reads complete promptly.
+ reads.wait()
+
+ return ProcessOutput(
+ exitCode: process.terminationStatus,
+ stdout: String(data: outBox.data, encoding: .utf8) ?? "",
+ stderr: String(data: errBox.data, encoding: .utf8) ?? "",
+ timedOut: timedOut
+ )
+ }
+}
diff --git a/apps/Donkey/Sources/DonkeyRuntime/MediaCutPlanner.swift b/apps/Donkey/Sources/DonkeyRuntime/MediaCutPlanner.swift
new file mode 100644
index 00000000..0aceab68
--- /dev/null
+++ b/apps/Donkey/Sources/DonkeyRuntime/MediaCutPlanner.swift
@@ -0,0 +1,233 @@
+import Foundation
+
+/// A half-open time span `[start, end)` in seconds.
+public struct MediaTimeSpan: Equatable, Sendable {
+ public var start: Double
+ public var end: Double
+
+ public init(start: Double, end: Double) {
+ self.start = start
+ self.end = end
+ }
+
+ public var length: Double { max(0, end - start) }
+}
+
+/// Deterministic span math for cutting filler words and silence out of a media file and rejoining the
+/// kept parts — the engine Descript / auto-editor implement in code rather than leaving to a model.
+///
+/// Given the spans to REMOVE and the file's duration it computes the exact spans to KEEP and the ffmpeg
+/// filtergraph that stitches them back together, frame-accurate with audio and video in lockstep. Every
+/// function here is pure: no ffmpeg, no IO, no clock, no randomness, so the same inputs always produce
+/// the same cut. The IO (running ffmpeg/ffprobe) lives in `MediaCutEngine`; this is the part that has to
+/// be exactly right, and it is unit-tested directly.
+public enum MediaCutPlanner {
+ /// Tunables, with defaults grounded in how auto-editor / Descript behave: a small outward pad on each
+ /// filler so its trailing breath goes too, a natural pause left at each end of a removed silence so
+ /// speech doesn't sound clipped, and floors that keep the edit from making cuts too small to be worth
+ /// the seam.
+ public struct Parameters: Equatable, Sendable {
+ /// Expand each filler span outward by this much (seconds) so the word's edges/breath are removed.
+ public var fillerPadSec: Double
+ /// Leave this much silence (seconds) at each end of a removed silence, so the cut sounds natural.
+ public var keepPauseSec: Double
+ /// Merge two removals whose gap is at most this (seconds) into one — avoids a pointless micro-keep.
+ public var mergeGapSec: Double
+ /// Ignore a removal shorter than this (seconds): a cut this small is more jarring than the content.
+ public var minRemovalSec: Double
+ /// Drop a kept sliver shorter than this (seconds) rather than emit a frame or two of footage.
+ public var minKeepSec: Double
+
+ public init(
+ fillerPadSec: Double = 0.03,
+ keepPauseSec: Double = 0.15,
+ mergeGapSec: Double = 0.04,
+ minRemovalSec: Double = 0.05,
+ minKeepSec: Double = 0.02
+ ) {
+ self.fillerPadSec = max(0, fillerPadSec)
+ self.keepPauseSec = max(0, keepPauseSec)
+ self.mergeGapSec = max(0, mergeGapSec)
+ self.minRemovalSec = max(0, minRemovalSec)
+ self.minKeepSec = max(0, minKeepSec)
+ }
+ }
+
+ /// The default unambiguous filler lexicon. Words like "like" / "you know" are deliberately absent:
+ /// they are filler only sometimes, so removing them is a judgment call the caller passes as explicit
+ /// spans, not a blanket lexicon match.
+ public static let defaultFillerLexicon: Set<String> = ["um", "uh", "uhm", "umm", "erm", "er", "ah", "hmm", "mhm", "mm"]
+
+ // MARK: - Building removal spans from each source
+
+ /// Parse ffmpeg `silencedetect` output (it logs to stderr) into the spans to remove, each shrunk by
+ /// `keepPauseSec` at both ends so a natural pause survives the cut. A `silence_start` with no matching
+ /// `silence_end` (silence running to EOF) yields an open end (`+inf`); `keepSegments` clamps it to the
+ /// real duration.
+ public static func silenceSpans(fromSilenceDetect text: String, keepPauseSec: Double) -> [MediaTimeSpan] {
+ var starts: [Double] = []
+ var ends: [Double] = []
+ for line in text.split(whereSeparator: { $0 == "\n" || $0 == "\r" }) {
+ if let value = number(after: "silence_start:", in: line) {
+ starts.append(value)
+ }
+ // `silence_end: 19.43 | silence_duration: 0.9` — take the value right after the key.
+ if let value = number(after: "silence_end:", in: line) {
+ ends.append(value)
+ }
+ }
+ let pause = max(0, keepPauseSec)
+ var spans: [MediaTimeSpan] = []
+ for (index, start) in starts.enumerated() {
+ let rawEnd = index < ends.count ? ends[index] : Double.greatestFiniteMagnitude
+ let shrunkStart = start + pause
+ let shrunkEnd = rawEnd == Double.greatestFiniteMagnitude ? rawEnd : rawEnd - pause
+ if shrunkEnd > shrunkStart {
+ spans.append(MediaTimeSpan(start: shrunkStart, end: shrunkEnd))
+ }
+ }
+ return spans
+ }
+
+ /// Parse a transcript JSON (the `{ "words": [{ "text", "start", "end" }] }` shape `transcribe`
+ /// writes) into the spans for every word whose normalized text is in `lexicon`, each padded outward by
+ /// `padSec`. Times are in seconds. Malformed JSON yields no spans.
+ public static func fillerSpans(fromTranscriptJSON data: Data, lexicon: Set<String>, padSec: Double) -> [MediaTimeSpan] {
+ struct Word: Decodable { var text: String; var start: Double; var end: Double }
+ struct Transcript: Decodable { var words: [Word] }
+ guard let transcript = try? JSONDecoder().decode(Transcript.self, from: data) else { return [] }
+ let pad = max(0, padSec)
+ let normalizedLexicon = Set(lexicon.map { normalize($0) })
+ return transcript.words.compactMap { word in
+ guard normalizedLexicon.contains(normalize(word.text)), word.end > word.start else { return nil }
+ return MediaTimeSpan(start: word.start - pad, end: word.end + pad)
+ }
+ }
+
+ /// Parse an explicit removal list, `"1.2-3.4, 5-6.0"` (seconds), into spans. Whitespace and a trailing
+ /// `s` unit are tolerated; malformed entries are skipped. Used for caller-judged removals (a discourse
+ /// "like", a flubbed take) that no lexicon should decide.
+ public static func explicitSpans(fromList list: String) -> [MediaTimeSpan] {
+ list.split(whereSeparator: { $0 == "," || $0 == "\n" || $0 == ";" }).compactMap { piece in
+ let parts = piece.split(separator: "-", maxSplits: 1).map {
+ $0.trimmingCharacters(in: CharacterSet(charactersIn: " \t s"))
+ }
+ guard parts.count == 2, let start = Double(parts[0]), let end = Double(parts[1]), end > start else {
+ return nil
+ }
+ return MediaTimeSpan(start: start, end: end)
+ }
+ }
+
+ // MARK: - The core: removals -> kept segments
+
+ /// Turn the spans to remove into the spans to KEEP across `[0, duration]`. Clamps to the real
+ /// duration, drops removals shorter than `minRemovalSec`, merges removals within `mergeGapSec`,
+ /// inverts to the gaps between them, and drops kept slivers shorter than `minKeepSec`. The result is
+ /// the ordered, non-overlapping footage to stitch back together. With no removals it is the whole
+ /// file; with removals covering everything it is empty.
+ public static func keepSegments(
+ removing removals: [MediaTimeSpan],
+ duration: Double,
+ parameters: Parameters = Parameters()
+ ) -> [MediaTimeSpan] {
+ guard duration > 0 else { return [] }
+
+ let cleaned = removals
+ .map { MediaTimeSpan(start: clamp($0.start, 0, duration), end: clamp($0.end, 0, duration)) }
+ .filter { $0.length >= parameters.minRemovalSec }
+ .sorted { $0.start < $1.start }
+
+ var merged: [MediaTimeSpan] = []
+ for span in cleaned {
+ if var last = merged.last, span.start <= last.end + parameters.mergeGapSec {
+ last.end = max(last.end, span.end)
+ merged[merged.count - 1] = last
+ } else {
+ merged.append(span)
+ }
+ }
+
+ var keeps: [MediaTimeSpan] = []
+ var cursor = 0.0
+ for removal in merged {
+ // A removal at the cursor (e.g. one starting at t=0) leaves no lead segment — never emit a
+ // zero-length keep, which would feed ffmpeg an empty trim.
+ let lead = removal.start - cursor
+ if lead > 0, lead >= parameters.minKeepSec {
+ keeps.append(MediaTimeSpan(start: cursor, end: removal.start))
+ }
+ cursor = max(cursor, removal.end)
+ }
+ let tail = duration - cursor
+ if tail > 0, tail >= parameters.minKeepSec {
+ keeps.append(MediaTimeSpan(start: cursor, end: duration))
+ }
+ return keeps
+ }
+
+ // MARK: - Rendering the kept segments
+
+ /// The ffmpeg `filter_complex` that trims each kept span and concatenates them back into one stream,
+ /// re-stamping timestamps so there are no gaps. `trim`/`atrim` cut on exact frame/sample boundaries
+ /// and the same span list drives both, so video and audio stay in lockstep. Returns `""` when there is
+ /// nothing to keep or neither stream is present.
+ public static func filterGraph(keeping keeps: [MediaTimeSpan], hasVideo: Bool, hasAudio: Bool) -> String {
+ guard !keeps.isEmpty, hasVideo || hasAudio else { return "" }
+ var lines: [String] = []
+ var concatInputs = ""
+ for (index, keep) in keeps.enumerated() {
+ let start = format(keep.start)
+ let end = format(keep.end)
+ if hasVideo {
+ lines.append("[0:v]trim=start=\(start):end=\(end),setpts=PTS-STARTPTS[v\(index)]")
+ concatInputs += "[v\(index)]"
+ }
+ if hasAudio {
+ lines.append("[0:a]atrim=start=\(start):end=\(end),asetpts=PTS-STARTPTS[a\(index)]")
+ concatInputs += "[a\(index)]"
+ }
+ }
+ let videoFlag = hasVideo ? 1 : 0
+ let audioFlag = hasAudio ? 1 : 0
+ var outputs = ""
+ if hasVideo { outputs += "[v]" }
+ if hasAudio { outputs += "[a]" }
+ lines.append("\(concatInputs)concat=n=\(keeps.count):v=\(videoFlag):a=\(audioFlag)\(outputs)")
+ return lines.joined(separator: ";\n")
+ }
+
+ // MARK: - Helpers
+
+ private static func clamp(_ value: Double, _ lower: Double, _ upper: Double) -> Double {
+ min(max(value, lower), upper)
+ }
+
+ /// The first decimal number appearing after `key` in `line`, or nil. Tolerates the bracketed
+ /// `[silencedetect @ 0x..]` prefix and a trailing `| silence_duration: ..` on the same line.
+ private static func number(after key: String, in line: Substring) -> Double? {
+ guard let range = line.range(of: key) else { return nil }
+ let rest = line[range.upperBound...]
+ var token = ""
+ for character in rest {
+ if character == " " || character == "\t" { if token.isEmpty { continue } else { break } }
+ if character.isNumber || character == "." || character == "-" || character == "+" {
+ token.append(character)
+ } else if !token.isEmpty {
+ break
+ }
+ }
+ return Double(token)
+ }
+
+ /// Lowercase and strip surrounding punctuation so `"Um,"` matches the lexicon entry `"um"`.
+ private static func normalize(_ text: String) -> String {
+ text.lowercased().trimmingCharacters(in: CharacterSet.alphanumerics.inverted)
+ }
+
+ /// Fixed 3-decimal seconds (millisecond precision) so the filtergraph is deterministic and never uses
+ /// scientific notation for a large timestamp.
+ private static func format(_ value: Double) -> String {
+ String(format: "%.3f", value)
+ }
+}
diff --git a/apps/Donkey/Sources/DonkeyRuntime/ReframePlanner.swift b/apps/Donkey/Sources/DonkeyRuntime/ReframePlanner.swift
new file mode 100644
index 00000000..09d50ba8
--- /dev/null
+++ b/apps/Donkey/Sources/DonkeyRuntime/ReframePlanner.swift
@@ -0,0 +1,222 @@
+// ReframePlanner — the pure decision core of the `reframe` tool, with no AVFoundation/Vision/CoreImage
+// dependency so it is deterministic and unit-testable. Given per-frame face detections, audio energy,
+// and scene-cut flags, it links faces into tracks, decides the active speaker each frame, and produces
+// the crop path. The `reframe` CLI (tools/reframe/main.swift) does the Vision detection, audio read, and
+// render around this; both compile this same file, so the algorithm under test is the algorithm that ships.
+//
+// The active-speaker signal is the standard audio-visual one: the talking face is the tracked face whose
+// mouth moves while audio is voiced. A face that never moves its mouth is excluded; audio↔lip sync
+// correlation breaks close calls; hysteresis + immediate-handoff-on-silence keep the crop from flickering.
+// (A trained model such as LR-ASD can replace `activeSpeaker` as a drop-in scorer behind this interface.)
+
+import Foundation
+
+public struct ReframeFaceSample: Sendable, Equatable {
+ public var cx: Double // face-center x in display pixels (0 = left)
+ public var cy: Double // face-center y in display pixels (0 = top)
+ public var w: Double // face width in display pixels
+ public var h: Double // face height in display pixels
+ public var openness: Double // inner-lip vertical aperture in face-box units (open mouth -> larger)
+ public init(cx: Double, cy: Double, w: Double, h: Double, openness: Double) {
+ self.cx = cx; self.cy = cy; self.w = w; self.h = h; self.openness = openness
+ }
+}
+
+public struct ReframePlan: Sendable {
+ public var cropX: [Double] // left edge of the crop window per bin, clamped to [0, dispW-cropW]
+ public var activeTrack: [Int] // chosen speaker track id per bin (-1 = none)
+ public var hardCut: [Bool] // per bin: cut instantly rather than pan into this bin
+ public var trackCount: Int
+}
+
+public struct ReframePlanner: Sendable {
+ public var dispW: Double
+ public var dispH: Double
+ public var cropW: Double
+ public var sampleFPS: Double
+
+ public init(dispW: Double, dispH: Double, cropW: Double, sampleFPS: Double) {
+ self.dispW = dispW; self.dispH = dispH; self.cropW = cropW; self.sampleFPS = sampleFPS
+ }
+
+ struct Track { var id: Int; var lastBin: Int; var samples: [Int: ReframeFaceSample] }
+
+ /// `detections[bin]` is the faces found in that sampled frame; `energy[bin]` the audio RMS; `sceneCut[bin]`
+ /// a hard scene change. All three arrays are bin-aligned and the same length (the bin count).
+ public func plan(detections: [[ReframeFaceSample]], energy: [Double], sceneCut: [Bool]) -> ReframePlan {
+ let nBins = detections.count
+ guard nBins > 0 else { return ReframePlan(cropX: [], activeTrack: [], hardCut: [], trackCount: 0) }
+ func binTime(_ i: Int) -> Double { (Double(i) + 0.5) / sampleFPS }
+
+ // --- link detections into per-person tracks (greedy nearest centroid) ---
+ var tracks: [Track] = []
+ var nextID = 0
+ for i in 0..<nBins {
+ for det in detections[i] {
+ var best = -1; var bestDist = Double.greatestFiniteMagnitude
+ for idx in tracks.indices {
+ let tr = tracks[idx]
+ guard binTime(i) - binTime(tr.lastBin) <= 0.5 else { continue }
+ if let last = tr.samples[tr.lastBin] {
+ let d = hypot(det.cx - last.cx, det.cy - last.cy)
+ if d < bestDist && d < max(det.w, 80) * 1.2 { bestDist = d; best = idx }
+ }
+ }
+ if best >= 0 { tracks[best].samples[i] = det; tracks[best].lastBin = i }
+ else { tracks.append(Track(id: nextID, lastBin: i, samples: [i: det])); nextID += 1 }
+ }
+ }
+ tracks = tracks.filter { $0.samples.count >= 2 }
+
+ // --- voiced gate ---
+ let peakE = energy.max() ?? 0
+ let voicedThresh = max(1e-4, peakE * 0.12)
+ func voiced(_ i: Int) -> Bool { i >= 0 && i < energy.count && energy[i] > voicedThresh }
+
+ // --- per-track smoothed openness, mouth-activity envelope, sync correlation ---
+ func opennessSmoothed(_ tr: Track) -> [Double?] {
+ var s = [Double?](repeating: nil, count: nBins)
+ for (bin, fs) in tr.samples { s[bin] = fs.openness }
+ let known = (0..<nBins).filter { s[$0] != nil }
+ guard known.count >= 2 else { return s }
+ for idx in 0..<(known.count - 1) {
+ let a = known[idx], b = known[idx + 1]
+ if b - a > 1 && b - a <= 4 {
+ let va = s[a]!, vb = s[b]!
+ for k in (a + 1)..<b { s[k] = va + (vb - va) * Double(k - a) / Double(b - a) }
+ }
+ }
+ var out = s
+ for k in 0..<nBins where s[k] != nil {
+ var acc = 0.0, c = 0.0
+ for d in -1...1 { let j = k + d; if j >= 0 && j < nBins, let v = s[j] { acc += v; c += 1 } }
+ out[k] = acc / c
+ }
+ return out
+ }
+ func activityEnv(_ op: [Double?]) -> [Double] {
+ var a = [Double](repeating: 0, count: nBins)
+ var last: Double? = nil
+ for i in 0..<nBins {
+ if let v = op[i] { if let l = last { a[i] = abs(v - l) }; last = v } else { last = nil }
+ }
+ let w = max(2, Int(sampleFPS * 0.25))
+ var e = a
+ for i in 0..<nBins {
+ let lo = max(0, i - w), hi = min(nBins - 1, i + w)
+ e[i] = (lo...hi).reduce(0.0) { $0 + a[$1] } / Double(hi - lo + 1)
+ }
+ return e
+ }
+ func corrLag(_ op: [Double?], center i: Int, win w: Int, maxLag: Int) -> Double {
+ var best = -2.0
+ for lag in -maxLag...maxLag {
+ var xs: [Double] = []; var ys: [Double] = []
+ for k in (i - w)...(i + w) {
+ let j = k + lag
+ guard k >= 0, k < nBins, j >= 0, j < nBins, let o = op[k] else { continue }
+ xs.append(o); ys.append(energy[j])
+ }
+ guard xs.count >= 5 else { continue }
+ let mx = xs.reduce(0, +) / Double(xs.count), my = ys.reduce(0, +) / Double(ys.count)
+ var num = 0.0, dx = 0.0, dy = 0.0
+ for t in 0..<xs.count { let a = xs[t] - mx, b = ys[t] - my; num += a * b; dx += a * a; dy += b * b }
+ if dx > 1e-9 && dy > 1e-9 { best = max(best, num / (dx.squareRoot() * dy.squareRoot())) }
+ }
+ return best
+ }
+ let trackOpenness = Dictionary(uniqueKeysWithValues: tracks.map { ($0.id, opennessSmoothed($0)) })
+ let trackActivity = Dictionary(uniqueKeysWithValues: tracks.map { ($0.id, activityEnv(trackOpenness[$0.id]!)) })
+ let allPositive = trackActivity.values.flatMap { $0 }.filter { $0 > 1e-6 }.sorted()
+ let noiseFloor = allPositive.isEmpty ? 1e-4 : max(1e-4, allPositive[Int(0.25 * Double(allPositive.count))])
+ let trackMaxAct = trackActivity.mapValues { $0.max() ?? 0 }
+ func capable(_ id: Int) -> Bool { (trackMaxAct[id] ?? 0) > noiseFloor * 2 }
+
+ // --- active speaker per bin ---
+ let win = max(6, Int(sampleFPS * 0.7))
+ let maxLag = max(2, Int(sampleFPS * 0.12))
+ let minDwell = max(1, Int(sampleFPS * 0.4))
+ var activeTrack = [Int](repeating: -1, count: nBins)
+ var lastActive = -1
+ var dwell = 0
+ func commit(_ i: Int, _ candidate: Int) {
+ if candidate == lastActive || lastActive < 0 || dwell >= minDwell {
+ activeTrack[i] = candidate; lastActive = candidate; dwell = 0
+ } else { activeTrack[i] = lastActive; dwell += 1 }
+ }
+ for i in 0..<nBins {
+ let present = tracks.filter { tr in (max(0, i - 2)...min(nBins - 1, i + 2)).contains { tr.samples[$0] != nil } }
+ if present.isEmpty || !voiced(i) { activeTrack[i] = lastActive; dwell += 1; continue }
+ let speakers = present.filter { capable($0.id) }
+ if speakers.isEmpty { activeTrack[i] = lastActive >= 0 ? lastActive : (present.first?.id ?? -1); dwell += 1; continue }
+ if speakers.count == 1 { commit(i, speakers[0].id); continue }
+ let scored = speakers.map { ($0.id, trackActivity[$0.id]![i]) }.sorted { $0.1 > $1.1 }
+ let best = scored[0]
+ let second = scored.count > 1 ? scored[1].1 : 0.0
+ var winner = best.0
+ if best.1 >= max(noiseFloor, second * 1.3) {
+ winner = best.0
+ } else if best.1 > noiseFloor {
+ winner = speakers.map { ($0.id, corrLag(trackOpenness[$0.id]!, center: i, win: win, maxLag: maxLag)) }
+ .max { $0.1 < $1.1 }!.0
+ } else {
+ activeTrack[i] = lastActive >= 0 ? lastActive : best.0; dwell += 1; continue
+ }
+ let curAct = lastActive >= 0 ? (trackActivity[lastActive]?[i] ?? 0) : 0
+ if lastActive < 0 || winner == lastActive || curAct < noiseFloor || dwell >= minDwell {
+ activeTrack[i] = winner; lastActive = winner; dwell = 0
+ } else { activeTrack[i] = lastActive; dwell += 1 }
+ }
+
+ // --- focus center -> crop path (with hard cuts and smoothing) ---
+ func trackCenter(_ id: Int, _ bin: Int) -> Double? {
+ guard let tr = tracks.first(where: { $0.id == id }) else { return nil }
+ for d in 0...win {
+ if let s = tr.samples[bin] { return s.cx }
+ if bin - d >= 0, let s = tr.samples[bin - d] { return s.cx }
+ if bin + d < nBins, let s = tr.samples[bin + d] { return s.cx }
+ }
+ return nil
+ }
+ var centerX = [Double](repeating: dispW / 2, count: nBins)
+ var lastCenter = dispW / 2
+ for i in 0..<nBins {
+ if activeTrack[i] >= 0, let c = trackCenter(activeTrack[i], i) { lastCenter = c }
+ else if let widest = tracks.compactMap({ $0.samples[i] }).max(by: { $0.w < $1.w }) { lastCenter = widest.cx }
+ centerX[i] = lastCenter
+ }
+ var cropX = centerX.map { min(max($0 - cropW / 2, 0), dispW - cropW) }
+
+ var hardCut = [Bool](repeating: false, count: nBins)
+ for i in 1..<nBins {
+ let switched = activeTrack[i] != activeTrack[i - 1] && activeTrack[i] >= 0 && activeTrack[i - 1] >= 0
+ let bigJump = abs(cropX[i] - cropX[i - 1]) > dispW * 0.18
+ if (switched && bigJump) || (i < sceneCut.count && sceneCut[i]) { hardCut[i] = true }
+ }
+
+ let maxVel = dispW * 0.9 / sampleFPS
+ func smoothRun(_ lo: Int, _ hi: Int) {
+ guard hi > lo else { return }
+ var tmp = Array(cropX[lo...hi])
+ for _ in 0..<2 {
+ var out = tmp
+ for k in tmp.indices {
+ let a = max(0, k - 2), b = min(tmp.count - 1, k + 2)
+ out[k] = (a...b).reduce(0.0) { $0 + tmp[$1] } / Double(b - a + 1)
+ }
+ tmp = out
+ }
+ for k in 1..<tmp.count {
+ let d = tmp[k] - tmp[k - 1]
+ if d > maxVel { tmp[k] = tmp[k - 1] + maxVel }
+ if d < -maxVel { tmp[k] = tmp[k - 1] - maxVel }
+ }
+ for (k, idx) in (lo...hi).enumerated() { cropX[idx] = min(max(tmp[k], 0), dispW - cropW) }
+ }
+ var runStart = 0
+ for i in 1..<nBins where hardCut[i] { smoothRun(runStart, i - 1); runStart = i }
+ smoothRun(runStart, nBins - 1)
+
+ return ReframePlan(cropX: cropX, activeTrack: activeTrack, hardCut: hardCut, trackCount: tracks.count)
+ }
+}
diff --git a/apps/Donkey/Sources/DonkeyRuntime/Resources/BuiltInSkills/media/SKILL.md b/apps/Donkey/Sources/DonkeyRuntime/Resources/BuiltInSkills/media/SKILL.md
index 4800974b..ad58580c 100644
--- a/apps/Donkey/Sources/DonkeyRuntime/Resources/BuiltInSkills/media/SKILL.md
+++ b/apps/Donkey/Sources/DonkeyRuntime/Resources/BuiltInSkills/media/SKILL.md
@@ -1,10 +1,10 @@
# Media
id: media
-description: Expert audio and video — download from a URL with yt-dlp, transcode/trim/extract/grab frames with ffmpeg, and transcribe, subtitle, or translate with the model.
-tags: video, audio, media, download, convert, youtube, subtitles, transcribe
-keywords: video, audio, download, youtube, vimeo, mp4, mp3, convert, trim, clip, extract audio, transcode, frame, subtitle, subtitles, caption, captions, transcribe, transcript, translate, srt, vtt
-tools: shell_exec, llm.generate, files.write
+description: Expert audio and video — download from a URL with yt-dlp, transcode/trim/extract/grab frames with ffmpeg, transcribe/subtitle/translate, cut filler words or silence with word-level timing, and reframe landscape to vertical 9:16 that tracks the active speaker.
+tags: video, audio, media, download, convert, youtube, subtitles, transcribe, edit, reframe, vertical
+keywords: video, audio, download, youtube, vimeo, mp4, mp3, convert, trim, clip, extract audio, transcode, frame, subtitle, subtitles, caption, captions, transcribe, transcript, translate, srt, vtt, filler words, remove silence, um, uh, jump cut, tighten, reframe, vertical, 9:16, portrait, tiktok, reels, shorts, crop to vertical, active speaker, follow speaker
+tools: shell_exec, transcribe, llm.generate, files.write
`yt-dlp` and `ffmpeg`/`ffprobe` are bundled, signed, and on the PATH, so use them
by bare name. They are first-party capability tools: downloading from the user's
@@ -36,6 +36,10 @@ case say the media tools are still installing and stop. Do not try to install an
- One frame / thumbnail: `ffmpeg -ss 5 -i in.mp4 -frames:v 1 thumb.png`. Frames every second: `ffmpeg -i in.mp4 -vf fps=1 frame_%03d.png`.
- ffmpeg refuses to overwrite by default and prompts; pass `-y` to overwrite or choose a new output name.
+## Two ways to transcribe — pick by the timing you need
+- **`transcribe` (on-device, word-level).** Runs Apple's local speech engine on an audio file and writes a JSON file holding the plain `text` plus `words` — every word with a `start`/`end` in seconds, accurate to a fraction of a second. Private, no credits. Use it whenever you need to know *exactly when* words are spoken: cutting filler words or silence, finding a quoted moment, chaptering. Hand it compact audio (extract it from a video first); if it reports no transcript, extract audio and retry.
+- **`llm.generate` SRT (the model).** Sentence-level cues with approximate timing — fine for subtitles, not precise enough to cut individual words. Use it for translation or when you just need readable captions.
+
## Subtitles & transcription
Get the subtitle text, then apply it. Prefer the cheapest source that gives correct timing.
@@ -54,6 +58,32 @@ Get the subtitle text, then apply it. Prefer the cheapest source that gives corr
- Soft, toggleable track (the reliable fallback, and fine for an archive copy): `ffmpeg -i clip.mp4 -i subs.srt -c copy -c:s mov_text out.mp4`. This muxes the translation into the file as a real subtitle stream with no libass and no re-encode, so it works even when burn-in can't.
- Model timestamps are approximate (good enough for subtitles); always extract audio before transcribing, and chunk long files.
+## Cut filler words or silence
+Use the **`media.cut`** tool — a deterministic, frame-accurate editor. It does the span math and the ffmpeg render itself; you only say what to remove. Do NOT hand-build select/trim/concat ffmpeg for this.
+
+- **Filler words**: run `transcribe` on the audio first, then `media.cut inputPath=clip.mp4 removeFillers=true transcriptPath=<the transcribe JSON>` — it cuts um/uh/er with the right padding.
+- **Silence / dead air**: `media.cut inputPath=clip.mp4 removeSilence=true`.
+- **Both at once**: pass `removeFillers=true removeSilence=true` together (still give `transcriptPath`).
+- **A specific bad take, or a discourse "like" the lexicon won't catch**: pass `removeSpans="12.4-15.0, 88.0-90.5"` (seconds).
+
+It writes `<name>-tightened.<ext>` next to the source (override with `outputPath`) and reports how much it removed. Finding nothing to cut is a clean result, not an error. Verify the output as below.
+
+## Reframe landscape to vertical (reframe)
+`reframe` is bundled alongside ffmpeg. It turns a landscape clip into vertical 9:16 that **follows
+whoever is talking** — face tracking plus on-device active-speaker detection — instead of ffmpeg's
+fixed-rectangle `crop`. It is fully local (Apple Vision + AVFoundation, no model file, no network)
+and keeps the original audio. Use it for any "make this vertical / portrait / for TikTok/Reels/Shorts"
+ask on real footage; keep ffmpeg `crop` only when the user wants a fixed, non-tracking crop.
+- `reframe --input in.mp4 --output out.mp4 --aspect 9:16 --height 1920` → prints a JSON summary
+ (`out`, `width`, `height`, `facesTracked`, `speakersFollowed`, `cuts`). `--aspect` and `--height`
+ are optional (default 9:16 at 1920 tall). It analyzes the whole clip, so pass a generous
+ `timeoutSeconds` (a minute or so for a long clip).
+- It picks the speaking face when several are in frame (a still listener is ignored), smooth-pans to
+ follow them, and cuts on scene changes. With no faces it falls back to a centered crop.
+- It does **not** add captions. For a captioned vertical clip, reframe first, then burn subtitles
+ (above) onto the vertical file so the text is sized to the 9:16 frame. For the full
+ podcast/long-video → short-form pipeline, see the `shorts` skill.
+
## Verify
- Confirm the output exists and is real media: `ffprobe -v error -show_entries format=duration:format_name -of default=nw=1 out.mp4`.
- A zero-byte file or an ffprobe error means the operation failed — report it, don't claim success.
\ No newline at end of file
diff --git a/apps/Donkey/Sources/DonkeyRuntime/Resources/BuiltInSkills/shorts/SKILL.md b/apps/Donkey/Sources/DonkeyRuntime/Resources/BuiltInSkills/shorts/SKILL.md
new file mode 100644
index 00000000..e27312c2
--- /dev/null
+++ b/apps/Donkey/Sources/DonkeyRuntime/Resources/BuiltInSkills/shorts/SKILL.md
@@ -0,0 +1,36 @@
+# Shorts
+
+id: shorts
+description: Turn a long video or podcast into vertical short-form clips for TikTok, Reels, and Shorts — pick the strong moments, crop to 9:16 tracking whoever is speaking, and burn in captions.
+tags: shorts, tiktok, reels, vertical, clips, highlights, podcast, captions, social
+keywords: tiktok, reels, shorts, vertical video, 9:16, portrait, clip, clips, highlight, highlights, snippet, snippets, podcast clip, social media clip, captions, subtitles, reframe, repurpose, turn into clips, best moments
+
+Turn a long recording into short vertical clips ready to post. This skill orchestrates the
+pieces — the actual download/transcribe/cut/caption commands live in the `media` skill, and the
+landscape→vertical speaker-tracking crop is the bundled `reframe` tool. Reach for it on asks like
+"make TikToks from this podcast", "cut this interview into Reels", "vertical clips with subtitles".
+
+## The pipeline
+1. **Get the source.** A local file is ready to use. A URL: download it with `yt-dlp` (see `media`).
+ For a long source, also pull the transcript/captions — reuse the video's own captions when it has
+ them (free), otherwise transcribe (see `media`). You need text with timestamps to choose moments.
+2. **Pick the moments.** Read the timestamped transcript and choose self-contained spans that land —
+ a complete thought with a hook and a payoff, usually 15–60s. Don't cut mid-sentence. Propose the
+ moments (with timestamps) and, when the user hasn't said how many, confirm how many clips they want.
+3. **Cut each span.** Trim it out with `ffmpeg` (see `media`). Transcribe the *clip* (not the whole
+ source) so caption timestamps start at zero and line up.
+4. **Reframe to vertical.** Run `reframe --input clip.mp4 --output clip_v.mp4 --aspect 9:16` — it
+ crops to 9:16 and follows whoever is talking (a still listener is ignored, and it cuts on scene
+ changes). Pass a generous `timeoutSeconds`. This is the step that makes a landscape two-person
+ podcast watchable on a phone.
+5. **Caption it.** Burn the clip's subtitles onto the vertical file (see `media`), so the text is
+ sized to the 9:16 frame. Burned-in captions are what social players expect.
+
+Output one `*_v.mp4` per moment, captioned, in the user's Downloads (or a folder they name).
+
+## Keep in mind
+- Reframe first, caption second — captions burned before reframing would get cropped or shrunk.
+- A talking-head or multi-person conversation is the sweet spot. Heavy B-roll or fast cutting has no
+ single speaker to follow; `reframe` falls back to a centered crop, so a fixed `ffmpeg` crop is just
+ as good there — say so rather than implying it tracked a subject.
+- Picking the moment is judgment, not a formula: favor a strong opening line and a clear payoff.
diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/Fixtures/HarnessEval/remove-filler-words/analysis.txt b/apps/Donkey/Tests/DonkeyRuntimeTests/Fixtures/HarnessEval/remove-filler-words/analysis.txt
new file mode 100644
index 00000000..6310ed13
--- /dev/null
+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/Fixtures/HarnessEval/remove-filler-words/analysis.txt
@@ -0,0 +1,7 @@
+Total words: 12
+Filler words (text start end): um 3.10 3.42 | uh 7.80 8.05
+Silences over 0.5s (start end): 18.51 19.43 | 95.20 96.88
+Removal spans, fillers padded 0.05s (start end): 3.05 3.47 | 7.75 8.10
+Silence removal keeping 0.15s floor (start end): 18.59 19.36 | 95.28 96.81
+All removals merged (start end): 3.05 3.47 | 7.75 8.10 | 18.59 19.36 | 95.28 96.81
+Keep spans over [0, 664.0] (start end): 0 3.05 | 3.47 7.75 | 8.10 18.59 | 19.36 95.28 | 96.81 664.0
diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/Fixtures/HarnessEval/remove-filler-words/prompt.txt b/apps/Donkey/Tests/DonkeyRuntimeTests/Fixtures/HarnessEval/remove-filler-words/prompt.txt
new file mode 100644
index 00000000..bfb15b10
--- /dev/null
+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/Fixtures/HarnessEval/remove-filler-words/prompt.txt
@@ -0,0 +1 @@
+remove the filler words and the long silences from talk.mov and save a tightened cut
\ No newline at end of file
diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/Fixtures/HarnessEval/remove-filler-words/scenario.json b/apps/Donkey/Tests/DonkeyRuntimeTests/Fixtures/HarnessEval/remove-filler-words/scenario.json
new file mode 100644
index 00000000..275eb979
--- /dev/null
+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/Fixtures/HarnessEval/remove-filler-words/scenario.json
@@ -0,0 +1,20 @@
+{
+ "frontmostApp": "Finder",
+ "maxSteps": 18,
+ "disk": [
+ { "path": "talk.mov", "describe": "QuickTime movie, 11 min, 1080p with audio — a talking-head screen recording." }
+ ],
+ "responses": [
+ { "tool": "shell_exec", "contains": ["ffmpeg", "-vn"], "summary": "size=N/A time=00:11:04 — wrote talk.m4a (mono, 64kbps).", "produces": ["talk.m4a"] },
+ { "tool": "transcribe", "summary": "Transcribed on-device (apple-speechanalyzer) → talk-words.json with per-word start/end timings.", "produces": ["talk-words.json"] },
+ { "tool": "shell_exec", "contains": ["talk-words.json"], "summaryFile": "words.json" },
+ { "tool": "media.cut", "summary": "Cut 6 span(s), removed 12.4s — 664.0s → 651.6s → talk-tightened.mov", "produces": ["talk-tightened.mov"] },
+ { "tool": "shell_exec", "contains": ["ffprobe", "talk-tightened"], "summary": "duration=651.640000\nformat_name=mov,mp4,m4a,3gp,3g2,mj2" }
+ ],
+ "expect": {
+ "turnKind": "act",
+ "skills": ["media"],
+ "used": ["transcribe", "media.cut"],
+ "completed": true
+ }
+}
diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/Fixtures/HarnessEval/remove-filler-words/words.json b/apps/Donkey/Tests/DonkeyRuntimeTests/Fixtures/HarnessEval/remove-filler-words/words.json
new file mode 100644
index 00000000..8eb43b13
--- /dev/null
+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/Fixtures/HarnessEval/remove-filler-words/words.json
@@ -0,0 +1,20 @@
+{
+ "text": "so um the main idea uh here is really simple you know",
+ "locale": "en-US",
+ "backend": "apple-speechanalyzer",
+ "wordCount": 12,
+ "words": [
+ {"text": "so", "start": 2.80, "end": 3.10},
+ {"text": "um", "start": 3.10, "end": 3.42},
+ {"text": "the", "start": 3.55, "end": 3.74},
+ {"text": "main", "start": 3.74, "end": 4.08},
+ {"text": "idea", "start": 4.08, "end": 4.50},
+ {"text": "uh", "start": 7.80, "end": 8.05},
+ {"text": "here", "start": 8.05, "end": 8.36},
+ {"text": "is", "start": 8.36, "end": 8.55},
+ {"text": "really", "start": 8.55, "end": 9.00},
+ {"text": "simple", "start": 9.00, "end": 9.60},
+ {"text": "you", "start": 15.02, "end": 15.18},
+ {"text": "know", "start": 15.18, "end": 15.48}
+ ]
+}
diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/MediaCutPlannerTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/MediaCutPlannerTests.swift
new file mode 100644
index 00000000..201a3945
--- /dev/null
+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/MediaCutPlannerTests.swift
@@ -0,0 +1,210 @@
+import DonkeyRuntime
+import Foundation
+import Testing
+
+/// Deterministic math for the cut engine — the part that must be exactly right, tested directly with no
+/// ffmpeg and no model. Covers the inversion (removals → keeps), every floor/merge/clamp rule, parsing
+/// silencedetect output and a transcript into removal spans, and the exact ffmpeg filtergraph.
+@Suite
+struct MediaCutPlannerTests {
+ // Loose float compare for the span arithmetic.
+ private func near(_ a: Double, _ b: Double, _ tol: Double = 1e-6) -> Bool { abs(a - b) <= tol }
+
+ private func spans(_ pairs: [(Double, Double)]) -> [MediaTimeSpan] {
+ pairs.map { MediaTimeSpan(start: $0.0, end: $0.1) }
+ }
+
+ // No floors/merge, so this is pure inversion.
+ private let exact = MediaCutPlanner.Parameters(
+ fillerPadSec: 0, keepPauseSec: 0, mergeGapSec: 0, minRemovalSec: 0, minKeepSec: 0
+ )
+
+ private func expectKeeps(_ keeps: [MediaTimeSpan], _ expected: [(Double, Double)], _ label: String) {
+ #expect(keeps.count == expected.count, "[\(label)] count: got \(keeps.map { ($0.start, $0.end) })")
+ for (index, pair) in expected.enumerated() where index < keeps.count {
+ #expect(near(keeps[index].start, pair.0) && near(keeps[index].end, pair.1),
+ "[\(label)] span \(index): got (\(keeps[index].start), \(keeps[index].end)), want \(pair)")
+ }
+ }
+
+ // MARK: keepSegments — inversion
+
+ @Test func singleMiddleRemoval() {
+ let keeps = MediaCutPlanner.keepSegments(removing: spans([(3, 4)]), duration: 10, parameters: exact)
+ expectKeeps(keeps, [(0, 3), (4, 10)], "middle")
+ }
+
+ @Test func noRemovalsKeepsWholeFile() {
+ let keeps = MediaCutPlanner.keepSegments(removing: [], duration: 10, parameters: exact)
+ expectKeeps(keeps, [(0, 10)], "none")
+ }
+
+ @Test func removalAtStart() {
+ let keeps = MediaCutPlanner.keepSegments(removing: spans([(0, 2)]), duration: 10, parameters: exact)
+ expectKeeps(keeps, [(2, 10)], "start")
+ }
+
+ @Test func removalAtEnd() {
+ let keeps = MediaCutPlanner.keepSegments(removing: spans([(8, 10)]), duration: 10, parameters: exact)
+ expectKeeps(keeps, [(0, 8)], "end")
+ }
+
+ @Test func removalCoveringEverythingLeavesNothing() {
+ let keeps = MediaCutPlanner.keepSegments(removing: spans([(0, 10)]), duration: 10, parameters: exact)
+ #expect(keeps.isEmpty)
+ }
+
+ @Test func overlappingRemovalsMerge() {
+ let keeps = MediaCutPlanner.keepSegments(removing: spans([(2, 5), (3, 6)]), duration: 10, parameters: exact)
+ expectKeeps(keeps, [(0, 2), (6, 10)], "overlap")
+ }
+
+ @Test func unsortedRemovalsHandled() {
+ let keeps = MediaCutPlanner.keepSegments(removing: spans([(8, 9), (2, 3)]), duration: 10, parameters: exact)
+ expectKeeps(keeps, [(0, 2), (3, 8), (9, 10)], "unsorted")
+ }
+
+ @Test func removalsClampedToDuration() {
+ let keeps = MediaCutPlanner.keepSegments(removing: spans([(8, 999)]), duration: 10, parameters: exact)
+ expectKeeps(keeps, [(0, 8)], "clamp")
+ }
+
+ // MARK: keepSegments — floors & merge
+
+ @Test func mergeWithinGap() {
+ let params = MediaCutPlanner.Parameters(keepPauseSec: 0, mergeGapSec: 0.04, minRemovalSec: 0, minKeepSec: 0)
+ // Gap between removals is 0.02 ≤ 0.04 → merged into one, so no micro-keep between them.
+ let keeps = MediaCutPlanner.keepSegments(removing: spans([(3, 4), (4.02, 5)]), duration: 10, parameters: params)
+ expectKeeps(keeps, [(0, 3), (5, 10)], "merge")
+ }
+
+ @Test func noMergeBeyondGap() {
+ let params = MediaCutPlanner.Parameters(keepPauseSec: 0, mergeGapSec: 0.04, minRemovalSec: 0, minKeepSec: 0)
+ // Gap 0.1 > 0.04 → kept apart, so the 0.1s sliver between survives.
+ let keeps = MediaCutPlanner.keepSegments(removing: spans([(3, 4), (4.1, 5)]), duration: 10, parameters: params)
+ expectKeeps(keeps, [(0, 3), (4, 4.1), (5, 10)], "nomerge")
+ }
+
+ @Test func removalShorterThanFloorIgnored() {
+ let params = MediaCutPlanner.Parameters(keepPauseSec: 0, mergeGapSec: 0, minRemovalSec: 0.05, minKeepSec: 0)
+ let keeps = MediaCutPlanner.keepSegments(removing: spans([(3, 3.03)]), duration: 10, parameters: params)
+ expectKeeps(keeps, [(0, 10)], "tinyRemoval")
+ }
+
+ @Test func keepSliverShorterThanFloorDropped() {
+ let params = MediaCutPlanner.Parameters(keepPauseSec: 0, mergeGapSec: 0, minRemovalSec: 0, minKeepSec: 0.02)
+ // [0,3] and [3.01,10] are both REMOVED, leaving only the 0.01s gap [3,3.01] which is below
+ // minKeep → dropped. Nothing survives.
+ let keeps = MediaCutPlanner.keepSegments(removing: spans([(0, 3), (3.01, 10)]), duration: 10, parameters: params)
+ #expect(keeps.isEmpty, "tinyKeep: got \(keeps.map { ($0.start, $0.end) })")
+ }
+
+ @Test func zeroDurationYieldsNothing() {
+ #expect(MediaCutPlanner.keepSegments(removing: spans([(0, 1)]), duration: 0, parameters: exact).isEmpty)
+ }
+
+ // MARK: silenceSpans
+
+ @Test func silenceSpansParsedAndShrunk() {
+ let text = """
+ [silencedetect @ 0x6000] silence_start: 18.512
+ [silencedetect @ 0x6000] silence_end: 19.430 | silence_duration: 0.918
+ [silencedetect @ 0x6000] silence_start: 95.204
+ [silencedetect @ 0x6000] silence_end: 96.880 | silence_duration: 1.676
+ """
+ let result = MediaCutPlanner.silenceSpans(fromSilenceDetect: text, keepPauseSec: 0.15)
+ #expect(result.count == 2)
+ #expect(near(result[0].start, 18.662) && near(result[0].end, 19.280))
+ #expect(near(result[1].start, 95.354) && near(result[1].end, 96.730))
+ }
+
+ @Test func silenceRunningToEndOfFileHasOpenEnd() {
+ let result = MediaCutPlanner.silenceSpans(fromSilenceDetect: "silence_start: 5.0", keepPauseSec: 0)
+ #expect(result.count == 1)
+ #expect(near(result[0].start, 5.0))
+ #expect(result[0].end == Double.greatestFiniteMagnitude)
+ }
+
+ @Test func silenceShorterThanTwicePauseDropped() {
+ // A 0.1s silence with a 0.15s pause each side would invert — it is dropped, not emitted backwards.
+ let text = "silence_start: 4.0\nsilence_end: 4.1"
+ #expect(MediaCutPlanner.silenceSpans(fromSilenceDetect: text, keepPauseSec: 0.15).isEmpty)
+ }
+
+ // MARK: fillerSpans
+
+ @Test func fillerSpansMatchLexiconCaseAndPunctuationInsensitive() {
+ let json = """
+ { "words": [
+ { "text": "so", "start": 2.8, "end": 3.1 },
+ { "text": "Um,", "start": 3.1, "end": 3.42 },
+ { "text": "uh", "start": 7.8, "end": 8.05 },
+ { "text": "idea", "start": 4.0, "end": 4.5 }
+ ] }
+ """
+ let result = MediaCutPlanner.fillerSpans(
+ fromTranscriptJSON: Data(json.utf8),
+ lexicon: MediaCutPlanner.defaultFillerLexicon,
+ padSec: 0.03
+ )
+ #expect(result.count == 2)
+ #expect(near(result[0].start, 3.07) && near(result[0].end, 3.45))
+ #expect(near(result[1].start, 7.77) && near(result[1].end, 8.08))
+ }
+
+ @Test func fillerSpansEmptyOnMalformedJSON() {
+ #expect(MediaCutPlanner.fillerSpans(fromTranscriptJSON: Data("not json".utf8), lexicon: ["um"], padSec: 0).isEmpty)
+ }
+
+ // MARK: explicitSpans
+
+ @Test func explicitSpansParsed() {
+ let result = MediaCutPlanner.explicitSpans(fromList: "1.2-3.4, 5-6.0")
+ #expect(result.count == 2)
+ #expect(near(result[0].start, 1.2) && near(result[0].end, 3.4))
+ #expect(near(result[1].start, 5.0) && near(result[1].end, 6.0))
+ }
+
+ @Test func explicitSpansToleratesUnitsAndSkipsGarbage() {
+ let result = MediaCutPlanner.explicitSpans(fromList: "3.0s-4.0s, nonsense, 8-7")
+ // "8-7" is end<=start and skipped; "nonsense" skipped; only the units span survives.
+ #expect(result.count == 1)
+ #expect(near(result[0].start, 3.0) && near(result[0].end, 4.0))
+ }
+
+ // MARK: filterGraph
+
+ @Test func filterGraphBothStreams() {
+ let graph = MediaCutPlanner.filterGraph(keeping: spans([(0, 3), (4, 10)]), hasVideo: true, hasAudio: true)
+ let expected = """
+ [0:v]trim=start=0.000:end=3.000,setpts=PTS-STARTPTS[v0];
+ [0:a]atrim=start=0.000:end=3.000,asetpts=PTS-STARTPTS[a0];
+ [0:v]trim=start=4.000:end=10.000,setpts=PTS-STARTPTS[v1];
+ [0:a]atrim=start=4.000:end=10.000,asetpts=PTS-STARTPTS[a1];
+ [v0][a0][v1][a1]concat=n=2:v=1:a=1[v][a]
+ """
+ #expect(graph == expected)
+ }
+
+ @Test func filterGraphVideoOnly() {
+ let graph = MediaCutPlanner.filterGraph(keeping: spans([(0, 3)]), hasVideo: true, hasAudio: false)
+ let expected = """
+ [0:v]trim=start=0.000:end=3.000,setpts=PTS-STARTPTS[v0];
+ [v0]concat=n=1:v=1:a=0[v]
+ """
+ #expect(graph == expected)
+ }
+
+ @Test func filterGraphAudioOnly() {
+ let graph = MediaCutPlanner.filterGraph(keeping: spans([(0, 3)]), hasVideo: false, hasAudio: true)
+ let expected = """
+ [0:a]atrim=start=0.000:end=3.000,asetpts=PTS-STARTPTS[a0];
+ [a0]concat=n=1:v=0:a=1[a]
+ """
+ #expect(graph == expected)
+ }
+
+ @Test func filterGraphEmptyWhenNothingKept() {
+ #expect(MediaCutPlanner.filterGraph(keeping: [], hasVideo: true, hasAudio: true).isEmpty)
+ }
+}
diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/ReframeBinaryIntegrationTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/ReframeBinaryIntegrationTests.swift
new file mode 100644
index 00000000..1ec40f2a
--- /dev/null
+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/ReframeBinaryIntegrationTests.swift
@@ -0,0 +1,73 @@
+import AVFoundation
+import Foundation
+import Testing
+
+// End-to-end test of the real `reframe` binary: it compiles the CLI (tools/reframe/main.swift +
+// ReframePlanner.swift, exactly as scripts/fetch-bundled-tools.sh does), runs it on a committed
+// video fixture, and verifies the PRODUCED vertical file with AVFoundation — real output, not a mock.
+//
+// Opt-in (it compiles Swift and exports video, ~15s): run with
+// DONKEY_REFRAME_E2E=1 swift test --filter ReframeBinaryIntegrationTests
+@Suite
+struct ReframeBinaryIntegrationTests {
+ static var enabled: Bool { ProcessInfo.processInfo.environment["DONKEY_REFRAME_E2E"] == "1" }
+
+ // .../apps/Donkey/Tests/DonkeyRuntimeTests/ThisFile.swift -> repo root is four levels up.
+ static func repoRoot() -> URL {
+ var url = URL(fileURLWithPath: #filePath).deletingLastPathComponent() // DonkeyRuntimeTests
+ for _ in 0..<4 { url = url.deletingLastPathComponent() } // Tests, Donkey, apps, root
+ return url
+ }
+
+ @discardableResult
+ static func run(_ tool: URL, _ args: [String]) -> (code: Int32, err: String) {
+ let p = Process()
+ p.executableURL = tool
+ p.arguments = args
+ let errPipe = Pipe()
+ p.standardError = errPipe
+ p.standardOutput = Pipe()
+ try? p.run()
+ p.waitUntilExit()
+ let err = String(data: errPipe.fileHandleForReading.readDataToEndOfFile(), encoding: .utf8) ?? ""
+ return (p.terminationStatus, err)
+ }
+
+ @Test(.enabled(if: ReframeBinaryIntegrationTests.enabled))
+ func producesAVerticalClipWithAudioFromARealVideo() async throws {
+ let root = Self.repoRoot()
+ let mainSwift = root.appendingPathComponent("tools/reframe/main.swift")
+ let plannerSwift = root.appendingPathComponent("apps/Donkey/Sources/DonkeyRuntime/ReframePlanner.swift")
+ let fixture = root.appendingPathComponent("apps/Donkey/Tests/DonkeyRuntimeTests/Fixtures/FunctionalEval/extract-audio/inputs/clip.mp4")
+ #expect(FileManager.default.fileExists(atPath: fixture.path), "fixture video missing")
+
+ let tmp = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent("reframe-e2e-\(getpid())")
+ try FileManager.default.createDirectory(at: tmp, withIntermediateDirectories: true)
+ defer { try? FileManager.default.removeItem(at: tmp) }
+ let binary = tmp.appendingPathComponent("reframe")
+ let outVideo = tmp.appendingPathComponent("out.mp4")
+
+ // Build the CLI exactly like the bundling script (two source files, swiftc -O).
+ let build = Self.run(URL(fileURLWithPath: "/usr/bin/xcrun"),
+ ["swiftc", "-O", mainSwift.path, plannerSwift.path, "-o", binary.path])
+ #expect(build.code == 0, "reframe build failed: \(build.err)")
+ #expect(FileManager.default.fileExists(atPath: binary.path), "reframe binary not produced")
+
+ // Run it on the real fixture (smaller height keeps the export quick).
+ let runResult = Self.run(binary, ["--input", fixture.path, "--output", outVideo.path, "--aspect", "9:16", "--height", "640"])
+ #expect(runResult.code == 0, "reframe run failed: \(runResult.err)")
+ #expect(FileManager.default.fileExists(atPath: outVideo.path), "output video not produced")
+
+ // Verify the PRODUCED file is a real vertical 9:16 video that kept its audio and duration.
+ let asset = AVURLAsset(url: outVideo)
+ let vTracks = try await asset.loadTracks(withMediaType: .video)
+ #expect(vTracks.count == 1)
+ let size = try await vTracks[0].load(.naturalSize)
+ #expect(Int(size.width) == 360 && Int(size.height) == 640, "expected 360x640, got \(size)")
+ let aTracks = try await asset.loadTracks(withMediaType: .audio)
+ #expect(aTracks.count == 1, "audio track was not retained")
+ let inDur = try await AVURLAsset(url: fixture).load(.duration).seconds
+ let outDur = try await asset.load(.duration).seconds
+ #expect(abs(outDur - inDur) < 0.3, "duration drift: in \(inDur) vs out \(outDur)")
+ }
+}
diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/ReframePlannerTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/ReframePlannerTests.swift
new file mode 100644
index 00000000..79d0cf01
--- /dev/null
+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/ReframePlannerTests.swift
@@ -0,0 +1,109 @@
+import DonkeyRuntime
+import Foundation
+import Testing
+
+// Deterministic unit tests for the reframe decision core. ReframePlanner is the exact algorithm the
+// bundled `reframe` CLI ships (the CLI compiles this same file), so these protect the real tracking,
+// active-speaker, and crop-path logic without needing video I/O or Vision.
+@Suite
+struct ReframePlannerTests {
+ // 1280x720 landscape -> 9:16 (cropW 405). Two people: left at x=320, right at x=960.
+ let dispW = 1280.0, dispH = 720.0, cropW = 405.0, fps = 24.0
+ let xLeft = 320.0, xRight = 960.0
+
+ func planner() -> ReframePlanner { ReframePlanner(dispW: dispW, dispH: dispH, cropW: cropW, sampleFPS: fps) }
+ func center(_ cropX: Double) -> Double { cropX + cropW / 2 }
+
+ // A talking mouth changes shape frame-to-frame (wide range, like speech); a listening mouth only
+ // micro-moves (as real faces do — a perfectly frozen face is unrealistic and degenerates the noise
+ // floor). Deterministic pseudo-random keeps it reproducible.
+ func openness(speaking: Bool, _ i: Int) -> Double {
+ guard speaking else { return 0.12 + 0.004 * sin(Double(i)) }
+ let r = Double((i &* 1_103_515_245 &+ 12_345) & 0x7FFF) / 32_767.0
+ return 0.05 + 0.40 * r
+ }
+ func face(x: Double, speaking: Bool, _ i: Int) -> ReframeFaceSample {
+ ReframeFaceSample(cx: x, cy: 360, w: 160, h: 200, openness: openness(speaking: speaking, i))
+ }
+
+ func twoPerson(nBins: Int, leftSpeaking: (Int) -> Bool, rightSpeaking: (Int) -> Bool)
+ -> (dets: [[ReframeFaceSample]], energy: [Double]) {
+ var dets: [[ReframeFaceSample]] = []
+ var energy: [Double] = []
+ for i in 0..<nBins {
+ dets.append([face(x: xLeft, speaking: leftSpeaking(i), i), face(x: xRight, speaking: rightSpeaking(i), i)])
+ energy.append(1.0) // voiced throughout
+ }
+ return (dets, energy)
+ }
+
+ // The crop follows the talking face, not the still listener.
+ @Test
+ func cropsToTheTalkingFace() {
+ let n = 48
+ let (dets, energy) = twoPerson(nBins: n, leftSpeaking: { _ in true }, rightSpeaking: { _ in false })
+ let plan = planner().plan(detections: dets, energy: energy, sceneCut: Array(repeating: false, count: n))
+ #expect(plan.trackCount == 2)
+ let avg = (12..<n).map { center(plan.cropX[$0]) }.reduce(0, +) / Double(n - 12)
+ #expect(avg < 500) // left speaker is ~320; frame middle is 640
+ }
+
+ // When the speaker changes, the crop hands off to the new speaker.
+ @Test
+ func handsOffWhenTheSpeakerChanges() {
+ let n = 96
+ let (dets, energy) = twoPerson(nBins: n, leftSpeaking: { $0 < n / 2 }, rightSpeaking: { $0 >= n / 2 })
+ let plan = planner().plan(detections: dets, energy: energy, sceneCut: Array(repeating: false, count: n))
+ let first = (12..<(n / 2 - 4)).map { center(plan.cropX[$0]) }
+ let second = ((n / 2 + 10)..<n).map { center(plan.cropX[$0]) }
+ let firstAvg = first.reduce(0, +) / Double(first.count)
+ let secondAvg = second.reduce(0, +) / Double(second.count)
+ #expect(firstAvg < 500) // left
+ #expect(secondAvg > 780) // right (~960)
+ }
+
+ // The crop window never leaves the frame, even for a speaker pinned at the edge.
+ @Test
+ func cropPathStaysInBounds() {
+ let n = 48
+ var dets: [[ReframeFaceSample]] = []
+ for i in 0..<n { dets.append([face(x: dispW - 30, speaking: true, i)]) }
+ let plan = planner().plan(detections: dets, energy: Array(repeating: 1.0, count: n), sceneCut: Array(repeating: false, count: n))
+ for x in plan.cropX { #expect(x >= 0 && x <= dispW - cropW) }
+ }
+
+ // A scene cut becomes a hard cut (instant recenter, no pan through the cut).
+ @Test
+ func sceneCutBecomesAHardCut() {
+ let n = 48
+ let (dets, energy) = twoPerson(nBins: n, leftSpeaking: { _ in true }, rightSpeaking: { _ in false })
+ var cuts = Array(repeating: false, count: n); cuts[24] = true
+ let plan = planner().plan(detections: dets, energy: energy, sceneCut: cuts)
+ #expect(plan.hardCut[24])
+ }
+
+ // Inside a continuous run the crop motion is velocity-limited (smooth, no teleport).
+ @Test
+ func motionIsVelocityLimitedWithinARun() {
+ let n = 48
+ let (dets, energy) = twoPerson(nBins: n, leftSpeaking: { _ in true }, rightSpeaking: { _ in false })
+ let plan = planner().plan(detections: dets, energy: energy, sceneCut: Array(repeating: false, count: n))
+ let maxVel = dispW * 0.9 / fps
+ for i in 1..<plan.cropX.count where !plan.hardCut[i] {
+ #expect(abs(plan.cropX[i] - plan.cropX[i - 1]) <= maxVel + 1e-6)
+ }
+ }
+
+ // No faces and no audio: a centered crop, no crash.
+ @Test
+ func emptyInputIsCenteredAndSafe() {
+ let n = 24
+ let plan = planner().plan(detections: Array(repeating: [], count: n),
+ energy: Array(repeating: 0, count: n),
+ sceneCut: Array(repeating: false, count: n))
+ #expect(plan.trackCount == 0)
+ #expect(plan.cropX.count == n)
+ let centered = min(max(dispW / 2 - cropW / 2, 0), dispW - cropW)
+ for x in plan.cropX { #expect(abs(x - centered) < 1e-6) }
+ }
+}
diff --git a/scripts/ensure-bundled-tools.sh b/scripts/ensure-bundled-tools.sh
index 1007d155..5dae0f26 100755
--- a/scripts/ensure-bundled-tools.sh
+++ b/scripts/ensure-bundled-tools.sh
@@ -17,9 +17,10 @@ VENDOR_DIR="${DONKEY_TOOLS_DIR:-$ROOT_DIR/vendor/donkey-tools}"
MANIFEST="$ROOT_DIR/apps/Donkey/Sources/DonkeyRuntime/Resources/bundled-tools.json"
# Tools without which a build is not shippable: ffmpeg/ffprobe (media), yt-dlp (the
-# YouTube/download path), lit + pdf-fill (the pdf skill), epub-pack (the book skill).
+# YouTube/download path), lit + pdf-fill (the pdf skill), epub-pack (the book skill),
+# reframe (the shorts skill's active-speaker auto-reframe).
# Keep in sync with fetch-bundled-tools.sh and BundledTools.swift.
-MANDATORY_TOOLS=(ffmpeg ffprobe yt-dlp lit pdf-fill epub-pack)
+MANDATORY_TOOLS=(ffmpeg ffprobe yt-dlp lit pdf-fill epub-pack reframe)
OPTIONAL_TOOLS=(qpdf exiftool)
missing_of() {
diff --git a/scripts/fetch-bundled-tools.sh b/scripts/fetch-bundled-tools.sh
index 6e83e2f5..f8283ec2 100755
--- a/scripts/fetch-bundled-tools.sh
+++ b/scripts/fetch-bundled-tools.sh
@@ -195,6 +195,27 @@ build_epub_pack() {
ok "epub-pack"
}
+# Build the `reframe` CLI from the in-repo Swift source. It links only Apple system frameworks
+# (AVFoundation/Vision/CoreImage), so the result is a single self-contained binary — no dylib
+# bundling. Its decision core, ReframePlanner.swift, is shared with the app (it lives in
+# DonkeyRuntime and is unit-tested there); the CLI compiles it in alongside main.swift so the
+# shipped algorithm is the tested one. MANDATORY: it is the shorts skill's on-device
+# active-speaker auto-reframe (landscape -> vertical 9:16 that follows whoever is talking).
+build_reframe() {
+ if [ -x "$VENDOR_DIR/reframe" ]; then ok "reframe (cached)"; return 0; fi
+ command -v swiftc >/dev/null 2>&1 || { echo "FATAL: swiftc unavailable for reframe build" >&2; exit 1; }
+ if ! swiftc -O \
+ "$ROOT_DIR/tools/reframe/main.swift" \
+ "$ROOT_DIR/apps/Donkey/Sources/DonkeyRuntime/ReframePlanner.swift" \
+ -o "$VENDOR_DIR/reframe" 2>/tmp/reframe-build.log; then
+ echo "FATAL: reframe build failed; tail of /tmp/reframe-build.log:" >&2
+ tail -25 /tmp/reframe-build.log >&2
+ exit 1
+ fi
+ chmod +x "$VENDOR_DIR/reframe"
+ ok "reframe"
+}
+
log "Ensuring dylibbundler"
command -v dylibbundler >/dev/null 2>&1 || brew install dylibbundler >/dev/null 2>&1
@@ -210,6 +231,9 @@ build_pdf_fill
# --- epub-pack: mandatory, built from in-repo Swift source (native Foundation, no deps) ---
build_epub_pack
+# --- reframe: mandatory, built from in-repo Swift source (native AVFoundation/Vision, no deps) ---
+build_reframe
+
# --- qpdf (Homebrew) ---
if [ -x "$VENDOR_DIR/qpdf" ]; then
ok "qpdf (cached)"
@@ -268,6 +292,20 @@ fi
log "Signing"
"$SCRIPT_DIR/sign-bundled-tools.sh" "$VENDOR_DIR"
+# Guard: the bundled ffmpeg MUST carry the libass `subtitles` filter (subtitle burn-in), in
+# every channel — dev, nightly, release all install this same vendored bundle. A future edit
+# that drops --enable-libass (or a libass build break) would silently cripple every caption
+# workflow, so verify the now-signed binary and fail the whole run loudly rather than ship it.
+if [ -x "$VENDOR_DIR/ffmpeg" ]; then
+ if "$VENDOR_DIR/ffmpeg" -hide_banner -filters 2>/dev/null | grep -qw subtitles; then
+ ok "ffmpeg libass(subtitles) verified"
+ else
+ echo "FATAL: bundled ffmpeg lacks the libass 'subtitles' filter (subtitle burn-in)." >&2
+ echo " It must be built with --enable-libass; see build_libass/build_lgpl_ffmpeg." >&2
+ exit 1
+ fi
+fi
+
log "Summary"
printf '%s\n' "${STATUS[@]}"
echo
diff --git a/scripts/publish-bundled-tools.sh b/scripts/publish-bundled-tools.sh
index d5fb4c9a..e619f233 100755
--- a/scripts/publish-bundled-tools.sh
+++ b/scripts/publish-bundled-tools.sh
@@ -24,7 +24,7 @@ ASSET="donkey-tools-$VERSION-$ARCH.tar.gz"
URL="https://github.com/$REPO/releases/download/$TAG/$ASSET"
OUT="/tmp/$ASSET"
-MANDATORY_TOOLS=(ffmpeg ffprobe yt-dlp lit pdf-fill epub-pack)
+MANDATORY_TOOLS=(ffmpeg ffprobe yt-dlp lit pdf-fill epub-pack reframe)
echo "==> Building tools from source (idempotent; skips already-built)"
"$SCRIPT_DIR/fetch-bundled-tools.sh"
diff --git a/tools/reframe/main.swift b/tools/reframe/main.swift
new file mode 100644
index 00000000..12886e3d
--- /dev/null
+++ b/tools/reframe/main.swift
@@ -0,0 +1,290 @@
+// reframe — a native CLI that turns landscape video into vertical (9:16) short-form
+// that tracks the ACTIVE SPEAKER, fully on-device.
+//
+// ffmpeg crops a fixed rectangle; this follows the person who is talking. The whole
+// pipeline uses only Apple system frameworks (AVFoundation + Vision + CoreImage), so
+// there is no model file to bundle and no network call:
+//
+// 1. Analyze — sample frames, detect faces + lip landmarks (Vision), and a scene-cut flag.
+// 2. Audio — read PCM, compute per-bin energy.
+// 3+4. Plan — ReframePlanner (shared, unit-tested) links faces into tracks, picks the
+// active speaker each frame, and builds the smoothed crop path with hard cuts.
+// 5. Render — AVAssetExportSession + a video composition of transform ramps, so the
+// original audio is retained and the motion is sub-pixel smooth.
+//
+// The active-speaker decision and crop path live in ReframePlanner.swift (compiled in
+// alongside this file), which has no AVFoundation/Vision dependency and is unit-tested in
+// DonkeyRuntimeTests — so the algorithm under test is the algorithm that ships here.
+//
+// Usage:
+// reframe --input IN.mp4 --output OUT.mp4 [--aspect 9:16] [--height 1920] [--fps 24] [--plan plan.json]
+//
+// All I/O is JSON so an LLM can drive it: success prints a JSON summary to stdout; errors
+// print {"error":"…"} to stderr and exit non-zero.
+
+import Foundation
+import AVFoundation
+import Vision
+import CoreImage
+import CoreMedia
+
+// MARK: - I/O helpers
+
+func parseArgs(_ argv: [String]) -> [String: String] {
+ var flags: [String: String] = [:]
+ var i = 0
+ while i < argv.count {
+ let a = argv[i]
+ if a.hasPrefix("--") {
+ let key = String(a.dropFirst(2))
+ if i + 1 < argv.count, !argv[i + 1].hasPrefix("--") { flags[key] = argv[i + 1]; i += 2 }
+ else { flags[key] = "true"; i += 1 }
+ } else { i += 1 }
+ }
+ return flags
+}
+
+func fail(_ message: String) -> Never {
+ let payload = ["error": message]
+ if let data = try? JSONSerialization.data(withJSONObject: payload),
+ let text = String(data: data, encoding: .utf8) {
+ FileHandle.standardError.write((text + "\n").data(using: .utf8)!)
+ }
+ exit(1)
+}
+
+func emit(_ object: [String: Any]) {
+ guard let data = try? JSONSerialization.data(withJSONObject: object, options: [.prettyPrinted, .sortedKeys]),
+ let text = String(data: data, encoding: .utf8) else { fail("could not serialize output") }
+ print(text)
+}
+
+func loadSync<T>(_ op: @escaping () async throws -> T) -> T? {
+ let sem = DispatchSemaphore(value: 0)
+ var out: T?
+ Task { out = try? await op(); sem.signal() }
+ sem.wait()
+ return out
+}
+
+// MARK: - inputs
+
+let flags = parseArgs(Array(CommandLine.arguments.dropFirst()))
+guard let inPath = flags["input"], let outPath = flags["output"] else {
+ fail("usage: reframe --input IN.mp4 --output OUT.mp4 [--aspect 9:16] [--height 1920] [--fps 24]")
+}
+let aspect = flags["aspect"] ?? "9:16"
+let aspParts = aspect.split(separator: ":").compactMap { Double($0) }
+guard aspParts.count == 2, aspParts[0] > 0, aspParts[1] > 0 else { fail("bad --aspect (expected like 9:16)") }
+let arN = aspParts[0], arD = aspParts[1]
+let sampleFPS = max(6, Double(flags["fps"] ?? "24") ?? 24.0)
+let outH = max(64, Double(flags["height"] ?? "1920") ?? 1920)
+
+let inURL = URL(fileURLWithPath: (inPath as NSString).expandingTildeInPath)
+let outURL = URL(fileURLWithPath: (outPath as NSString).expandingTildeInPath)
+guard FileManager.default.fileExists(atPath: inURL.path) else { fail("input not found: \(inPath)") }
+let asset = AVURLAsset(url: inURL)
+
+guard let vTrack = (loadSync({ try await asset.loadTracks(withMediaType: .video).first }) ?? nil) else {
+ fail("no video track in \(inPath)")
+}
+let durationCM = loadSync({ try await asset.load(.duration) }) ?? .zero
+let duration = durationCM.seconds
+guard duration > 0 else { fail("zero-duration video") }
+let naturalSize = loadSync({ try await vTrack.load(.naturalSize) }) ?? .zero
+let preferred = loadSync({ try await vTrack.load(.preferredTransform) }) ?? .identity
+let nominalFPSRaw = loadSync({ try await vTrack.load(.nominalFrameRate) }) ?? 30
+let videoFPS = nominalFPSRaw > 1 ? Double(nominalFPSRaw) : 30.0
+
+// display-oriented size (after preferredTransform)
+let dispRect = CGRect(origin: .zero, size: naturalSize).applying(preferred)
+let dispW = abs(dispRect.width)
+let dispH = abs(dispRect.height)
+guard dispW > 0, dispH > 0 else { fail("could not read video dimensions") }
+
+// crop window (full height vertical slice; letterbox-ish clamp if the target is wider than source)
+var cropW = (dispH * arN / arD).rounded()
+var cropH = dispH
+if cropW > dispW { cropW = dispW; cropH = (dispW * arD / arN).rounded() }
+let outW = (outH * arN / arD).rounded()
+let scaleS = outW / cropW
+
+let nBins = max(1, Int((duration * sampleFPS).rounded(.up)))
+func binTime(_ i: Int) -> Double { (Double(i) + 0.5) / sampleFPS }
+
+// MARK: - Pass 1: faces + lip openness + scene cuts via Vision
+
+let generator = AVAssetImageGenerator(asset: asset)
+generator.appliesPreferredTrackTransform = true
+generator.requestedTimeToleranceBefore = .zero
+generator.requestedTimeToleranceAfter = .zero
+generator.maximumSize = CGSize(width: 960, height: 960) // smaller = faster Vision; boxes stay normalized
+
+func lipOpenness(_ lm: VNFaceLandmarks2D?) -> Double {
+ guard let lips = lm?.innerLips ?? lm?.outerLips, lips.pointCount >= 4 else { return 0 }
+ let ys = lips.normalizedPoints.map { Double($0.y) }
+ return ys.max()! - ys.min()! // inner-lip vertical aperture in face-box units (open mouth -> larger)
+}
+
+func sceneDiff(_ a: CGImage, _ b: CGImage) -> Double {
+ let w = 32, h = 18
+ func gray(_ img: CGImage) -> [Double]? {
+ var buf = [UInt8](repeating: 0, count: w * h)
+ let cs = CGColorSpaceCreateDeviceGray()
+ guard let ctx = CGContext(data: &buf, width: w, height: h, bitsPerComponent: 8, bytesPerRow: w,
+ space: cs, bitmapInfo: CGImageAlphaInfo.none.rawValue) else { return nil }
+ ctx.draw(img, in: CGRect(x: 0, y: 0, width: w, height: h))
+ return buf.map { Double($0) / 255.0 }
+ }
+ guard let ga = gray(a), let gb = gray(b) else { return 0 }
+ var s = 0.0
+ for k in 0..<ga.count { s += abs(ga[k] - gb[k]) }
+ return s / Double(ga.count)
+}
+
+var detections = [[ReframeFaceSample]](repeating: [], count: nBins)
+var sceneCut = [Bool](repeating: false, count: nBins)
+var prevSampleImage: CGImage?
+for i in 0..<nBins {
+ let cm = CMTime(seconds: binTime(i), preferredTimescale: 600)
+ guard let cg = try? generator.copyCGImage(at: cm, actualTime: nil) else { continue }
+ if let prev = prevSampleImage, sceneDiff(prev, cg) > 0.18 { sceneCut[i] = true }
+ prevSampleImage = cg
+ let req = VNDetectFaceLandmarksRequest()
+ let handler = VNImageRequestHandler(cgImage: cg, orientation: .up, options: [:])
+ try? handler.perform([req])
+ // Vision boxes are normalized with a bottom-left origin; convert to display pixels (top-left y).
+ detections[i] = (req.results ?? []).map { f in
+ let bb = f.boundingBox
+ return ReframeFaceSample(
+ cx: Double(bb.midX) * dispW,
+ cy: (1.0 - Double(bb.midY)) * dispH,
+ w: Double(bb.width) * dispW,
+ h: Double(bb.height) * dispH,
+ openness: lipOpenness(f.landmarks)
+ )
+ }
+}
+
+// MARK: - Pass 2: audio energy per bin
+
+var energy = [Double](repeating: 0, count: nBins)
+if let aTrack = (loadSync({ try await asset.loadTracks(withMediaType: .audio).first }) ?? nil) {
+ let reader = try? AVAssetReader(asset: asset)
+ let settings: [String: Any] = [
+ AVFormatIDKey: kAudioFormatLinearPCM,
+ AVLinearPCMBitDepthKey: 32,
+ AVLinearPCMIsFloatKey: true,
+ AVLinearPCMIsNonInterleaved: false,
+ AVNumberOfChannelsKey: 1,
+ AVSampleRateKey: 16000.0,
+ ]
+ let output = AVAssetReaderTrackOutput(track: aTrack, outputSettings: settings)
+ if let reader, reader.canAdd(output) {
+ reader.add(output)
+ reader.startReading()
+ var sumSq = [Double](repeating: 0, count: nBins)
+ var cnt = [Double](repeating: 0, count: nBins)
+ let sr = 16000.0
+ while let sb = output.copyNextSampleBuffer() {
+ let pts = CMSampleBufferGetPresentationTimeStamp(sb).seconds
+ guard let blockBuffer = CMSampleBufferGetDataBuffer(sb) else { continue }
+ var lengthAtOffset = 0; var totalLength = 0; var dataPtr: UnsafeMutablePointer<Int8>?
+ CMBlockBufferGetDataPointer(blockBuffer, atOffset: 0, lengthAtOffsetOut: &lengthAtOffset,
+ totalLengthOut: &totalLength, dataPointerOut: &dataPtr)
+ guard let dataPtr else { continue }
+ let count = totalLength / MemoryLayout<Float32>.size
+ dataPtr.withMemoryRebound(to: Float32.self, capacity: count) { fp in
+ for n in 0..<count {
+ let bin = Int((pts + Double(n) / sr) * sampleFPS)
+ if bin >= 0 && bin < nBins { let v = Double(fp[n]); sumSq[bin] += v * v; cnt[bin] += 1 }
+ }
+ }
+ }
+ for i in 0..<nBins { energy[i] = cnt[i] > 0 ? (sumSq[i] / cnt[i]).squareRoot() : 0 }
+ }
+}
+
+// MARK: - Pass 3+4: plan tracks, active speaker, and crop path (ReframePlanner)
+
+let plan = ReframePlanner(dispW: dispW, dispH: dispH, cropW: cropW, sampleFPS: sampleFPS)
+ .plan(detections: detections, energy: energy, sceneCut: sceneCut)
+let cropX = plan.cropX
+let hardCut = plan.hardCut
+
+// Optional debug plan.
+if let planPath = flags["plan"] {
+ var bins: [[String: Any]] = []
+ for i in 0..<nBins {
+ let center = (cropX[i] + cropW / 2)
+ bins.append(["t": binTime(i), "cropX": cropX[i], "center": center,
+ "speaker": plan.activeTrack[i], "hardCut": hardCut[i]])
+ }
+ let obj: [String: Any] = ["dispW": dispW, "dispH": dispH, "cropW": cropW, "cropH": cropH,
+ "outW": outW, "outH": outH, "tracks": plan.trackCount, "bins": bins]
+ if let data = try? JSONSerialization.data(withJSONObject: obj, options: [.prettyPrinted]) {
+ try? data.write(to: URL(fileURLWithPath: (planPath as NSString).expandingTildeInPath))
+ }
+}
+
+// MARK: - Pass 5: render via export session + transform ramps
+
+let rOffset = CGAffineTransform(translationX: -dispRect.minX, y: -dispRect.minY)
+let rectify = preferred.concatenating(rOffset)
+func transformFor(_ cx: Double) -> CGAffineTransform {
+ let cropScale = CGAffineTransform(a: scaleS, b: 0, c: 0, d: scaleS, tx: -cx * scaleS, ty: 0)
+ return rectify.concatenating(cropScale)
+}
+
+let comp = AVMutableVideoComposition()
+comp.renderSize = CGSize(width: outW, height: outH)
+comp.frameDuration = CMTime(value: 1, timescale: CMTimeScale(max(1, videoFPS.rounded())))
+
+let instruction = AVMutableVideoCompositionInstruction()
+instruction.timeRange = CMTimeRange(start: .zero, duration: durationCM)
+let layer = AVMutableVideoCompositionLayerInstruction(assetTrack: vTrack)
+
+func tAt(_ i: Int) -> CMTime { CMTime(seconds: binTime(i), preferredTimescale: 600) }
+layer.setTransform(transformFor(cropX[0]), at: .zero)
+for i in 0..<(nBins - 1) {
+ let start = i == 0 ? CMTime.zero : tAt(i)
+ let end = tAt(i + 1)
+ if hardCut[i + 1] {
+ layer.setTransformRamp(fromStart: transformFor(cropX[i]), toEnd: transformFor(cropX[i]),
+ timeRange: CMTimeRange(start: start, end: end))
+ layer.setTransform(transformFor(cropX[i + 1]), at: end)
+ } else {
+ layer.setTransformRamp(fromStart: transformFor(cropX[i]), toEnd: transformFor(cropX[i + 1]),
+ timeRange: CMTimeRange(start: start, end: end))
+ }
+}
+instruction.layerInstructions = [layer]
+comp.instructions = [instruction]
+
+guard let export = AVAssetExportSession(asset: asset, presetName: AVAssetExportPresetHighestQuality) else {
+ fail("could not create export session")
+}
+export.videoComposition = comp
+export.outputURL = outURL
+export.outputFileType = .mp4
+try? FileManager.default.removeItem(at: outURL)
+
+let sem = DispatchSemaphore(value: 0)
+export.exportAsynchronously { sem.signal() }
+sem.wait()
+
+guard export.status == .completed else {
+ fail("export failed: \(export.error?.localizedDescription ?? "unknown") (status \(export.status.rawValue))")
+}
+
+let usedSpeakers = Set(plan.activeTrack.filter { $0 >= 0 }).count
+let cuts = hardCut.filter { $0 }.count
+emit([
+ "out": outURL.path,
+ "width": Int(outW),
+ "height": Int(outH),
+ "durationSeconds": duration,
+ "facesTracked": plan.trackCount,
+ "speakersFollowed": max(usedSpeakers, plan.trackCount > 0 ? 1 : 0),
+ "cuts": cuts,
+])