| import AVFoundation |
| import Foundation |
| import CoreMedia |
|
|
| class ContinuousSegmenter: NSObject, AVCaptureVideoDataOutputSampleBufferDelegate, AVCaptureAudioDataOutputSampleBufferDelegate { |
| |
| let segmentDuration: CMTime = .init(seconds: 2, preferredTimescale: 600) |
| let outputDir: URL |
|
|
| |
| let session = AVCaptureSession() |
| let videoOutput = AVCaptureVideoDataOutput() |
| let audioOutput = AVCaptureAudioDataOutput() |
|
|
| |
| var currentWriter: AVAssetWriter? |
| var videoInput: AVAssetWriterInput? |
| var audioInput: AVAssetWriterInput? |
| var segmentStartTime: CMTime = .zero |
| var segmentIndex = 0 |
|
|
| init(outputDir: URL) { |
| self.outputDir = outputDir |
| super.init() |
| setupSession() |
| |
| rollWriter(at: .zero) |
| } |
|
|
| private func setupSession() { |
| session.beginConfiguration() |
| session.sessionPreset = .high |
|
|
| |
| let displayID = CGMainDisplayID() |
| guard let screenIn = AVCaptureScreenInput(displayID: displayID) else { |
| fatalError("❌ Unable to create screen input") |
| } |
| screenIn.minFrameDuration = CMTime(value: 1, timescale: 30) |
| screenIn.capturesCursor = true |
| session.addInput(screenIn) |
|
|
| |
| guard let audioDev = AVCaptureDevice.default(for: .audio), |
| let audioIn = try? AVCaptureDeviceInput(device: audioDev), |
| session.canAddInput(audioIn) else { |
| fatalError("❌ Unable to create audio input") |
| } |
| session.addInput(audioIn) |
|
|
| |
| let q = DispatchQueue(label: "segmentation.queue") |
| videoOutput.setSampleBufferDelegate(self, queue: q) |
| audioOutput.setSampleBufferDelegate(self, queue: q) |
| guard session.canAddOutput(videoOutput), session.canAddOutput(audioOutput) else { |
| fatalError("❌ Unable to add data outputs") |
| } |
| session.addOutput(videoOutput) |
| session.addOutput(audioOutput) |
| session.commitConfiguration() |
| } |
|
|
| private func rollWriter(at startTime: CMTime) { |
| |
| if let oldWriter = currentWriter { |
| oldWriter.finishWriting { |
| print("✅ Finished segment \(self.segmentIndex - 1)") |
| } |
| } |
|
|
| |
| do { |
| let filename = String(format: "segment_%03d.mov", segmentIndex) |
| let fileURL = outputDir.appendingPathComponent(filename) |
| try FileManager.default.createDirectory(at: outputDir, withIntermediateDirectories: true) |
|
|
| let writer = try AVAssetWriter(outputURL: fileURL, fileType: .mov) |
|
|
| |
| let vSettings: [String: Any] = [ |
| AVVideoCodecKey: AVVideoCodecType.h264, |
| AVVideoWidthKey: 1280, |
| AVVideoHeightKey: 720 |
| ] |
| let vInput = AVAssetWriterInput(mediaType: .video, outputSettings: vSettings) |
| vInput.expectsMediaDataInRealTime = true |
| writer.add(vInput) |
|
|
| |
| let aSettings: [String: Any] = [ |
| AVFormatIDKey: kAudioFormatMPEG4AAC, |
| AVNumberOfChannelsKey: 2, |
| AVSampleRateKey: 48000, |
| AVEncoderBitRateKey: 128000 |
| ] |
| let aInput = AVAssetWriterInput(mediaType: .audio, outputSettings: aSettings) |
| aInput.expectsMediaDataInRealTime = true |
| writer.add(aInput) |
|
|
| |
| currentWriter = writer |
| videoInput = vInput |
| audioInput = aInput |
| segmentStartTime = startTime |
| segmentIndex += 1 |
|
|
| |
| writer.startWriting() |
| writer.startSession(atSourceTime: startTime) |
| print("▶️ Started segment \(segmentIndex - 1) at \(startTime.seconds) s") |
| } catch { |
| fatalError("❌ Could not start writer: \(error)") |
| } |
| } |
|
|
| func start() { |
| session.startRunning() |
| } |
|
|
| private func handle(_ sample: CMSampleBuffer, mediaType: AVMediaType) { |
| guard CMSampleBufferDataIsReady(sample), currentWriter != nil else { return } |
|
|
| let pts = CMSampleBufferGetPresentationTimeStamp(sample) |
|
|
| |
| if CMTimeSubtract(pts, segmentStartTime) >= segmentDuration { |
| rollWriter(at: pts) |
| } |
|
|
| |
| if mediaType == .video, let vInput = videoInput, vInput.isReadyForMoreMediaData { |
| vInput.append(sample) |
| } |
| if mediaType == .audio, let aInput = audioInput, aInput.isReadyForMoreMediaData { |
| aInput.append(sample) |
| } |
| } |
|
|
| |
| func captureOutput(_ output: AVCaptureOutput, |
| didOutput sampleBuffer: CMSampleBuffer, |
| from connection: AVCaptureConnection) { |
| if output === videoOutput { |
| handle(sampleBuffer, mediaType: .video) |
| } else if output === audioOutput { |
| handle(sampleBuffer, mediaType: .audio) |
| } |
| } |
| } |
|
|
| |
| let cwd = URL(fileURLWithPath: FileManager.default.currentDirectoryPath) |
| let segmentsDir = cwd.appendingPathComponent("segments") |
| let segmenter = ContinuousSegmenter(outputDir: segmentsDir) |
| segmenter.start() |
| RunLoop.main.run() |
|
|
|
|