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 |
| Project style | 11 scanned source file(s) across Swift, organized around ranked entry, type, and file boundaries. |
| Execution model | Source-visible boundaries: Sendable or @Sendable, DispatchQueue(label:), async declaration or closure, Task, @MainActor; none alone proves a background thread. |
| State/event model | Source-visible mechanisms: ObservableObject, @Published, SwiftUI state property wrapper. |
| Key frameworks/packages | SwiftUI, Foundation, ScreenCaptureKit, Combine, OSLog; these are source dependencies, not architecture labels. |
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 {
var body: some Scene {
WindowGroup {
ContentView()
.frame(minWidth: 960, minHeight: 724)
.background(.black)
}
}
}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.
Concurrency, scheduling, and thread safety
Evidence limit: actor isolation, async/await, or Task creation does not by itself prove background-thread execution; Sendable conformance alone does not prove thread-safe mutation.
| Concern | Source mechanism | Verified placement or handoff | Evidence |
|---|---|---|---|
| Transfer contract | Sendable or @Sendable |
The source declares a sendability boundary; this alone does not synchronize mutable state. | CaptureSample/CaptureEngine.swift:14 |
| Queue scheduling | DispatchQueue(label:) |
The source constructs a dispatch queue; its label alone does not prove a thread. | CaptureSample/CaptureEngine.swift:33 |
| Suspension boundary | async declaration or closure |
The source declares or crosses an asynchronous boundary; it does not by itself establish background execution. | CaptureSample/CaptureEngine.swift:66 |
| Task creation | Task |
The source creates an unstructured task; surrounding context determines inherited actor isolation. | CaptureSample/ContentView.swift:60 |
| Main isolation | @MainActor |
The cited annotation marks its attached declaration or closure as main-actor isolated. | CaptureSample/ScreenRecorder.swift:18 |
@MainActor/MainActor.run, DispatchQueue.main, and RunLoop.main are reported as distinct isolation, queue, and event-loop mechanisms. A plain Task is kept separate from Task.detached; neither is labeled as a background thread.
Reference code
CaptureSample/CaptureEngine.swift:14 — representative execution boundary
struct CapturedFrame: @unchecked Sendable {
static var invalid: CapturedFrame {
CapturedFrame(surface: nil, contentRect: .zero, contentScale: 0, scaleFactor: 0)
}
// ...
}State propagation, frameworks, and dependencies
Evidence limit: an import proves a source-level compilation dependency at the cited line; it does not prove runtime use, architectural adoption, or whether a Swift package is a direct application dependency.
| Category | Mechanism or module | Verified role | Evidence |
|---|---|---|---|
| State propagation | ObservableObject |
ObservableObject supplies an observation contract. | CaptureSample/AudioPlayer.swift:11 |
| State propagation | @Published |
A published property can emit owner-controlled changes. | CaptureSample/AudioPlayer.swift:15 |
| State propagation | SwiftUI state property wrapper |
A SwiftUI property wrapper supplies or observes UI state. | CaptureSample/ContentView.swift:15 |
| Source import | SwiftUI |
The cited file imports this module; runtime use and architectural role are not inferred. | CaptureSample/CaptureSampleApp.swift:7 |
| Source import | Foundation |
The cited file imports this module; runtime use and architectural role are not inferred. | CaptureSample/AudioPlayer.swift:8 |
| Source import | ScreenCaptureKit |
The cited file imports this module; runtime use and architectural role are not inferred. | CaptureSample/CaptureEngine.swift:9 |
| Source import | Combine |
The cited file imports this module; runtime use and architectural role are not inferred. | CaptureSample/CaptureEngine.swift:11 |
| Source import | OSLog |
The cited file imports this module; runtime use and architectural role are not inferred. | CaptureSample/CaptureEngine.swift:10 |
receive(on:) describes downstream delivery scheduling, while subscribe(on:) describes upstream subscription/request/cancel scheduling. An import Combine alone establishes neither behavior nor a Store, reducer, Redux, or other application architecture.
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
class CaptureEngine: NSObject, @unchecked Sendable {
// ...
private let logger = Logger()
// ...
}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. |
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 — startCapture
func startCapture(configuration: SCStreamConfiguration, filter: SCContentFilter) -> AsyncThrowingStream<CapturedFrame, Error> {
AsyncThrowingStream<CapturedFrame, Error> { continuation in
// The stream output object. Avoid reassigning it to a new object every time startCapture is called.
let streamOutput = CaptureEngineStreamOutput(continuation: continuation)
self.streamOutput = streamOutput
streamOutput.capturedFrameHandler = { continuation.yield($0) }
streamOutput.pcmBufferHandler = { self.powerMeter.process(buffer: $0) }
do {
stream = SCStream(filter: filter, configuration: configuration, delegate: streamOutput)
// Add a stream output to capture screen content.
try stream?.addStreamOutput(streamOutput, type: .screen, sampleHandlerQueue: videoSampleBufferQueue)
try stream?.addStreamOutput(streamOutput, type: .audio, sampleHandlerQueue: audioSampleBufferQueue)
try stream?.addStreamOutput(streamOutput, type: .microphone, sampleHandlerQueue: micSampleBufferQueue)
stream?.startCapture()
} catch {
continuation.finish(throwing: error)
}
}
}CaptureSample/ScreenRecorder.swift:195 — start
func start() async {
// Exit early if already running.
guard !isRunning else { return }
if !isSetup {
// Starting polling for available screen content.
await monitorAvailableContent()
isSetup = true
}
// If the user enables audio capture, start monitoring the audio stream.
if isAudioCaptureEnabled {
startAudioMetering()
}
do {
let config = streamConfiguration
let filter = contentFilter
// Update the running state.
isRunning = true
setPickerUpdate(false)
// Start the stream and await new video frames.
for try await frame in captureEngine.startCapture(configuration: config, filter: filter) {
capturePreview.updateFrame(frame)
if contentSize != frame.size {
// Update the content size if it changed.
contentSize = frame.size
}
}
} catch {
logger.error("\(error.localizedDescription)")
// Unable to start the stream. Set the running state to false.
isRunning = false
}
}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 |
Cited implementation, SwiftUI, CaptureSampleApp |
CaptureSample/ScreenRecorder.swift |
Cited implementation, @MainActor, AudioLevelsProvider, ScreenRecorder, CaptureType, DynamicRangePreset, SCScreenRecordingError |
CaptureSample/PowerMeter.swift |
AudioLevelProvider, Cited implementation, AudioLevels, PowerMeter, PowerLevels, MeterTable |
CaptureSample/CaptureEngine.swift |
Cited implementation, Sendable or @Sendable, DispatchQueue(label:), async declaration or closure, ScreenCaptureKit, Combine, OSLog, CapturedFrame, CaptureEngine, CaptureEngineStreamOutput |
CaptureSample/Views/ConfigurationView.swift |
Cited implementation, ConfigurationView, HeaderView |
CaptureSample/ContentView.swift |
Task, SwiftUI state property wrapper, ContentView, ContentView_Previews |
CaptureSample/AudioPlayer.swift |
ObservableObject, @Published, Foundation, AudioPlayer |
CaptureSample/Views/PickerSettingsView.swift |
PickerSettingsView, BundleIDsListView |
CaptureSample/Views/AudioLevelsView.swift |
AudioLevelsView |
CaptureSample/Views/MaterialView.swift |
MaterialView |
CaptureSample/Views/CapturePreview.swift |
CapturePreview, CaptureVideoPreview |