Capturing screen content in macOS
At a glance
| Item | Summary |
|---|---|
| Purpose | Stream desktop content like displays, apps, and windows by adopting screen capture in your app. |
| App architecture | A Swift sample with the source-visible chain CaptureSampleApp → ContentView → AudioLevelProvider → ScreenCaptureKit APIs. |
| Main patterns | Protocol-oriented abstraction, Delegate or data-source callbacks, Binding-based state propagation, Publisher-backed observable state, Actor-isolated state |
| Project style | 11 scanned source file(s) across Swift, organized around ranked entry, type, and file boundaries. |
Project structure
Source bundle/
├── CaptureSample/
│ ├── CaptureSampleApp.swift
│ ├── ScreenRecorder.swift
│ ├── Views/
│ │ ├── ConfigurationView.swift
│ │ ├── PickerSettingsView.swift
│ │ ├── AudioLevelsView.swift
│ │ ├── MaterialView.swift
│ │ └── CapturePreview.swift
│ ├── CaptureEngine.swift
│ ├── ContentView.swift
│ ├── PowerMeter.swift
│ └── AudioPlayer.swift
└── CaptureSample.xcodeproj/
└── .xcodesamplecode.plist
Structure observations
- Architecturally prominent files are ranked from entry points and role-named declarations; resource-only paths are omitted.
- Primary languages: Swift.
- The verified tree contains 4 project/configuration file(s) and 24 source declaration(s).
Overall architecture
flowchart LR
N1["CaptureSampleApp"]
N2["ContentView"]
N3["AudioLevelProvider"]
N4["ScreenCaptureKit APIs"]
N1 --> N2
N2 --> N3
N3 --> N4
Reference code
CaptureSample/CaptureSampleApp.swift:9 — architecture anchor
@main
struct CaptureSampleApp: App {
// ...
}Interpretation
The arrows summarize the source-visible entry, role-named types or folders, and framework direction; when nodes come from structural folders, the sequence is a high-level interpretation rather than proof that every adjacent node calls the next. Ownership is claimed only where the next section cites a stored property or assignment. The diagram is intentionally limited to the dominant path into ScreenCaptureKit.
Ownership and state
classDiagram
ScreenRecorder *-- Logger : logger
ScreenRecorder o-- CaptureType : captureType
ScreenRecorder *-- Int : maximumStreamCount
ScreenRecorder o-- Excludedwindowidsselection : excludedWindowIDsSelection
Ownership evidence
CaptureSample/ScreenRecorder.swift:43 — stored dependency or nearest verified ownership anchor
@MainActor
class ScreenRecorder: NSObject,
ObservableObject,
SCContentSharingPickerObserver {
// ...
}| Owner | Object or state | Relationship | Mutation authority |
|---|---|---|---|
ScreenRecorder |
Logger (logger) |
creates and retains | Initialized by the owner; the binding is immutable |
ScreenRecorder |
CaptureType (captureType) |
stores or receives | App/module collaborators |
ScreenRecorder |
Int (maximumStreamCount) |
owns value state | App/module collaborators |
ScreenRecorder |
Excludedwindowidsselection (excludedWindowIDsSelection) |
stores or receives | App/module collaborators |
Composition arrows indicate a source-visible construction expression or locally owned value state; aggregation means the owner stores or receives a dependency without proving exclusive lifetime ownership.
Class and protocol design
CaptureSample/PowerMeter.swift:19 — representative type boundary
protocol AudioLevelProvider {
var levels: AudioLevels { get }
}| Type | Responsibility | Depends on or conforms to |
|---|---|---|
CaptureSampleApp |
Application entry and top-level composition | App |
AudioLevelProvider |
Defines a capability or collaboration contract | Concrete collaborators/imported frameworks |
AudioLevelsProvider |
Supplies a capability or framework resource | ObservableObject |
ScreenRecorder |
Owns capture or recording work | NSObject |
ConfigurationView |
User-interface presentation and input forwarding | View |
HeaderView |
User-interface presentation and input forwarding | View |
CaptureEngine |
Owns processing or simulation work | NSObject, @unchecked Sendable |
ContentView |
User-interface presentation and input forwarding | View |
PickerSettingsView |
User-interface presentation and input forwarding | View |
BundleIDsListView |
User-interface presentation and input forwarding | View |
The source explicitly defines local protocol relationships: PowerMeter → AudioLevelProvider.
Access control
| Symbol | Access | Verified effect | Likely rationale |
|---|---|---|---|
logger (CaptureSample/CaptureEngine.swift:29) |
private |
Use is restricted to the lexical declaration and same-file extensions allowed by Swift. | Inference: keep state mutation or dependency lifetime inside the owning implementation. |
stream (CaptureSample/CaptureEngine.swift:31) |
private(set) |
Read access follows the declaration; writes remain in the private scope. | Inference: allow observation while reserving invariant-changing writes for the owner. |
streamOutput (CaptureSample/CaptureEngine.swift:32) |
private |
Use is restricted to the lexical declaration and same-file extensions allowed by Swift. | Inference: keep state mutation or dependency lifetime inside the owning implementation. |
videoSampleBufferQueue (CaptureSample/CaptureEngine.swift:33) |
private |
Use is restricted to the lexical declaration and same-file extensions allowed by Swift. | Inference: keep state mutation or dependency lifetime inside the owning implementation. |
Reference code
CaptureSample/CaptureEngine.swift:29 — representative boundary
private let logger = Logger()
private(set) var stream: SCStream?
private var streamOutput: CaptureEngineStreamOutput?
private let videoSampleBufferQueue = DispatchQueue(label: "com.example.apple-samplecode.VideoSampleBufferQueue")
private let audioSampleBufferQueue = DispatchQueue(label: "com.example.apple-samplecode.AudioSampleBufferQueue")Swift declarations without a modifier are internal; explicit private, fileprivate, private(set), public, or open entries above are interpreted by language semantics. Objective-C/C samples instead rely on header and implementation boundaries, which are not equivalent to Swift lexical privacy.
Logic ownership and placement
| Logic | Owning type or file | Placement rationale |
|---|---|---|
| Application entry and top-level composition | CaptureSampleApp |
The source’s App suffix makes this role explicit. |
| Owns processing or simulation work | CaptureEngine |
The source’s Engine suffix makes this role explicit. |
| Owns media or timeline playback | AudioPlayer |
The source’s Player suffix makes this role explicit. |
| Supplies a capability or framework resource | AudioLevelProvider, AudioLevelsProvider |
The source’s Provider suffix makes this role explicit. |
| Owns capture or recording work | ScreenRecorder |
The source’s Recorder suffix makes this role explicit. |
| User-interface presentation and input forwarding | AudioLevelsView, BundleIDsListView, ConfigurationView, ContentView |
The source’s View suffix makes this role explicit. |
Design patterns
| Pattern | Source evidence | Purpose or tradeoff |
|---|---|---|
| Protocol-oriented abstraction | CaptureSample/PowerMeter.swift:23 |
A local protocol and concrete conformance create an explicit capability boundary. |
| Delegate or data-source callbacks | CaptureSample/CaptureEngine.swift:95 |
Callback protocols invert event delivery back into the sample’s owner. |
| Binding-based state propagation | CaptureSample/Views/ConfigurationView.swift:21 |
A binding exposes controlled read/write access while the upstream owner remains authoritative. |
| Publisher-backed observable state | CaptureSample/ScreenRecorder.swift:48 |
Published properties notify observers while mutation remains with the state object. |
| Actor-isolated state | CaptureSample/ScreenRecorder.swift:18 |
Actor annotations make the concurrency ownership boundary explicit. |
Main application flow
Starting a capture is an asynchronous pipeline: the UI starts the recorder, the engine adapts ScreenCaptureKit callbacks into an async stream, and the recorder updates the preview for every yielded frame.
sequenceDiagram
actor User
participant View as ContentView
participant Recorder as ScreenRecorder
participant Engine as CaptureEngine
participant Stream as SCStream
participant Output as CaptureEngineStreamOutput
participant Preview as CapturePreview
User->>View: Start capture
View->>Recorder: start()
Recorder->>Engine: startCapture(configuration, filter)
Engine->>Stream: addStreamOutput(...) and startCapture()
loop each screen sample
Stream-->>Output: didOutputSampleBuffer
Output-->>Engine: continuation.yield(frame)
Engine-->>Recorder: AsyncThrowingStream frame
Recorder->>Preview: updateFrame(frame)
end
Reference code
CaptureSample/CaptureEngine.swift:44 — the engine creates the callback adapter and yields captured frames into an async stream.
func startCapture(configuration: SCStreamConfiguration, filter: SCContentFilter) -> AsyncThrowingStream<CapturedFrame, Error> {
AsyncThrowingStream<CapturedFrame, Error> { continuation in
let streamOutput = CaptureEngineStreamOutput(continuation: continuation)
self.streamOutput = streamOutput
streamOutput.capturedFrameHandler = { continuation.yield($0) }
do {
stream = SCStream(filter: filter, configuration: configuration, delegate: streamOutput)
try stream?.addStreamOutput(streamOutput, type: .screen, sampleHandlerQueue: videoSampleBufferQueue)
stream?.startCapture()
} catch {
continuation.finish(throwing: error)
}
}
}CaptureSample/ScreenRecorder.swift:217 — the recorder consumes the stream in order and forwards each frame to the preview.
for try await frame in captureEngine.startCapture(configuration: config, filter: filter) {
capturePreview.updateFrame(frame)
if contentSize != frame.size {
contentSize = frame.size
}
}Naming conventions
- Types: App: CaptureSampleApp; Engine: CaptureEngine; Player: AudioPlayer; Provider: AudioLevelProvider, AudioLevelsProvider; Recorder: ScreenRecorder; View: AudioLevelsView, BundleIDsListView, ConfigurationView, ContentView, HeaderView.
- Protocols:
AudioLevelProvider. - Methods:
monitorAvailableContent,start,stop,openRecordingFolder,startAudioMetering,stopAudioMetering,addMicrophoneOutput,removeMicrophoneOutput. - Files:
CaptureSample/CaptureSampleApp.swift,CaptureSample/ScreenRecorder.swift,CaptureSample/Views/ConfigurationView.swift,CaptureSample/CaptureEngine.swift,CaptureSample/ContentView.swift,CaptureSample/PowerMeter.swift.
Architecture takeaways
CaptureSampleAppis the main source-visible entry or composition anchor for this sample.- Framework work reaches SwiftUI, ScreenCaptureKit, AVFoundation, AVFAudio through a deliberately small high-level chain; the detailed API graph remains inside the cited implementation files.
- Stored-property evidence identifies lifecycle collaboration; it does not by itself prove exclusive object ownership.
- Access-control conclusions separate verified language visibility from the likely design rationale.
- Local protocol relationships provide an explicit substitution boundary.
Source map
| Source file | Relevant symbols |
|---|---|
CaptureSample/CaptureSampleApp.swift |
CaptureSampleApp |
CaptureSample/ScreenRecorder.swift |
AudioLevelsProvider, ScreenRecorder, CaptureType, DynamicRangePreset, SCScreenRecordingError |
CaptureSample/Views/ConfigurationView.swift |
ConfigurationView, HeaderView |
CaptureSample/CaptureEngine.swift |
CapturedFrame, CaptureEngine, CaptureEngineStreamOutput |
CaptureSample/ContentView.swift |
ContentView, ContentView_Previews |
CaptureSample/PowerMeter.swift |
AudioLevels, AudioLevelProvider, PowerMeter, PowerLevels, MeterTable |
CaptureSample/Views/PickerSettingsView.swift |
PickerSettingsView, BundleIDsListView |
CaptureSample/AudioPlayer.swift |
AudioPlayer |
CaptureSample/Views/AudioLevelsView.swift |
AudioLevelsView |
CaptureSample/Views/MaterialView.swift |
MaterialView |