Files

61 lines
2.8 KiB
Swift

// SPDX-License-Identifier: GPL-3.0-or-later
import Foundation
import CoreGraphics
/// Only linked into the disposable helper. These waits never run in the Mac
/// application's main actor or machine controller. The codec implementation is
/// exactly the same bounded writer used by the native capture controls.
@objc(VCCPlaytestVideoWriter)
final class VCCPlaytestVideoWriter: NSObject {
private let encoder: CoCoVideoEncoder
private let directory: URL
private let includeAudio: Bool
private var sampleOffset: Int64 = 0
@objc init(directory: URL, includeAudio: Bool) throws {
self.directory = directory; self.includeAudio = includeAudio
encoder = try CoCoVideoEncoder(workingURL: directory.appendingPathComponent("Working.mov"))
super.init()
}
private final class Reply<T>: @unchecked Sendable {
let semaphore = DispatchSemaphore(value: 0)
private let lock = NSLock()
private var result: Result<T, Error>?
func complete(_ result: Result<T, Error>) { lock.lock(); self.result = result; lock.unlock(); semaphore.signal() }
func wait() throws -> T {
guard semaphore.wait(timeout: .now() + 20) == .success else { throw CoCoRecordingError.message("The disposable video writer timed out.") }
lock.lock(); defer { lock.unlock() }
guard let result else { throw CoCoRecordingError.message("The disposable video writer returned no result.") }
return try result.get()
}
}
@objc func appendPixels(_ pixels: Data, area: CGRect, samples: Data) throws {
guard samples.count % 8 == 0, samples.count <= 16_384 * 8 else { throw CoCoRecordingError.message("Invalid disposable video audio interval.") }
let frame = CoCoVideoFrame(pixels: pixels, area: area,
audio: includeAudio ? samples : Data(count: samples.count), sampleOffset: sampleOffset)
encoder.append([frame]); sampleOffset += Int64(samples.count / 8)
let reply = Reply<Void>()
encoder.whenDrained { reply.complete($0) }
try reply.wait()
}
@objc func finish() throws -> URL {
let reply = Reply<URL>()
encoder.finish { reply.complete($0) }
let working = try reply.wait()
let output = directory.appendingPathComponent("Clip.mp4")
let exported = Reply<URL>()
Task.detached {
do { try await CoCoVideoEncoder.exportMP4(from: working, to: output); exported.complete(.success(output)) }
catch { exported.complete(.failure(error)) }
}
let result = try exported.wait()
// Conversion verifies playable tracks/duration before removing only our
// known working file. Failures retain that file for explicit recovery.
try FileManager.default.removeItem(at: working)
return result
}
}