]> git.r.bdr.sh - rbdr/captura/blame - Captura/Domain/CapturaCaptureSession.swift
Remove SwiftData references
[rbdr/captura] / Captura / Domain / CapturaCaptureSession.swift
CommitLineData
c9b9e1d6
RBR
1import AppKit
2import AVFoundation
3
4class CapturaCaptureSession: AVCaptureSession, AVCaptureFileOutputRecordingDelegate, AVCaptureVideoDataOutputSampleBufferDelegate {
5
6 let videoOutput = AVCaptureVideoDataOutput()
7 let movieFileOutput = AVCaptureMovieFileOutput()
8 var receivedFrames = false
9
10 init(_ screen: NSScreen, box: NSRect) {
11 super.init()
12
13 let displayId = screen.deviceDescription[NSDeviceDescriptionKey("NSScreenNumber")] as! CGDirectDisplayID
14 let screenInput = AVCaptureScreenInput(displayID: displayId)
15 screenInput?.cropRect = box.insetBy(dx: 1, dy: 1)
16
17 if self.canAddInput(screenInput!) {
18 self.addInput(screenInput!)
19 }
20
21 videoOutput.setSampleBufferDelegate(self, queue: Dispatch.DispatchQueue(label: "sample buffer delegate", attributes: []))
22
23 if self.canAddOutput(videoOutput) {
24 self.addOutput(videoOutput)
25 }
26
27 if self.canAddOutput(movieFileOutput) {
28 self.addOutput(movieFileOutput)
29 }
30 }
31
32 func startRecording() {
33 receivedFrames = false
34 self.startRunning()
35
36 DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
37 if !self.receivedFrames {
38 NotificationCenter.default.post(name: .failedToStart, object: nil, userInfo: nil)
39 }
40 }
41 }
42
43 func startRecording(to url: URL) {
44 self.startRecording()
45 movieFileOutput.startRecording(to: url, recordingDelegate: self)
46 }
47
48 // MARK: - AVCaptureVideoDataOutputSampleBufferDelegate Implementation
49
50 func captureOutput(_ output: AVCaptureOutput, didOutput sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection) {
51 receivedFrames = true
52
53 guard let imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer) else { return }
54 NotificationCenter.default.post(name: .receivedFrame, object: nil, userInfo: ["frame": imageBuffer])
55 }
56
57 // MARK: - AVCaptureFileOutputRecordingDelegate Implementation
58
59 func fileOutput(_ output: AVCaptureFileOutput, didFinishRecordingTo outputFileURL: URL, from connections: [AVCaptureConnection], error: Error?) {}
60}