Skip to content

Record your screen, ship a demo. Free and open-source, GPU-accelerated, no watermarks, no subscriptions. Windows, macOS, Linux. Actively maintained.

fix(recording): advance the macOS audio timeline on the clock, not on the data

EtienneLescot714280677eb4
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index ee9f3f0e7..cad5e99db 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -284,6 +284,41 @@ jobs:
cd crates
cargo build -p compositor-view-napi --release
+ # The macOS capture helper had NO job on any pull request — not a build, not a test.
+ # `build.yml` compiles it, and build.yml triggers only on `push: tags: v*` or
+ # workflow_dispatch, so a Swift file that did not compile surfaced when someone cut a
+ # release rather than when they pushed it. That is the same gap `rust-windows-compositor-
+ # check` above was added to close for the Windows compositor.
+ #
+ # `swift test`, not just `swift build`, and the difference is the reason this job exists
+ # at all. PR #343 changed how audio is placed on the recording timeline and shipped 301
+ # lines of Swift tests beside the change; not one of them ever ran, because no workflow
+ # invoked `swift test` and nothing under `electron/native/screencapturekit/Tests` was
+ # executed on any pull request. A change to recording timing that no measurement can
+ # contradict is not one to merge into a shipped capture path, so the measurement runs here.
+ #
+ # `AudioTrackMixerTests` needs no screen, no display server and no TCC grant: the mixer
+ # takes its sink and its clock as parameters, so the tests drive it with a collecting sink
+ # and a hand-moved clock. That is what makes "does a sound land where it happened"
+ # answerable on a headless runner. The other half of that question — the one that needs a
+ # real display, a real tap and a real speaker — is `npm run test:sck-audio-timeline:mac`,
+ # which cannot run here and is run by hand.
+ #
+ # macos-14 for the same reason the compositor job uses it: Apple Silicon, matching what
+ # ships. The release build runs too, because the executable targets are not covered by the
+ # test target and `-c release` is what `build:native:mac` actually produces.
+ swift-macos-helper:
+ name: Swift test (macOS capture helper)
+ runs-on: macos-14
+ steps:
+ - uses: actions/checkout@v7
+ - name: Show toolchain
+ run: swift --version
+ - name: swift test (capture core)
+ run: swift test --package-path electron/native/screencapturekit
+ - name: swift build (release, both helpers)
+ run: swift build -c release --package-path electron/native/screencapturekit
+
semantic-pr:
name: Validate PR title (semantic)
runs-on: ubuntu-latest
diff --git a/electron/native/screencapturekit/Package.swift b/electron/native/screencapturekit/Package.swift
index ec3b1d98d..b865f8ae6 100644
--- a/electron/native/screencapturekit/Package.swift
+++ b/electron/native/screencapturekit/Package.swift
@@ -18,13 +18,28 @@ let package = Package(
)
],
targets: [
+ // The parts of the helper that are testable without a screen, a display server or a
+ // TCC grant. A library rather than files in the executable target because a test
+ // target cannot link an executable's `@main` — and until this split existed nothing
+ // under this package could be tested at all, which is how PR #343 came to carry 301
+ // lines of Swift tests that no pull request ever ran.
+ .target(
+ name: "OpenScreenCaptureCore",
+ path: "Sources/OpenScreenCaptureCore"
+ ),
.executableTarget(
name: "OpenScreenScreenCaptureKitHelper",
+ dependencies: ["OpenScreenCaptureCore"],
path: "Sources/OpenScreenScreenCaptureKitHelper"
),
.executableTarget(
name: "OpenScreenMacOSCursorHelper",
path: "Sources/OpenScreenMacOSCursorHelper"
+ ),
+ .testTarget(
+ name: "OpenScreenCaptureCoreTests",
+ dependencies: ["OpenScreenCaptureCore"],
+ path: "Tests/OpenScreenCaptureCoreTests"
)
]
)
diff --git a/electron/native/screencapturekit/Sources/OpenScreenScreenCaptureKitHelper/AudioTrackMixer.swift b/electron/native/screencapturekit/Sources/OpenScreenCaptureCore/AudioTrackMixer.swift
similarity index 63%
rename from electron/native/screencapturekit/Sources/OpenScreenScreenCaptureKitHelper/AudioTrackMixer.swift
rename to electron/native/screencapturekit/Sources/OpenScreenCaptureCore/AudioTrackMixer.swift
index e193fb67d..51e2bdbeb 100644
--- a/electron/native/screencapturekit/Sources/OpenScreenScreenCaptureKitHelper/AudioTrackMixer.swift
+++ b/electron/native/screencapturekit/Sources/OpenScreenCaptureCore/AudioTrackMixer.swift
@@ -2,6 +2,26 @@ import AVFoundation
import CoreMedia
import Foundation
+/// Where the mixed track goes. `AVAssetWriterInput` satisfies this as it stands, with no
+/// adapter — the protocol exists so `swift test` can drive the mixer without a writer, a file,
+/// or an AAC encoder in the way, and read back the exact frames and presentation timestamps it
+/// produced. Measuring the timeline through an encoder would fold AAC's priming delay into
+/// every assertion; measuring it here is exact.
+public protocol MixedAudioSink: AnyObject {
+ var isReadyForMoreMediaData: Bool { get }
+ @discardableResult
+ func append(_ sampleBuffer: CMSampleBuffer) -> Bool
+}
+
+extension AVAssetWriterInput: MixedAudioSink {}
+
+/// The instant the writer's timeline has reached, in the writer's own time domain — the domain
+/// the session start and every sample's presentation timestamp already live in.
+///
+/// Frozen while the recording is paused, so that a pause stops the audio clock rather than
+/// resetting it: what follows keeps the position it would have had.
+public typealias TimelineClock = () -> CMTime
+
/// Sums system audio and the microphone into the single AAC track the helper muxes.
///
/// The helper used to give AVAssetWriter one input per source, so a recording with both
@@ -16,15 +36,25 @@ import Foundation
/// The two sources run off independent clocks, so samples are placed on a shared timeline by
/// presentation timestamp rather than by arrival order: a source that starts late, drifts, or
/// drops buffers lands at the offset it belongs at instead of shoving everything after it out
-/// of sync. A chunk goes out as soon as every live source covers it — or, once some other
-/// source has run `stallToleranceFrames` past it, without it, so a microphone that goes quiet
-/// or disappears mid-recording can never stall the track.
+/// of sync.
+///
+/// **The cursor advances on the clock, not on the data.** Chunks go out for as long as the take
+/// runs, filled from whichever source covers them and with silence where none does. Inferring
+/// the position from arrivals instead is the bug this mirrors from Windows (`7e6cde3f`,
+/// getopenscreen/openscreen#406): there the emit counter only moved while a queue held samples,
+/// so a take beginning in silence emitted nothing and the first sound landed at timestamp zero.
+/// Here the same inference lived in the anchor — it was set lazily on the first decoded buffer
+/// to `max(firstPresentationTime, sessionStart)`, so audio that first arrived four seconds in
+/// made frame zero of the mixed track *be* four seconds in, and the leading silence was simply
+/// absent from the file. Anchoring to the session start and letting the clock carry the cursor
+/// covers the leading silence, the trailing silence and mid-take gaps with one mechanism, and
+/// shifts no source relative to any other.
///
/// Not thread-safe by design: every entry point runs on the recorder's serial sample queue,
-/// which is also the queue ScreenCaptureKit delivers both audio outputs on.
-@available(macOS 13.0, *)
-final class AudioTrackMixer {
- enum Source: Int, CaseIterable {
+/// which is also the queue ScreenCaptureKit delivers both audio outputs on and the queue the
+/// recorder's tick timer fires on.
+public final class AudioTrackMixer {
+ public enum Source: Int, CaseIterable {
case system = 0
case microphone = 1
}
@@ -37,13 +67,28 @@ final class AudioTrackMixer {
static let bytesPerFrame = channelCount * MemoryLayout<Int16>.size
/// 10 ms — the chunk size the Windows mixer emits too.
static let chunkFrames = sampleRate / 100
- /// How far ahead one source may run before the ones lagging behind it are written off
- /// as stalled and the chunk goes out without them. Two orders of magnitude above the
- /// delivery skew between two outputs of the same SCStream, so ordinary jitter never
- /// trips it; the file is written offline, so the latency it buys back costs nothing.
- static let stallToleranceFrames = sampleRate / 4
- /// Longest hole a source may silence-pad across. Past this the source has been dead
- /// long enough that padding would materialize however long the outage lasted.
+ /// How long a source may deliver nothing at all before it is written off and chunks go
+ /// out without it.
+ ///
+ /// Measured from that source's own last delivery, and deliberately not from how far
+ /// behind the clock its coverage is. Those differ for a source that is alive but
+ /// arriving late, and the difference is the whole take: a capture path whose buffers
+ /// reach us a fixed delay after the audio they describe would be permanently "behind",
+ /// so writing it off for that would emit silence, drop the real samples as
+ /// already-passed, and do it again for every chunk. Asking "has it stopped delivering"
+ /// instead is immune to any constant latency, and it is the actual question — a dead
+ /// microphone stops, a slow one does not.
+ ///
+ /// Nothing is shifted by this number and no sample moves because of it; it only decides
+ /// when to stop waiting. That is what separates it from the bounded start-up rebase in
+ /// PR #343, where the same 250 ms moved real audio. The value is two orders of magnitude
+ /// above the ~2.5 ms delivery skew between two outputs of the same SCStream, so ordinary
+ /// jitter never trips it, and the file is written offline, so the latency it costs at a
+ /// transition into silence costs the recording nothing.
+ static let emissionGraceFrames = sampleRate / 4
+ /// Longest hole a source may silence-pad across. Past this the source has been dead long
+ /// enough that padding would materialize however long the outage lasted — the cursor
+ /// carries the track across the gap instead.
static let maxSilencePadFrames = sampleRate * 2
/// Writer backpressure allowance, in chunks (5 s). `expectsMediaDataInRealTime` keeps
/// this at zero or one in practice; the cap only bounds a pathological writer stall.
@@ -52,29 +97,37 @@ final class AudioTrackMixer {
static let finalFlushTimeout = 5.0
}
- private let input: AVAssetWriterInput
+ private let input: MixedAudioSink
+ private let clock: TimelineClock
private let includesSystemAudio: Bool
private let includesMicrophone: Bool
private let microphoneGain: Float
private let outputFormatDescription: CMAudioFormatDescription?
private var sources = [SourceTimeline](repeating: SourceTimeline(), count: Source.allCases.count)
- private var sessionStart: CMTime?
- /// Timeline origin: frame 0 of the mixed track, in the writer's time domain.
+ /// Timeline origin: frame 0 of the mixed track, in the writer's time domain. Set once,
+ /// eagerly, to the writer's session start — never inferred from a buffer.
private var anchor: CMTime?
/// Absolute frame index of the next chunk to emit.
private var cursor: Int64 = 0
+ /// Frames emitted for which a given source contributed nothing. This is the measurement
+ /// that answers whether ScreenCaptureKit's system-audio output is silence-gapped the way the
+ /// WASAPI loopback tap is: on a take where nothing plays, a gapped tap leaves this equal to
+ /// the whole track and a continuously-streaming one leaves it near zero.
+ private var uncoveredFrames = [Int64](repeating: 0, count: Source.allCases.count)
private var pending: [CMSampleBuffer] = []
private var didWarnAboutBacklog = false
private var didWarnAboutDecode: Set<Int> = []
- init(
- input: AVAssetWriterInput,
+ public init(
+ input: MixedAudioSink,
includesSystemAudio: Bool,
includesMicrophone: Bool,
- microphoneGain: Double
+ microphoneGain: Double,
+ clock: @escaping TimelineClock
) {
self.input = input
+ self.clock = clock
self.includesSystemAudio = includesSystemAudio
self.includesMicrophone = includesMicrophone
// The request carries MIC_GAIN_BOOST (1.4); Windows applies it unconditionally and so
@@ -84,22 +137,29 @@ final class AudioTrackMixer {
self.outputFormatDescription = Self.makeOutputFormatDescription()
}
- /// Anchors the mixer to the writer session. Audio delivered before this is dropped — the
- /// writer would reject anything ahead of its session start anyway.
- func beginTimeline(at sessionStart: CMTime) {
- guard self.sessionStart == nil, sessionStart.isValid else {
+ /// Anchors frame 0 of the mixed track to the writer session start.
+ ///
+ /// Eagerly, and to the session start itself: audio that arrives before it is trimmed at
+ /// frame zero rather than moving the origin, and audio that arrives long after it lands at
+ /// the offset it belongs at with real silence in front of it.
+ public func beginTimeline(at sessionStart: CMTime) {
+ guard anchor == nil, sessionStart.isValid, sessionStart.isNumeric else {
return
}
- self.sessionStart = sessionStart
+ anchor = CMTimeConvertScale(
+ sessionStart,
+ timescale: CMTimeScale(MixFormat.sampleRate),
+ method: .roundHalfAwayFromZero
+ )
}
- func ingest(_ sampleBuffer: CMSampleBuffer, from source: Source) {
- guard includes(source), let sessionStart else {
+ public func ingest(_ sampleBuffer: CMSampleBuffer, from source: Source) {
+ guard includes(source), let anchor else {
return
}
let presentationTime = CMSampleBufferGetPresentationTimeStamp(sampleBuffer)
- guard presentationTime.isValid else {
+ guard presentationTime.isValid, presentationTime.isNumeric else {
return
}
guard let frames = decodeInterleavedStereo(sampleBuffer, gain: gain(for: source)),
@@ -111,30 +171,38 @@ final class AudioTrackMixer {
return
}
- if anchor == nil {
- anchor = CMTimeConvertScale(
- CMTimeMaximum(presentationTime, sessionStart),
- timescale: CMTimeScale(MixFormat.sampleRate),
- method: .roundHalfAwayFromZero
- )
- }
- guard let anchor else {
+ let now = clock()
+ sources[source.rawValue].ingest(
+ frames,
+ atFrame: frameIndex(of: presentationTime, from: anchor)
+ )
+ // Where the clock stood when this source last said anything — not where its samples
+ // sit. See `emissionGraceFrames`.
+ sources[source.rawValue].lastDeliveryFrame = frameIndex(of: now, from: anchor)
+ drain(upTo: now, grace: Int64(MixFormat.emissionGraceFrames))
+ }
+
+ /// Advances the cursor to wherever the clock now stands, emitting silence for anything no
+ /// source covered. Called on a timer, because a take that nothing is delivering audio for is
+ /// exactly the take whose timeline has to keep moving.
+ public func tick() {
+ guard anchor != nil else {
return
}
-
- let offset = CMTimeConvertScale(
- CMTimeSubtract(presentationTime, anchor),
- timescale: CMTimeScale(MixFormat.sampleRate),
- method: .roundHalfAwayFromZero
- )
- sources[source.rawValue].ingest(frames, atFrame: offset.value)
- drain(flushing: false)
+ drain(upTo: clock(), grace: Int64(MixFormat.emissionGraceFrames))
}
- /// Writes out everything still buffered. Call once, on the sample queue, before the
- /// writer input is marked as finished.
- func finish() {
- drain(flushing: true)
+ /// Carries the track out to the end of the take and writes out everything still buffered.
+ /// Call once, on the sample queue, before the writer input is marked as finished — and pass
+ /// the same source time the writer's `endSession` is given, so the audio track and the
+ /// container agree on where the recording ended.
+ public func finish(atSourceTime end: CMTime) {
+ if anchor != nil {
+ // No grace: capture has stopped, so a source that has not covered a chunk by now
+ // never will, and waiting on it would only truncate the tail.
+ drain(upTo: end, grace: 0)
+ emitTimelineSummary()
+ }
flushPending(force: true)
}
@@ -160,6 +228,41 @@ final class AudioTrackMixer {
])
}
+ /// Reports how much of the finished track each source actually covered.
+ ///
+ /// Not diagnostics for their own sake: nothing in the tree recorded whether
+ /// ScreenCaptureKit's system-audio output goes silent-but-delivering or stops delivering
+ /// altogether while nothing is playing, and the answer decides how much of the timeline the
+ /// clock is carrying on its own. One take with system audio enabled and nothing playing
+ /// settles it — `systemUncoveredSeconds` comes back as the whole track if the tap is gapped
+ /// the way WASAPI loopback is, and near zero if it streams silence.
+ private func emitTimelineSummary() {
+ var fields: [String: Any] = [
+ "event": "audio-timeline",
+ "code": "audio-timeline-summary",
+ "trackSeconds": seconds(cursor),
+ ]
+ if includesSystemAudio {
+ fields["systemUncoveredSeconds"] = seconds(uncoveredFrames[Source.system.rawValue])
+ }
+ if includesMicrophone {
+ fields["microphoneUncoveredSeconds"] = seconds(uncoveredFrames[Source.microphone.rawValue])
+ }
+ emit(fields)
+ }
+
+ private func seconds(_ frames: Int64) -> Double {
+ Double(frames) / Double(MixFormat.sampleRate)
+ }
+
+ private func frameIndex(of time: CMTime, from anchor: CMTime) -> Int64 {
+ CMTimeConvertScale(
+ CMTimeSubtract(time, anchor),
+ timescale: CMTimeScale(MixFormat.sampleRate),
+ method: .roundHalfAwayFromZero
+ ).value
+ }
+
private func includes(_ source: Source) -> Bool {
switch source {
case .system:
@@ -178,60 +281,71 @@ final class AudioTrackMixer {
}
}
- /// Emits every chunk that is ready. A chunk is ready once all live sources cover it; when
- /// one source has run far enough ahead of another, the laggard is marked stalled and the
- /// chunk goes out with silence in its place. That is what keeps a dead microphone — or a
- /// system-audio device that stops delivering — from blocking the whole track.
- private func drain(flushing: Bool) {
+ /// Emits every chunk the clock has passed.
+ ///
+ /// Two ways a chunk goes out. Normally it goes out as soon as every live source covers it,
+ /// which costs no latency at all. Otherwise it goes out once every source still missing
+ /// from it has gone `grace` without delivering anything — the case a purely data-driven
+ /// mixer has no answer for, because when no source is delivering there is nothing to
+ /// measure against. The clock supplies that reference whether one source has gone quiet,
+ /// both have, or neither has ever delivered a single buffer.
+ ///
+ /// `chunkEnd <= limitFrame` bounds the loop: a chunk covering time that has not happened yet
+ /// is never emitted, so the cursor can never outrun the take.
+ private func drain(upTo limit: CMTime, grace: Int64) {
+ guard let anchor, limit.isValid, limit.isNumeric else {
+ return
+ }
+ let limitFrame = frameIndex(of: limit, from: anchor)
+
while true {
- let delivered = sources.indices.filter { sources[$0].hasDelivered }
- guard let furthest = delivered.map({ sources[$0].endFrame }).max(), furthest > cursor else {
+ let chunkEnd = cursor + Int64(MixFormat.chunkFrames)
+ guard chunkEnd <= limitFrame else {
break
}
- let chunkEnd = cursor + Int64(MixFormat.chunkFrames)
- let live = delivered.filter { !sources[$0].isStalled }
- let complete = live.allSatisfy { sources[$0].endFrame >= chunkEnd }
- if !complete && !flushing {
- if furthest < chunkEnd + Int64(MixFormat.stallToleranceFrames) {
+ let live = sources.indices.filter { sources[$0].hasDelivered && !sources[$0].isStalled }
+ let laggards = live.filter { sources[$0].endFrame < chunkEnd }
+ if !laggards.isEmpty {
+ guard laggards.allSatisfy({ limitFrame >= sources[$0].lastDeliveryFrame + grace })
+ else {
break
}
- for index in live where sources[index].endFrame < chunkEnd {
+ // …and each stays stalled until its next buffer arrives, so one source going
+ // quiet can never hold the track back chunk after chunk.
+ for index in laggards {
sources[index].isStalled = true
}
}
- // emitChunk always advances the cursor when it can; bailing out on the one case
- // where it cannot is what stops this loop from spinning forever.
- guard emitChunk() else {
- break
- }
+ emitChunk()
}
}
- @discardableResult
- private func emitChunk() -> Bool {
- guard let anchor else {
- return false
- }
-
+ private func emitChunk() {
var mix = [Float](repeating: 0, count: MixFormat.chunkFrames * MixFormat.channelCount)
for index in sources.indices {
- sources[index].drain(into: &mix, from: cursor, frameCount: MixFormat.chunkFrames)
+ let contributed = sources[index].drain(
+ into: &mix,
+ from: cursor,
+ frameCount: MixFormat.chunkFrames
+ )
+ if let source = Source(rawValue: index), includes(source) {
+ uncoveredFrames[index] += Int64(MixFormat.chunkFrames - contributed)
+ }
}
let presentationTime = CMTimeAdd(
- anchor,
+ anchor ?? .zero,
CMTime(value: cursor, timescale: CMTimeScale(MixFormat.sampleRate))
)
cursor += Int64(MixFormat.chunkFrames)
guard let sampleBuffer = makeSampleBuffer(from: mix, at: presentationTime) else {
- return true
+ return
}
pending.append(sampleBuffer)
flushPending(force: false)
- return true
}
/// `append` is not advisory backpressure — it raises an NSException when the input is not
@@ -521,14 +635,19 @@ final class AudioTrackMixer {
}
/// One source's pending samples, positioned on the shared timeline: `startFrame` is the
- /// absolute frame index of the first frame in `samples`.
+ /// absolute frame index of the first frame in `samples`. A negative index is ordinary — that
+ /// is audio captured before the writer session started, and `dropFrames` trims it at frame
+ /// zero rather than letting it move the origin.
private struct SourceTimeline {
private(set) var samples: [Float] = []
private(set) var startFrame: Int64 = 0
/// A source only counts towards "is this chunk complete" once it has produced audio…
private(set) var hasDelivered = false
- /// …and stops counting the moment it misses a chunk the others already covered.
+ /// …and stops counting once it has gone `emissionGraceFrames` without producing any.
var isStalled = false
+ /// Where the clock stood at this source's most recent delivery, in absolute frames.
+ /// The mixer sets it, because only the mixer holds the clock.
+ var lastDeliveryFrame: Int64 = 0
var endFrame: Int64 { startFrame + Int64(samples.count / MixFormat.channelCount) }
@@ -547,7 +666,7 @@ final class AudioTrackMixer {
if gapFrames > MixFormat.maxSilencePadFrames {
// Nothing arrived for seconds. Zero-filling the hole would allocate however
// long the outage lasted, so restart here instead and let the mixer's own
- // catch-up carry the track across; the stale pending samples go with it.
+ // clock carry the track across; the stale pending samples go with it.
startFrame = frameIndex
samples = frames
return
@@ -568,21 +687,23 @@ final class AudioTrackMixer {
samples.append(contentsOf: frames[overlap...])
}
- /// Adds this source's contribution to one chunk and consumes it. Frames the source
- /// doesn't cover are simply left alone — `mix` already holds silence there.
- mutating func drain(into mix: inout [Float], from cursor: Int64, frameCount: Int) {
+ /// Adds this source's contribution to one chunk and consumes it, returning how many of
+ /// the chunk's frames it actually covered. Frames it doesn't cover are simply left
+ /// alone — `mix` already holds silence there.
+ @discardableResult
+ mutating func drain(into mix: inout [Float], from cursor: Int64, frameCount: Int) -> Int {
dropFrames(before: cursor)
guard !samples.isEmpty else {
- return
+ return 0
}
let lead = Int(startFrame - cursor)
guard lead < frameCount else {
- return
+ return 0
}
let usableFrames = min(frameCount - lead, samples.count / MixFormat.channelCount)
guard usableFrames > 0 else {
- return
+ return 0
}
let base = lead * MixFormat.channelCount
@@ -591,6 +712,7 @@ final class AudioTrackMixer {
}
samples.removeFirst(usableFrames * MixFormat.channelCount)
startFrame += Int64(usableFrames)
+ return usableFrames
}
/// Discards samples the mixer has already emitted past — a buffer that arrived after
diff --git a/electron/native/screencapturekit/Sources/OpenScreenCaptureCore/HelperOutput.swift b/electron/native/screencapturekit/Sources/OpenScreenCaptureCore/HelperOutput.swift
new file mode 100644
index 000000000..eae4fb690
--- /dev/null
+++ b/electron/native/screencapturekit/Sources/OpenScreenCaptureCore/HelperOutput.swift
@@ -0,0 +1,22 @@
+import Foundation
+
+/// The helper's whole protocol with the app: one JSON object per line on stdout.
+///
+/// Lives in the core library rather than beside the recorder because `AudioTrackMixer`
+/// reports through it too, and the mixer is what `swift test` builds against.
+public func emit(_ fields: [String: Any]) {
+ if let data = try? JSONSerialization.data(withJSONObject: fields, options: []),
+ let line = String(data: data, encoding: .utf8)
+ {
+ print(line)
+ fflush(stdout)
+ }
+}
+
+public func emitError(code: String, message: String) {
+ emit([
+ "event": "error",
+ "code": code,
+ "message": message,
+ ])
+}
diff --git a/electron/native/screencapturekit/Sources/OpenScreenScreenCaptureKitHelper/ScreenCaptureRecorder.swift b/electron/native/screencapturekit/Sources/OpenScreenScreenCaptureKitHelper/ScreenCaptureRecorder.swift
index c5e191056..47ef67261 100644
--- a/electron/native/screencapturekit/Sources/OpenScreenScreenCaptureKitHelper/ScreenCaptureRecorder.swift
+++ b/electron/native/screencapturekit/Sources/OpenScreenScreenCaptureKitHelper/ScreenCaptureRecorder.swift
@@ -2,6 +2,7 @@ import AVFoundation
import CoreGraphics
import CoreMedia
import Foundation
+import OpenScreenCaptureCore
import ScreenCaptureKit
struct Rectangle: Decodable {
@@ -101,23 +102,6 @@ enum HelperError: Error, CustomStringConvertible {
}
}
-func emit(_ fields: [String: Any]) {
- if let data = try? JSONSerialization.data(withJSONObject: fields, options: []),
- let line = String(data: data, encoding: .utf8)
- {
- print(line)
- fflush(stdout)
- }
-}
-
-func emitError(code: String, message: String) {
- emit([
- "event": "error",
- "code": code,
- "message": message,
- ])
-}
-
@available(macOS 13.0, *)
final class ScreenCaptureRecorder: NSObject, SCStreamOutput, SCStreamDelegate {
private struct CaptureTarget {
@@ -139,6 +123,9 @@ final class ScreenCaptureRecorder: NSObject, SCStreamOutput, SCStreamDelegate {
// audio track 0 and nothing else. See AudioTrackMixer.
private var audioInput: AVAssetWriterInput?
private var audioMixer: AudioTrackMixer?
+ /// Drives the mixer's cursor while nothing is arriving to drive it. Owned by the sample
+ /// queue: created when the writer session opens, cancelled on the same queue at teardown.
+ private var audioTicker: DispatchSourceTimer?
private var didStartWriting = false
private var didEmitRecordingStarted = false
private var didReportWriterFailure = false
@@ -307,6 +294,7 @@ final class ScreenCaptureRecorder: NSObject, SCStreamOutput, SCStreamDelegate {
writer.startSession(atSourceTime: presentationTime)
didStartWriting = true
audioMixer?.beginTimeline(at: presentationTime)
+ startAudioTicker()
}
if videoInput.isReadyForMoreMediaData {
@@ -537,20 +525,76 @@ final class ScreenCaptureRecorder: NSObject, SCStreamOutput, SCStreamDelegate {
input: input,
includesSystemAudio: request.audio.system.enabled,
includesMicrophone: nativeMicrophoneEnabled,
- microphoneGain: request.audio.microphone.gain
+ microphoneGain: request.audio.microphone.gain,
+ clock: { [weak self] in self?.timelineNow() ?? .invalid }
)
}
}
+ /// The instant the writer's timeline has reached: the host clock, less the time spent
+ /// paused — the same transform `retimedSampleBuffer` applies to every sample, so this and
+ /// the presentation timestamps are answers in one domain.
+ ///
+ /// Frozen while paused, because `pauseStartedAt` stops moving and `totalPausedDuration`
+ /// does not yet include the pause in progress. On resume the offset grows by exactly the
+ /// pause, so the position continues from where it froze: the pause interrupts the audio
+ /// clock without shifting anything recorded after it. That is the same property the
+ /// Windows mixer gets by re-deriving its anchor on resume, derived here instead of tracked.
+ private func timelineNow() -> CMTime {
+ let (paused, offset, pausedAt) = stateQueue.sync {
+ (isPaused, totalPausedDuration, pauseStartedAt)
+ }
+ let now = paused ? (pausedAt ?? CMClockGetTime(hostClock)) : CMClockGetTime(hostClock)
+ return CMTimeSubtract(now, offset)
+ }
+
+ /// A take that nothing is playing into is exactly the take whose audio timeline has to keep
+ /// moving, so the mixer cannot be driven by buffer arrival alone. 10 ms is the chunk size it
+ /// emits at; the leeway lets the system coalesce the wakeups, since being a few milliseconds
+ /// late only means the next tick emits two chunks instead of one.
+ private func startAudioTicker() {
+ guard audioMixer != nil, audioTicker == nil else {
+ return
+ }
+
+ let timer = DispatchSource.makeTimerSource(queue: sampleQueue)
+ timer.schedule(
+ deadline: .now() + .milliseconds(10),
+ repeating: .milliseconds(10),
+ leeway: .milliseconds(5)
+ )
+ timer.setEventHandler { [weak self] in
+ self?.audioMixer?.tick()
+ }
+ audioTicker = timer
+ timer.resume()
+ }
+
private func finishWriter() async {
guard let writer else {
return
}
// Capture has stopped, so nothing is in flight on the sample queue any more; hopping
- // onto it once is what makes the mixer's final flush safe without a lock.
+ // onto it once is what makes the mixer's final flush safe without a lock, and it is
+ // also where the ticker has to die, since that is the queue it fires on.
+ //
+ // `endSession` is the trailing half of the same bug the clock-driven cursor fixes at
+ // the front. Without it the file ended at the last sample anything happened to deliver,
+ // so a ten-second take that went quiet at six yielded a six-second recording; the
+ // helper had never called it at all. `end` comes from the same clock the mixer runs on
+ // and is read after `stopCapture()` returned, so it is at or past every sample already
+ // appended — which is what makes it safe to hand to `endSession`, since a source time
+ // before an appended sample would trim that sample back out.
sampleQueue.sync {
- audioMixer?.finish()
+ audioTicker?.cancel()
+ audioTicker = nil
+
+ let end = timelineNow()
+ audioMixer?.finish(atSourceTime: end)
+ if didStartWriting, writer.status == .writing {
+ writer.endSession(atSourceTime: end)
+ }
}
videoInput?.markAsFinished()
diff --git a/electron/native/screencapturekit/Tests/OpenScreenCaptureCoreTests/AudioTrackMixerTests.swift b/electron/native/screencapturekit/Tests/OpenScreenCaptureCoreTests/AudioTrackMixerTests.swift
new file mode 100644
index 000000000..a3ed536d9
--- /dev/null
+++ b/electron/native/screencapturekit/Tests/OpenScreenCaptureCoreTests/AudioTrackMixerTests.swift
@@ -0,0 +1,599 @@
+import AVFoundation
+import CoreMedia
+import Foundation
+import XCTest
+
+import OpenScreenCaptureCore
+
+/// Does a sound land where it happened, and does the track cover the whole take?
+///
+/// These drive `AudioTrackMixer` through a sink that keeps the mixed buffers instead of a
+/// writer that encodes them, and through a clock the test moves by hand instead of the host
+/// clock. Both substitutions are what make the assertions exact: an AAC encoder would fold its
+/// priming delay into every timestamp, and a real clock would make "four seconds in" mean
+/// "four seconds in, give or take the scheduler".
+///
+/// `scripts/test-macos-audio-timeline.mjs` asks the same questions of the real helper, with a
+/// real tone through the real speakers. That one measures the machine; this one measures the
+/// code, and is the half that can run on a pull request.
+final class AudioTrackMixerTests: XCTestCase {
+ private let sampleRate = 48_000
+ private let channelCount = 2
+ /// Well above the Int16 quantization floor, well below the 0.5 bursts these feed in.
+ private let audibleThreshold: Int16 = 1_000
+
+ // MARK: - Leading silence
+
+ /// The regression that closed PR #343 and the one Windows fixed in `7e6cde3f`: a take that
+ /// begins in silence used to anchor frame zero to the first buffer that showed up, so a
+ /// sound played four seconds in was heard from the very start and the track came out four
+ /// seconds short.
+ func testLeadingSilenceIsInTheFileRatherThanSkipped() {
+ let sink = RecordingSink()
+ let clock = TestClock(CMTime(value: 50, timescale: 1))
+ let mixer = makeMixer(sink: sink, clock: clock, includesMicrophone: false)
+ mixer.beginTimeline(at: clock.now)
+
+ // Four seconds of nothing at all — no buffer from any source.
+ clock.advance(seconds: 4)
+ mixer.tick()
+
+ mixer.ingest(
+ makeSourceBuffer(
+ burst(seconds: 0.5, left: 0.5, right: 0.5),
+ at: clock.now,
+ nonInterleaved: true
+ ),
+ from: .system
+ )
+ clock.advance(seconds: 0.5)
+ mixer.tick()
+ clock.advance(seconds: 1.5)
+ mixer.finish(atSourceTime: clock.now)
+
+ let frames = mixedFrames(sink)
+ XCTAssertEqual(sink.buffers.first?.presentationTimeStamp, CMTime(value: 50, timescale: 1))
+ assertContiguous(sink)
+ XCTAssertEqual(seconds(ofFrames: frames), 6.0, accuracy: 0.011)
+ XCTAssertEqual(firstAudibleSecond(frames) ?? -1, 4.0, accuracy: 0.001)
+ XCTAssertEqual(peak(frames, from: 0, to: 4.0), 0, "the leading silence has to be silent")
+ }
+
+ /// The other half of the same anchor: audio captured *before* the writer session started is
+ /// trimmed at frame zero. Moving the origin back to meet it would drag the whole take with
+ /// it, and the writer would reject it anyway.
+ func testAudioBeforeTheSessionStartIsTrimmedRatherThanMovingTheOrigin() {
+ let sink = RecordingSink()
+ let sessionStart = CMTime(value: 50, timescale: 1)
+ let clock = TestClock(sessionStart)
+ let mixer = makeMixer(sink: sink, clock: clock, includesMicrophone: false)
+ mixer.beginTimeline(at: sessionStart)
+
+ // 200 ms of audio, half of it captured before the session opened.
+ mixer.ingest(
+ makeSourceBuffer(
+ burst(seconds: 0.2, left: 0.5, right: 0.5),
+ at: CMTimeSubtract(sessionStart, CMTime(value: 100, timescale: 1_000)),
+ nonInterleaved: true
+ ),
+ from: .system
+ )
+ clock.advance(seconds: 0.1)
+ mixer.finish(atSourceTime: clock.now)
+
+ let frames = mixedFrames(sink)
+ XCTAssertEqual(sink.buffers.first?.presentationTimeStamp, sessionStart)
+ XCTAssertEqual(seconds(ofFrames: frames), 0.1, accuracy: 0.011)
+ XCTAssertGreaterThan(peak(frames, from: 0, to: 0.1), audibleThreshold)
+ }
+
+ // MARK: - Trailing silence
+
+ /// `drain()` used to run only from `ingest` and `finish`, and nothing called
+ /// `endSession(atSourceTime:)`, so the track ended at the last sample anything delivered.
+ /// A ten-second take that went quiet at two seconds produced two seconds of audio.
+ func testTrailingSilenceIsInTheFileRatherThanTruncated() {
+ let sink = RecordingSink()
+ let clock = TestClock(.zero)
+ let mixer = makeMixer(sink: sink, clock: clock, includesMicrophone: false)
+ mixer.beginTimeline(at: clock.now)
+
+ mixer.ingest(
+ makeSourceBuffer(burst(seconds: 2, left: 0.5, right: 0.5), at: clock.now, nonInterleaved: true),
+ from: .system
+ )
+ clock.advance(seconds: 2)
+ mixer.tick()
+
+ // Eight more seconds of take, with the source delivering nothing at all.
+ clock.advance(seconds: 8)
+ mixer.finish(atSourceTime: clock.now)
+
+ let frames = mixedFrames(sink)
+ assertContiguous(sink)
+ XCTAssertEqual(seconds(ofFrames: frames), 10.0, accuracy: 0.011)
+ XCTAssertGreaterThan(peak(frames, from: 0, to: 2.0), audibleThreshold)
+ XCTAssertEqual(peak(frames, from: 2.5, to: 10.0), 0, "the trailing silence has to be silent")
+ }
+
+ /// The worst case if ScreenCaptureKit's system-audio output turns out to be silence-gapped
+ /// the way the WASAPI loopback tap is: nothing is ever delivered, and the take still has to
+ /// come out as a full-length silent track rather than as no audio track at all.
+ func testATakeThatDeliversNoAudioAtAllStillSpansTheWholeRecording() {
+ let sink = RecordingSink()
+ let clock = TestClock(.zero)
+ let mixer = makeMixer(sink: sink, clock: clock, includesMicrophone: false)
+ mixer.beginTimeline(at: clock.now)
+
+ clock.advance(seconds: 3)
+ mixer.finish(atSourceTime: clock.now)
+
+ let frames = mixedFrames(sink)
+ assertContiguous(sink)
+ XCTAssertEqual(seconds(ofFrames: frames), 3.0, accuracy: 0.011)
+ XCTAssertEqual(peak(frames, from: 0, to: 3.0), 0)
+ }
+
+ // MARK: - Mid-take gaps
+
+ func testAudioAfterAMidTakeGapKeepsThePositionItHappenedAt() {
+ let sink = RecordingSink()
+ let clock = TestClock(.zero)
+ let mixer = makeMixer(sink: sink, clock: clock, includesMicrophone: false)
+ mixer.beginTimeline(at: clock.now)
+
+ mixer.ingest(
+ makeSourceBuffer(burst(seconds: 0.5, left: 0.5, right: 0.5), at: clock.now, nonInterleaved: true),
+ from: .system
+ )
+ clock.advance(seconds: 0.5)
+ mixer.tick()
+
+ // Five seconds of nothing, then the source speaks up again.
+ clock.advance(seconds: 5)
+ mixer.tick()
+ mixer.ingest(
+ makeSourceBuffer(burst(seconds: 0.5, left: 0.5, right: 0.5), at: clock.now, nonInterleaved: true),
+ from: .system
+ )
+ clock.advance(seconds: 0.5)
+ mixer.finish(atSourceTime: clock.now)
+
+ let frames = mixedFrames(sink)
+ assertContiguous(sink)
+ XCTAssertEqual(seconds(ofFrames: frames), 6.0, accuracy: 0.011)
+ XCTAssertGreaterThan(peak(frames, from: 0, to: 0.5), audibleThreshold)
+ XCTAssertEqual(peak(frames, from: 1.0, to: 5.4), 0, "the gap has to survive as silence")
+ XCTAssertGreaterThan(peak(frames, from: 5.5, to: 6.0), audibleThreshold)
+ }
+
+ // MARK: - The two sources against each other
+
+ /// PR #343 rebased each source's first buffer onto the session start independently, and its
+ /// own test asserted the consequence as intended: system audio first heard at +120 ms and
+ /// the microphone at +210 ms both moved to zero, deleting the 90 ms between them. One shared
+ /// anchor and placement by presentation timestamp keeps that 90 ms, because no source is
+ /// ever shifted by anything.
+ func testTheTwoSourcesAreNeverShiftedRelativeToEachOther() {
+ let sink = RecordingSink()
+ let sessionStart = CMTime(value: 50, timescale: 1)
+ let clock = TestClock(sessionStart)
+ let mixer = makeMixer(sink: sink, clock: clock, includesMicrophone: true, microphoneGain: 1)
+ mixer.beginTimeline(at: sessionStart)
+
+ // Left channel carries system audio, right carries the microphone, so the two onsets
+ // can be read back separately out of one mixed track.
+ mixer.ingest(
+ makeSourceBuffer(
+ burst(seconds: 0.3, left: 0.5, right: 0),
+ at: CMTimeAdd(sessionStart, CMTime(value: 120, timescale: 1_000)),
+ nonInterleaved: true
+ ),
+ from: .system
+ )
+ mixer.ingest(
+ makeSourceBuffer(
+ burst(seconds: 0.3, left: 0, right: 0.5),
+ at: CMTimeAdd(sessionStart, CMTime(value: 210, timescale: 1_000)),
+ nonInterleaved: false
+ ),
+ from: .microphone
+ )
+
+ clock.advance(seconds: 1)
+ mixer.finish(atSourceTime: clock.now)
+
+ let frames = mixedFrames(sink)
+ let systemOnset = firstAudibleSecond(frames, channel: 0)
+ let microphoneOnset = firstAudibleSecond(frames, channel: 1)
+ XCTAssertEqual(systemOnset ?? -1, 0.120, accuracy: 0.001)
+ XCTAssertEqual(microphoneOnset ?? -1, 0.210, accuracy: 0.001)
+ XCTAssertEqual((microphoneOnset ?? 0) - (systemOnset ?? 0), 0.090, accuracy: 0.002)
+ }
+
+ /// A dead microphone must not hold the track back — the whole reason the mixer marks a
+ /// source stalled rather than waiting for it. Now that lateness is measured against the
+ /// clock, this works even when the *other* source is silent too, which is the case the old
+ /// source-against-source tolerance had no answer for.
+ func testOneSourceGoingQuietDoesNotStallTheTrack() {
+ let sink = RecordingSink()
+ let clock = TestClock(.zero)
+ let mixer = makeMixer(sink: sink, clock: clock, includesMicrophone: true, microphoneGain: 1)
+ mixer.beginTimeline(at: clock.now)
+
+ // Both sources deliver 200 ms, then the microphone stops for good.
+ mixer.ingest(
+ makeSourceBuffer(burst(seconds: 0.2, left: 0.5, right: 0), at: clock.now, nonInterleaved: true),
+ from: .system
+ )
+ mixer.ingest(
+ makeSourceBuffer(burst(seconds: 0.2, left: 0, right: 0.5), at: clock.now, nonInterleaved: false),
+ from: .microphone
+ )
+ clock.advance(seconds: 0.2)
+ mixer.tick()
+
+ for _ in 0..<10 {
+ // Each buffer covers the 200 ms about to elapse, the way a live source delivers.
+ mixer.ingest(
+ makeSourceBuffer(burst(seconds: 0.2, left: 0.5, right: 0), at: clock.now, nonInterleaved: true),
+ from: .system
+ )
+ clock.advance(seconds: 0.2)
+ mixer.tick()
+ }
+ clock.advance(seconds: 0.2)
+ mixer.finish(atSourceTime: clock.now)
+
+ let frames = mixedFrames(sink)
+ XCTAssertEqual(seconds(ofFrames: frames), 2.4, accuracy: 0.011)
+ // System audio kept flowing the whole way despite the microphone never coming back.
+ XCTAssertGreaterThan(peak(frames, from: 2.0, to: 2.2, channel: 0), audibleThreshold)
+ }
+
+ /// A source that is alive but always arriving late must not be written off as stalled.
+ ///
+ /// This is the trap in driving the cursor off a clock: measure a source's lateness as the
+ /// gap between the clock and its coverage, and a capture path that delivers its buffers a
+ /// fixed delay after the audio they describe is late by that delay forever. Every chunk
+ /// would go out as silence and every real sample would then arrive too late to be placed,
+ /// so the source would be silent for the whole recording rather than merely delayed. The
+ /// grace is measured from the source's last delivery instead, which a constant latency
+ /// never trips. 400 ms here, comfortably past the 250 ms grace.
+ func testASourceThatIsAlwaysLateIsStillHeard() {
+ let sink = RecordingSink()
+ let clock = TestClock(.zero)
+ let mixer = makeMixer(sink: sink, clock: clock, includesMicrophone: false)
+ mixer.beginTimeline(at: clock.now)
+
+ clock.advance(seconds: 0.4)
+ for step in 0..<10 {
+ // The buffer describes audio from 400 ms ago; the clock is already well past it.
+ let capturedAt = CMTime(seconds: Double(step) * 0.2, preferredTimescale: 48_000)
+ mixer.ingest(
+ makeSourceBuffer(burst(seconds: 0.2, left: 0.5, right: 0.5), at: capturedAt, nonInterleaved: true),
+ from: .system
+ )
+ clock.advance(seconds: 0.2)
+ mixer.tick()
+ }
+ mixer.finish(atSourceTime: clock.now)
+
+ let frames = mixedFrames(sink)
+ XCTAssertEqual(seconds(ofFrames: frames), 2.4, accuracy: 0.011)
+ XCTAssertEqual(firstAudibleSecond(frames) ?? -1, 0.0, accuracy: 0.001)
+ // Every 100 ms of the two seconds the source actually described has to be audible.
+ for step in 0..<20 {
+ let from = Double(step) * 0.1
+ XCTAssertGreaterThan(
+ peak(frames, from: from, to: from + 0.1),
+ audibleThreshold,
+ "silence at \(from)s means the late source was written off"
+ )
+ }
+ }
+
+ // MARK: - Pause
+
+ /// A pause stops the clock instead of resetting it. `ScreenCaptureRecorder.timelineNow()`
+ /// freezes while paused and continues from the frozen value on resume, which is what this
+ /// clock does here: the paused seconds are absent from the track, and everything recorded
+ /// after the pause keeps the position it would have had.
+ func testAFrozenClockPausesTheTrackWithoutShiftingWhatFollows() {
+ let sink = RecordingSink()
+ let clock = TestClock(.zero)
+ let mixer = makeMixer(sink: sink, clock: clock, includesMicrophone: false)
+ mixer.beginTimeline(at: clock.now)
+
+ mixer.ingest(
+ makeSourceBuffer(burst(seconds: 1, left: 0.5, right: 0.5), at: clock.now, nonInterleaved: true),
+ from: .system
+ )
+ clock.advance(seconds: 1)
+ mixer.tick()
+
+ // Paused: real time passes, the timeline does not.
+ for _ in 0..<20 {
+ mixer.tick()
+ }
+ XCTAssertEqual(seconds(ofFrames: mixedFrames(sink)), 1.0, accuracy: 0.011)
+
+ // Resumed, and the source picks up at the position the timeline froze at.
+ mixer.ingest(
+ makeSourceBuffer(burst(seconds: 1, left: 0.5, right: 0.5), at: clock.now, nonInterleaved: true),
+ from: .system
+ )
+ clock.advance(seconds: 1)
+ mixer.finish(atSourceTime: clock.now)
+
+ let frames = mixedFrames(sink)
+ assertContiguous(sink)
+ XCTAssertEqual(seconds(ofFrames: frames), 2.0, accuracy: 0.011)
+ XCTAssertGreaterThan(peak(frames, from: 1.2, to: 1.8), audibleThreshold)
+ }
+
+ // MARK: - Gain
+
+ func testANonFiniteMicrophoneGainFallsBackToUnityRatherThanPoisoningTheMix() {
+ let sink = RecordingSink()
+ let clock = TestClock(.zero)
+ let mixer = makeMixer(sink: sink, clock: clock, includesMicrophone: true, microphoneGain: .nan)
+ mixer.beginTimeline(at: clock.now)
+
+ mixer.ingest(
+ makeSourceBuffer(burst(seconds: 0.5, left: 0.5, right: 0.5), at: clock.now, nonInterleaved: false),
+ from: .microphone
+ )
+ clock.advance(seconds: 0.5)
+ mixer.finish(atSourceTime: clock.now)
+
+ let frames = mixedFrames(sink)
+ // 0.5 at unity gain, quantized: 16 383 or 16 384 depending on rounding. NaN reaching
+ // the multiply instead would leave the whole track at zero.
+ let loudest = peak(frames, from: 0, to: 0.5)
+ XCTAssertGreaterThan(loudest, 16_000)
+ XCTAssertLessThan(loudest, 16_500)
+ }
+
+ // MARK: - Fixtures
+
+ private func makeMixer(
+ sink: MixedAudioSink,
+ clock: TestClock,
+ includesMicrophone: Bool,
+ microphoneGain: Double = 1.4
+ ) -> AudioTrackMixer {
+ AudioTrackMixer(
+ input: sink,
+ includesSystemAudio: true,
+ includesMicrophone: includesMicrophone,
+ microphoneGain: microphoneGain,
+ clock: { clock.now }
+ )
+ }
+
+ /// A burst whose every sample sits at exactly ±amplitude, so an onset can be located to the
+ /// frame. A sine would put near-zero samples at each zero crossing and blunt that.
+ private func burst(seconds: Double, left: Float, right: Float) -> [Float] {
+ let frameCount = Int(seconds * Double(sampleRate))
+ var samples = [Float](repeating: 0, count: frameCount * channelCount)
+ for frame in 0..<frameCount {
+ let sign: Float = frame % 2 == 0 ? 1 : -1
+ samples[frame * channelCount] = left * sign
+ samples[frame * channelCount + 1] = right * sign
+ }
+ return samples
+ }
+
+ /// One capture buffer in the shape ScreenCaptureKit actually delivers: 48 kHz stereo
+ /// Float32, non-interleaved for the system-audio output and interleaved for the microphone.
+ private func makeSourceBuffer(
+ _ interleavedSamples: [Float],
+ at presentationTime: CMTime,
+ nonInterleaved: Bool
+ ) -> CMSampleBuffer {
+ let frameCount = interleavedSamples.count / channelCount
+ let bytesPerChannelSample = MemoryLayout<Float>.size
+ var asbd = AudioStreamBasicDescription(
+ mSampleRate: Float64(sampleRate),
+ mFormatID: kAudioFormatLinearPCM,
+ mFormatFlags: kAudioFormatFlagIsFloat | kAudioFormatFlagIsPacked
+ | kAudioFormatFlagsNativeEndian
+ | (nonInterleaved ? kAudioFormatFlagIsNonInterleaved : 0),
+ mBytesPerPacket: UInt32(nonInterleaved ? bytesPerChannelSample : bytesPerChannelSample * channelCount),
+ mFramesPerPacket: 1,
+ mBytesPerFrame: UInt32(nonInterleaved ? bytesPerChannelSample : bytesPerChannelSample * channelCount),
+ mChannelsPerFrame: UInt32(channelCount),
+ mBitsPerChannel: 32,
+ mReserved: 0
+ )
+
+ var formatDescription: CMAudioFormatDescription?
+ XCTAssertEqual(
+ CMAudioFormatDescriptionCreate(
+ allocator: kCFAllocatorDefault,
+ asbd: &asbd,
+ layoutSize: 0,
+ layout: nil,
+ magicCookieSize: 0,
+ magicCookie: nil,
+ extensions: nil,
+ formatDescriptionOut: &formatDescription
+ ),
+ noErr
+ )
+
+ var sampleBuffer: CMSampleBuffer?
+ XCTAssertEqual(
+ CMAudioSampleBufferCreateWithPacketDescriptions(
+ allocator: kCFAllocatorDefault,
+ dataBuffer: nil,
+ dataReady: false,
+ makeDataReadyCallback: nil,
+ refcon: nil,
+ formatDescription: formatDescription!,
+ sampleCount: frameCount,
+ presentationTimeStamp: presentationTime,
+ packetDescriptions: nil,
+ sampleBufferOut: &sampleBuffer
+ ),
+ noErr
+ )
+
+ let planeCount = nonInterleaved ? channelCount : 1
+ let planeBytes = nonInterleaved
+ ? frameCount * bytesPerChannelSample
+ : frameCount * bytesPerChannelSample * channelCount
+ var planes = [UnsafeMutableRawPointer]()
+ for plane in 0..<planeCount {
+ let memory = UnsafeMutableRawPointer.allocate(byteCount: planeBytes, alignment: 16)
+ let floats = memory.bindMemory(to: Float.self, capacity: planeBytes / bytesPerChannelSample)
+ if nonInterleaved {
+ for frame in 0..<frameCount {
+ floats[frame] = interleavedSamples[frame * channelCount + plane]
+ }
+ } else {
+ for index in interleavedSamples.indices {
+ floats[index] = interleavedSamples[index]
+ }
+ }
+ planes.append(memory)
+ }
+ defer { planes.forEach { $0.deallocate() } }
+
+ let bufferList = AudioBufferList.allocate(maximumBuffers: planeCount)
+ defer { free(bufferList.unsafeMutablePointer) }
+ for plane in 0..<planeCount {
+ bufferList[plane] = AudioBuffer(
+ mNumberChannels: UInt32(nonInterleaved ? 1 : channelCount),
+ mDataByteSize: UInt32(planeBytes),
+ mData: planes[plane]
+ )
+ }
+
+ // Copies into a block buffer of its own, so the planes above can go out of scope.
+ XCTAssertEqual(
+ CMSampleBufferSetDataBufferFromAudioBufferList(
+ sampleBuffer!,
+ blockBufferAllocator: kCFAllocatorDefault,
+ blockBufferMemoryAllocator: kCFAllocatorDefault,
+ flags: 0,
+ bufferList: bufferList.unsafePointer
+ ),
+ noErr
+ )
+ XCTAssertEqual(CMSampleBufferSetDataReady(sampleBuffer!), noErr)
+ return sampleBuffer!
+ }
+
+ // MARK: - Readback
+
+ private func mixedFrames(_ sink: RecordingSink) -> [Int16] {
+ var samples = [Int16]()
+ for buffer in sink.buffers {
+ guard let block = CMSampleBufferGetDataBuffer(buffer) else {
+ continue
+ }
+ let length = CMBlockBufferGetDataLength(block)
+ var bytes = [UInt8](repeating: 0, count: length)
+ let status = bytes.withUnsafeMutableBytes { raw -> OSStatus in
+ guard let base = raw.baseAddress else {
+ return -1
+ }
+ return CMBlockBufferCopyDataBytes(
+ block,
+ atOffset: 0,
+ dataLength: length,
+ destination: base
+ )
+ }
+ XCTAssertEqual(status, kCMBlockBufferNoErr)
+ samples.append(contentsOf: bytes.withUnsafeBytes { Array($0.bindMemory(to: Int16.self)) })
+ }
+ return samples
+ }
+
+ private func seconds(ofFrames samples: [Int16]) -> Double {
+ Double(samples.count / channelCount) / Double(sampleRate)
+ }
+
+ /// Every chunk has to butt up against the one before it. A hole here would mean the mixer
+ /// emitted a timestamp it never filled, which is the failure this whole file is about.
+ private func assertContiguous(_ sink: RecordingSink, file: StaticString = #filePath, line: UInt = #line) {
+ var expected: CMTime?
+ for buffer in sink.buffers {
+ let presentationTime = buffer.presentationTimeStamp
+ if let expected {
+ XCTAssertEqual(
+ CMTimeGetSeconds(CMTimeSubtract(presentationTime, expected)),
+ 0,
+ accuracy: 1e-9,
+ "chunks must be contiguous",
+ file: file,
+ line: line
+ )
+ }
+ expected = CMTimeAdd(
+ presentationTime,
+ CMTime(value: CMTimeValue(CMSampleBufferGetNumSamples(buffer)), timescale: CMTimeScale(sampleRate))
+ )
+ }
+ }
+
+ private func peak(_ samples: [Int16], from: Double, to: Double, channel: Int? = nil) -> Int16 {
+ let firstFrame = Int(from * Double(sampleRate))
+ let lastFrame = min(Int(to * Double(sampleRate)), samples.count / channelCount)
+ var loudest: Int16 = 0
+ var frame = firstFrame
+ while frame < lastFrame {
+ for lane in 0..<channelCount where channel == nil || channel == lane {
+ let value = samples[frame * channelCount + lane]
+ loudest = max(loudest, value == Int16.min ? Int16.max : abs(value))
+ }
+ frame += 1
+ }
+ return loudest
+ }
+
+ private func firstAudibleSecond(_ samples: [Int16], channel: Int? = nil) -> Double? {
+ let frameCount = samples.count / channelCount
+ for frame in 0..<frameCount {
+ for lane in 0..<channelCount where channel == nil || channel == lane {
+ let value = samples[frame * channelCount + lane]
+ if (value == Int16.min ? Int16.max : abs(value)) > audibleThreshold {
+ return Double(frame) / Double(sampleRate)
+ }
+ }
+ }
+ return nil
+ }
+}
+
+/// Keeps what the mixer produced instead of encoding it, and is always ready, so nothing here
+/// exercises the backpressure path.
+private final class RecordingSink: MixedAudioSink {
+ private(set) var buffers: [CMSampleBuffer] = []
+
+ var isReadyForMoreMediaData: Bool { true }
+
+ @discardableResult
+ func append(_ sampleBuffer: CMSampleBuffer) -> Bool {
+ buffers.append(sampleBuffer)
+ return true
+ }
+}
+
+/// The writer timeline, moved by hand. Stands in for `ScreenCaptureRecorder.timelineNow()`,
+/// which is the host clock less the time spent paused — including the part where it stops
+/// moving altogether while the recording is paused.
+private final class TestClock {
+ private(set) var now: CMTime
+
+ init(_ start: CMTime) {
+ self.now = start
+ }
+
+ func advance(seconds: Double) {
+ now = CMTimeAdd(now, CMTime(seconds: seconds, preferredTimescale: 48_000))
+ }
+}
diff --git a/package.json b/package.json
index 1eb4bb244..da39a03b2 100644
--- a/package.json
+++ b/package.json
@@ -73,6 +73,8 @@
"test:wgc-webcam:win": "node scripts/test-windows-wgc-helper.mjs --webcam",
"test:wgc-camera-selection:win": "node scripts/test-windows-camera-selection.mjs",
"test:wgc-full:win": "node scripts/test-windows-wgc-helper.mjs --webcam --system-audio --microphone",
+ "test:sck-audio-timeline:mac": "node scripts/test-macos-audio-timeline.mjs",
+ "test:swift:mac": "swift test --package-path electron/native/screencapturekit",
"capture:openscreen-preview": "node scripts/capture-openscreen-preview.mjs",
"inspect:cursor-click-bounce": "node scripts/inspect-native-cursor-click-bounce.mjs",
"diagnostic:run": "node scripts/diagnostic-tool/diagnostic.mjs",
diff --git a/scripts/test-macos-audio-timeline.mjs b/scripts/test-macos-audio-timeline.mjs
new file mode 100644
index 000000000..e08af311b
--- /dev/null
+++ b/scripts/test-macos-audio-timeline.mjs
@@ -0,0 +1,388 @@
+/**
+ * Does a sound land where it happened, and does the track cover the whole take?
+ *
+ * The macOS sibling of scripts/test-windows-audio-timeline.mjs, and it asks one more
+ * question than that one does. The helper's mixed audio track used to take its origin
+ * from the first buffer that happened to arrive, so a take beginning in silence began
+ * the track wherever the first sound was — and it never called
+ * `writer.endSession(atSourceTime:)`, so the file also ENDED at the last sample anything
+ * delivered. Leading silence missing at the front, trailing silence missing at the back,
+ * one cause: a cursor advanced by data instead of by a clock.
+ *
+ * npm run test:sck-audio-timeline:mac
+ *
+ * Records ten seconds — four silent, three with a tone, three silent again — and measures
+ * where the tone sits and how long each track is. Plays through the default output device
+ * and captures the default display, so both have to be working: this measures the machine
+ * as much as the code. `swift test` is the half that measures only the code, and that one
+ * runs on every pull request.
+ *
+ * Two tolerances, because the two measurements are not equally tight:
+ *
+ * - The tone's position is compared against the instant playback was ASKED for, so it
+ * carries afplay's start-up latency and the output device waking up. 250 ms.
+ * - The audio track's length is compared against the VIDEO track's length in the same
+ * file. Both come from one writer session and one endSession, so no wall clock enters
+ * it at all and the comparison can be tight. 100 ms.
+ *
+ * That second one is the assertion with teeth, and it is the one Windows cannot make: its
+ * script has no video track to compare against and settles for "not shorter than the
+ * silence", with TOLERANCE_S = 1.0.
+ */
+import { spawn, spawnSync } from "node:child_process";
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+
+const __dirname = path.dirname(fileURLToPath(import.meta.url));
+const ROOT = path.join(__dirname, "..");
+
+const PLAY_AT_MS = Number(process.env.OPENSCREEN_SCK_TEST_PLAY_AT_MS ?? 4000);
+const TONE_MS = 3000;
+/** Silence after the tone, so the trailing half of the timeline is exercised too. */
+const TAIL_MS = 3000;
+/** How far the tone may sit from where it was asked for before this is a failure. */
+const TONE_TOLERANCE_S = 0.25;
+/** How far the audio track may differ in length from the video track in the same file. */
+const TRACK_TOLERANCE_S = 0.1;
+/** Analysis window for locating the tone. Tight enough to resolve a 250 ms mis-rebase. */
+const WINDOW_MS = 20;
+
+if (process.platform !== "darwin") {
+ console.log("macOS only — skipping.");
+ process.exit(0);
+}
+
+/**
+ * The vendored LGPL tree first, then whatever is on PATH.
+ *
+ * scripts/fetch-ffmpeg-macos.mjs BUILDS its tree from source (roughly five minutes),
+ * because no LGPL macOS binary is published — far too much to demand of a test run, so a
+ * Homebrew ffmpeg is accepted here. That is fine for measuring a file and would not be
+ * fine for shipping: Homebrew's build is GPL-3.0.
+ */
+function resolveTool(name) {
+ const fromEnv = process.env[`OPENSCREEN_${name.toUpperCase()}`];
+ if (fromEnv && fs.existsSync(fromEnv)) return fromEnv;
+
+ const thirdparty = path.join(ROOT, "crates", "thirdparty");
+ if (fs.existsSync(thirdparty)) {
+ for (const entry of fs.readdirSync(thirdparty)) {
+ if (!entry.startsWith("ffmpeg-n")) continue;
+ const candidate = path.join(thirdparty, entry, "bin", name);
+ if (fs.existsSync(candidate)) return candidate;
+ }
+ }
+
+ const onPath = spawnSync("/usr/bin/which", [name], { encoding: "utf8" });
+ const resolved = (onPath.stdout ?? "").trim();
+ return resolved && fs.existsSync(resolved) ? resolved : null;
+}
+
+function resolveHelper() {
+ const candidates = [
+ process.env.OPENSCREEN_SCK_HELPER_BIN,
+ path.join(
+ ROOT,
+ "electron",
+ "native",
+ "screencapturekit",
+ "build",
+ "openscreen-screencapturekit-helper",
+ ),
+ path.join(
+ ROOT,
+ "electron",
+ "native",
+ "bin",
+ "darwin-arm64",
+ "openscreen-screencapturekit-helper",
+ ),
+ path.join(
+ ROOT,
+ "electron",
+ "native",
+ "bin",
+ "darwin-x64",
+ "openscreen-screencapturekit-helper",
+ ),
+ ];
+ return candidates.find((candidate) => candidate && fs.existsSync(candidate)) ?? null;
+}
+
+/**
+ * The helper matches `source.displayId` against `SCShareableContent.displays`, so this has
+ * to be a real CGDirectDisplayID rather than an index. Asked of CoreGraphics directly —
+ * guessing 1 is right on most single-display Macs and wrong on the rest.
+ */
+function resolveDisplayId() {
+ const override = Number(process.env.OPENSCREEN_SCK_TEST_DISPLAY_ID);
+ if (Number.isFinite(override) && override > 0) return override;
+
+ const probe = path.join(os.tmpdir(), "openscreen-main-display-id.swift");
+ fs.writeFileSync(probe, "import CoreGraphics\nprint(CGMainDisplayID())\n");
+ const result = spawnSync("swift", [probe], { encoding: "utf8" });
+ fs.rmSync(probe, { force: true });
+ const parsed = Number((result.stdout ?? "").trim());
+ return Number.isFinite(parsed) && parsed > 0 ? parsed : 1;
+}
+
+const FFMPEG = resolveTool("ffmpeg");
+const FFPROBE = resolveTool("ffprobe");
+const HELPER = resolveHelper();
+if (!HELPER) {
+ console.error("No ScreenCaptureKit helper found. Run: npm run build:native:mac");
+ process.exit(1);
+}
+if (!FFMPEG || !FFPROBE) {
+ console.error(
+ "No ffmpeg/ffprobe found. Run `npm run fetch:ffmpeg:mac`, install one with Homebrew,\n" +
+ "or point OPENSCREEN_FFMPEG and OPENSCREEN_FFPROBE at binaries.",
+ );
+ process.exit(1);
+}
+
+const tonePath = path.join(os.tmpdir(), "openscreen-audio-timeline-tone.wav");
+const madeTone = spawnSync(FFMPEG, [
+ "-hide_banner",
+ "-loglevel",
+ "error",
+ "-f",
+ "lavfi",
+ "-i",
+ `sine=frequency=440:duration=${TONE_MS / 1000}`,
+ "-ac",
+ "2",
+ "-ar",
+ "48000",
+ "-acodec",
+ "pcm_s16le",
+ "-y",
+ tonePath,
+]);
+if (madeTone.status !== 0 || !fs.existsSync(tonePath)) {
+ console.error("Could not synthesise the test tone.");
+ process.exit(1);
+}
+
+const outputPath = path.join(os.tmpdir(), "openscreen-audio-timeline.mp4");
+fs.rmSync(outputPath, { force: true });
+
+const displayId = resolveDisplayId();
+const request = {
+ schemaVersion: 1,
+ recordingId: Date.now(),
+ source: { type: "display", sourceId: `screen:${displayId}:0`, displayId },
+ video: { fps: 30, width: 1280, height: 720, bitrate: 4_000_000, hideSystemCursor: true },
+ audio: {
+ system: { enabled: true },
+ // No microphone on purpose: a live one streams continuously and would keep the
+ // timeline moving on its own, hiding exactly the failure this measures.
+ microphone: { enabled: false, deviceId: null, deviceName: null, gain: 1 },
+ },
+ webcam: { enabled: false, deviceId: null, deviceName: null, width: 1280, height: 720, fps: 30 },
+ cursor: { mode: "editable-overlay" },
+ outputs: { screenPath: outputPath },
+};
+
+console.log(
+ `Recording ${(PLAY_AT_MS + TONE_MS + TAIL_MS) / 1000}s on display ${displayId}: ` +
+ `${PLAY_AT_MS / 1000}s of silence, a ${TONE_MS / 1000}s tone, then ${TAIL_MS / 1000}s of silence...`,
+);
+const proc = spawn(HELPER, [JSON.stringify(request)]);
+let helperOutput = "";
+let spawnError = null;
+let playbackArmed = false;
+const helperEvents = [];
+proc.on("error", (error) => {
+ spawnError = error.message;
+});
+
+/**
+ * Arms the tone once the helper says it is recording, never from spawn.
+ *
+ * Everything measured here is relative to the writer session, which opens on the first
+ * video frame — after ScreenCaptureKit, the encoder and the audio taps have all come up.
+ * Counting from spawn would fold that setup into the offset and fail the test on a slow
+ * machine with nothing wrong with the timestamps.
+ */
+function armPlaybackOnce() {
+ if (playbackArmed || !helperEvents.some((event) => event.event === "recording-started")) {
+ return;
+ }
+ playbackArmed = true;
+ setTimeout(() => {
+ // Blocking on purpose: it guarantees the tone really played before the tail is
+ // timed and the stop below is sent, which is the premise of the measurement.
+ spawnSync("/usr/bin/afplay", [tonePath]);
+ setTimeout(() => {
+ try {
+ proc.stdin.write("stop\n");
+ } catch {
+ // Already gone; the close handler reports how it ended.
+ }
+ }, TAIL_MS);
+ }, PLAY_AT_MS);
+}
+
+function consume(chunk) {
+ helperOutput += chunk.toString();
+ for (const line of chunk.toString().split("\n")) {
+ const trimmed = line.trim();
+ if (!trimmed.startsWith("{")) continue;
+ try {
+ helperEvents.push(JSON.parse(trimmed));
+ } catch {
+ // Not one of ours; the raw text is kept in helperOutput either way.
+ }
+ }
+ armPlaybackOnce();
+}
+proc.stdout.on("data", consume);
+proc.stderr.on("data", consume);
+
+// If the helper never announces itself, nothing would ever stop it.
+const startTimeout = setTimeout(() => {
+ if (!playbackArmed) {
+ console.error("The helper never reported that recording had started.");
+ proc.kill();
+ }
+}, 30_000);
+
+/** Per-stream durations, which is what "does the audio cover the take" is asked of. */
+function streamDurations() {
+ const probed = spawnSync(
+ FFPROBE,
+ [
+ "-hide_banner",
+ "-loglevel",
+ "error",
+ "-show_entries",
+ "stream=codec_type,duration",
+ "-of",
+ "json",
+ outputPath,
+ ],
+ { encoding: "utf8", maxBuffer: 1 << 24 },
+ );
+ try {
+ const streams = JSON.parse(probed.stdout ?? "{}").streams ?? [];
+ const durationOf = (kind) => {
+ const stream = streams.find((candidate) => candidate.codec_type === kind);
+ const seconds = Number(stream?.duration);
+ return Number.isFinite(seconds) ? seconds : null;
+ };
+ return { audio: durationOf("audio"), video: durationOf("video") };
+ } catch {
+ return { audio: null, video: null };
+ }
+}
+
+/** Where the tone actually sits, from the decoded samples rather than the metadata. */
+function firstAudibleSecond() {
+ const rate = 16000;
+ const decoded = spawnSync(
+ FFMPEG,
+ [
+ "-hide_banner",
+ "-nostats",
+ "-loglevel",
+ "error",
+ "-i",
+ outputPath,
+ "-map",
+ "0:a",
+ "-f",
+ "s16le",
+ "-ac",
+ "1",
+ "-ar",
+ String(rate),
+ "-",
+ ],
+ { maxBuffer: 1 << 28 },
+ );
+ const pcm = decoded.stdout ?? Buffer.alloc(0);
+ const samples = pcm.length / 2;
+ const windowSamples = (rate * WINDOW_MS) / 1000;
+ for (let index = 0; index * windowSamples < samples; index += 1) {
+ let peak = 0;
+ const from = index * windowSamples;
+ const to = Math.min(from + windowSamples, samples);
+ for (let at = from; at < to; at += 1) {
+ peak = Math.max(peak, Math.abs(pcm.readInt16LE(at * 2)));
+ }
+ // Well above dither, well below a real tone.
+ if (peak > 1200) return (index * WINDOW_MS) / 1000;
+ }
+ return null;
+}
+
+proc.on("close", (code, signal) => {
+ clearTimeout(startTimeout);
+ const problems = [];
+ if (!playbackArmed) problems.push("recording never started, so no tone was played");
+ if (spawnError) problems.push(`could not start the helper: ${spawnError}`);
+ if (signal) problems.push(`helper killed by ${signal}`);
+ if (code !== 0 && code !== null) problems.push(`helper exited ${code}`);
+
+ const { audio, video } = streamDurations();
+ const toneAt = firstAudibleSecond();
+ const playedAt = PLAY_AT_MS / 1000;
+
+ if (audio === null) {
+ problems.push("the recording has no audio track at all");
+ }
+ if (toneAt === null) {
+ problems.push(
+ "no audible tone in the recording — check the default output device is on and unmuted",
+ );
+ } else if (Math.abs(toneAt - playedAt) > TONE_TOLERANCE_S) {
+ problems.push(
+ `the tone sits at ${toneAt.toFixed(2)}s, and was played at ${playedAt.toFixed(2)}s`,
+ );
+ }
+ // The whole take has to be IN the audio track: the silence before the tone and the
+ // silence after it, not just the part where something was playing.
+ if (audio !== null && video !== null && Math.abs(audio - video) > TRACK_TOLERANCE_S) {
+ problems.push(
+ `the audio track is ${audio.toFixed(2)}s and the video track is ${video.toFixed(2)}s — ` +
+ `the mixed track does not span the take`,
+ );
+ }
+
+ // The mixer's own account of how much of the track it filled with silence because no
+ // source covered it. On a take where nothing plays, this is the measurement that says
+ // whether ScreenCaptureKit's system-audio output is silence-gapped the way the WASAPI
+ // loopback tap is, or whether it streams silence continuously.
+ const summary = helperEvents.findLast((event) => event.event === "audio-timeline");
+
+ fs.rmSync(outputPath, { force: true });
+ console.log(
+ `\n${problems.length ? "FAIL" : "PASS"} audio=${audio?.toFixed(2) ?? "(none)"}s ` +
+ `video=${video?.toFixed(2) ?? "(none)"}s ` +
+ `tone at ${toneAt === null ? "(none)" : `${toneAt.toFixed(2)}s`}, played at ${playedAt.toFixed(2)}s`,
+ );
+ if (summary) {
+ console.log(
+ ` system audio delivered nothing for ${Number(summary.systemUncoveredSeconds ?? 0).toFixed(2)}s ` +
+ `of a ${Number(summary.trackSeconds ?? 0).toFixed(2)}s track ` +
+ `(near the whole track means ScreenCaptureKit gaps its silence, like WASAPI loopback;\n` +
+ ` near zero means it streams silence and only the take's edges needed the clock)`,
+ );
+ }
+ for (const problem of problems) console.log(` -> ${problem}`);
+ if (problems.length) {
+ const complaints = helperEvents
+ .filter((event) => event.event === "error" || event.event === "warning")
+ .slice(-5);
+ for (const complaint of complaints) {
+ console.log(` helper: ${complaint.code}: ${complaint.message}`);
+ }
+ if (!complaints.length && helperOutput.trim()) {
+ console.log(` helper: ${helperOutput.trim().split("\n").slice(-3).join(" | ")}`);
+ }
+ }
+ process.exit(problems.length ? 1 : 0);
+});
diff --git a/technical-documentation/architecture/recording.md b/technical-documentation/architecture/recording.md
index f6323f72e..fa9d81cc8 100644
--- a/technical-documentation/architecture/recording.md
+++ b/technical-documentation/architecture/recording.md
@@ -71,6 +71,8 @@ A session writes a screen video and a `.session.json` manifest. Windows normally
The Windows helper mixes system loopback and microphone into one track, and timestamps it from a running count of emitted frames. That count is advanced by a clock rather than by the arrival of samples: a chunk goes out every 10 ms for as long as the recording runs, filled from whichever source has data and with silence where neither does. Advancing it only when a queue held samples is what made a take that began in silence emit nothing at all — WASAPI loopback delivers no packets while nothing is playing — so the first sound landed at timestamp zero and the track came out shorter than the take. A working microphone concealed it by streaming continuously, which is why it appeared as a system-audio desync on a machine whose microphone had failed. `npm run test:wgc-audio-timeline:win` measures where a tone played at a known instant actually lands.
+The macOS helper mixes the same two sources into one AAC track (`AudioTrackMixer`) and runs the same discipline, arrived at from the opposite direction. There the emit cursor is anchored to the writer session start and advanced by a monotonic clock read off `CMClockGetHostTimeClock` — the domain ScreenCaptureKit already timestamps its buffers in — with a 10 ms timer on the sample queue moving it while nothing is arriving to move it. The bug it replaces was the anchor, not the counter: `anchor` was set lazily on the first decoded buffer to `max(firstPresentationTime, sessionStart)`, so audio that first arrived four seconds in made frame zero of the track *be* four seconds in. The trailing half was worse still — `drain()` ran only from `ingest` and `finish`, and the helper never called `writer.endSession(atSourceTime:)` at all, so the file ended at the last sample anything happened to deliver. Both halves and any mid-take gap are now one mechanism: chunks go out for as long as the take runs, from whichever source covers them and from silence where none does, and a source is written off for a chunk only once real time has run 250 ms past it — a decision about when to stop waiting, which shifts nothing, and not a correction, which would. A pause freezes the clock rather than resetting it, so what follows keeps the position it would have had. Whether ScreenCaptureKit's system-audio output is silence-gapped the way WASAPI loopback is has never been recorded anywhere, and it decides how much of a take the clock is carrying alone rather than how the mixer should work; the helper now reports it per take as `audio-timeline`, whose `systemUncoveredSeconds` is the whole track if the tap is gapped and near zero if it streams silence. `swift test` runs the mixer against a collecting sink and a hand-moved clock on every pull request (`swift-macos-helper` in ci.yml, the first Swift job this repository has had); `npm run test:sck-audio-timeline:mac` measures a real tone through a real device, comparing the audio track's length against the video track's in the same file.
+
Cursor samples are persisted as cursor telemetry rather than baked into editable-overlay recordings. The loader resolves the sidecar at `<videoPath>.cursor.json` or through the recording links; see [cursor.md](cursor.md) for the telemetry format and rendering path.
## Known gaps