File size: 5,107 Bytes
2785f78
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
import AVFoundation
import Foundation
import CoreMedia

class ContinuousSegmenter: NSObject, AVCaptureVideoDataOutputSampleBufferDelegate, AVCaptureAudioDataOutputSampleBufferDelegate {
  // MARK: – Configuration
  let segmentDuration: CMTime = .init(seconds: 2, preferredTimescale: 600)
  let outputDir: URL

  // MARK: – Capture
  let session = AVCaptureSession()
  let videoOutput = AVCaptureVideoDataOutput()
  let audioOutput = AVCaptureAudioDataOutput()

  // MARK: – Writer state
  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()
    // Prepare first writer starting at time zero
    rollWriter(at: .zero)
  }

  private func setupSession() {
    session.beginConfiguration()
    session.sessionPreset = .high

    // Screen input (main display)
    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)

    // Audio input (system audio via BlackHole as default)
    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)

    // Data outputs
    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) {
    // Finish previous writer asynchronously
    if let oldWriter = currentWriter {
      oldWriter.finishWriting {
        print("✅ Finished segment \(self.segmentIndex - 1)")
      }
    }

    // Set up new writer
    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)

      // Video Input Configuration
      let vSettings: [String: Any] = [
        AVVideoCodecKey: AVVideoCodecType.h264,
        AVVideoWidthKey: 1280,
        AVVideoHeightKey: 720
      ]
      let vInput = AVAssetWriterInput(mediaType: .video, outputSettings: vSettings)
      vInput.expectsMediaDataInRealTime = true
      writer.add(vInput)

      // Audio Input Configuration
      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)

      // Assign new writer & inputs
      currentWriter = writer
      videoInput = vInput
      audioInput = aInput
      segmentStartTime = startTime
      segmentIndex += 1

      // Start writing session
      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)

    // Check for segment rollover
    if CMTimeSubtract(pts, segmentStartTime) >= segmentDuration {
      rollWriter(at: pts)
    }

    // Append to writer inputs
    if mediaType == .video, let vInput = videoInput, vInput.isReadyForMoreMediaData {
      vInput.append(sample)
    }
    if mediaType == .audio, let aInput = audioInput, aInput.isReadyForMoreMediaData {
      aInput.append(sample)
    }
  }

  // MARK: – Delegates
  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)
    }
  }
}

// === main ===
let cwd = URL(fileURLWithPath: FileManager.default.currentDirectoryPath)
let segmentsDir = cwd.appendingPathComponent("segments")
let segmenter = ContinuousSegmenter(outputDir: segmentsDir)
segmenter.start()
RunLoop.main.run()