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(macos): realign a microphone stamped on a foreign clock

Etienne Lescotb3d76aada62c
diff --git a/electron/native/screencapturekit/Sources/OpenScreenCaptureCore/AudioTrackMixer.swift b/electron/native/screencapturekit/Sources/OpenScreenCaptureCore/AudioTrackMixer.swift
index 042347394..8b4551a8d 100644
--- a/electron/native/screencapturekit/Sources/OpenScreenCaptureCore/AudioTrackMixer.swift
+++ b/electron/native/screencapturekit/Sources/OpenScreenCaptureCore/AudioTrackMixer.swift
@@ -95,6 +95,11 @@ public final class AudioTrackMixer {
static let maxPendingChunks = 500
/// How long the final flush waits for the input to accept the tail before giving up.
static let finalFlushTimeout = 5.0
+ /// How far a source's first buffer may sit from the clock before its timestamps are
+ /// taken to be on some other clock entirely. A live ScreenCaptureKit output hands
+ /// over audio tens of milliseconds after capturing it; a whole second apart is not
+ /// latency, it is a different time base. See `clockOffsets`.
+ static let foreignClockThreshold = CMTime(value: 1, timescale: 1)
}
private let input: MixedAudioSink
@@ -124,6 +129,22 @@ public final class AudioTrackMixer {
private var pending: [CMSampleBuffer] = []
private var didWarnAboutBacklog = false
private var didWarnAboutDecode: Set<Int> = []
+ /// Per source, what is added to every presentation timestamp before placement — fixed on
+ /// that source's first delivery, nil until then.
+ ///
+ /// Zero for a source whose timestamps are on the writer's clock, which is what placement
+ /// by timestamp assumes. ScreenCaptureKit does not promise that for the microphone output
+ /// (Apple: the microphone and app audio are on independent clocks), and on a Mac with no
+ /// input device at all the microphone output mirrors system audio, clock included — so
+ /// the only machine the mixer had been proven on was the one place the assumption held.
+ /// Placed raw, a microphone stamped seconds or hours off the session lands entirely
+ /// before frame zero (all trimmed) or beyond the end of the take (never reached), and the
+ /// track comes out silent with every buffer accounted as delivered.
+ ///
+ /// A foreign time base is recognised on the first buffer and mapped onto the clock once:
+ /// that buffer is taken to end where the clock stands, and every later one keeps its own
+ /// spacing from it, so the source's timing is preserved and only its origin moves.
+ private var clockOffsets = [CMTime?](repeating: nil, count: Source.allCases.count)
public init(
input: MixedAudioSink,
@@ -164,8 +185,8 @@ public final class AudioTrackMixer {
guard includes(source), let anchor else {
return
}
- let presentationTime = CMSampleBufferGetPresentationTimeStamp(sampleBuffer)
- guard presentationTime.isValid, presentationTime.isNumeric else {
+ let capturedTime = CMSampleBufferGetPresentationTimeStamp(sampleBuffer)
+ guard capturedTime.isValid, capturedTime.isNumeric else {
return
}
guard let frames = decodeInterleavedStereo(sampleBuffer, gain: gain(for: source)),
@@ -178,6 +199,15 @@ public final class AudioTrackMixer {
}
let now = clock()
+ let presentationTime = CMTimeAdd(
+ capturedTime,
+ clockOffset(
+ for: source,
+ capturedAt: capturedTime,
+ frameCount: frames.count / MixFormat.channelCount,
+ now: now
+ )
+ )
let startFrame = frameIndex(of: presentationTime, from: anchor)
noteDelivery(source, from: startFrame, frameCount: Int64(frames.count / MixFormat.channelCount))
sources[source.rawValue].ingest(frames, atFrame: startFrame)
@@ -212,6 +242,41 @@ public final class AudioTrackMixer {
flushPending(force: true)
}
+ /// The offset `clockOffsets` documents, fixed on the source's first delivery.
+ private func clockOffset(
+ for source: Source,
+ capturedAt capturedTime: CMTime,
+ frameCount: Int,
+ now: CMTime
+ ) -> CMTime {
+ if let offset = clockOffsets[source.rawValue] {
+ return offset
+ }
+ guard now.isValid, now.isNumeric else {
+ return .zero
+ }
+
+ // Judged on where the buffer starts: a live buffer is a few milliseconds long and
+ // arrives just after it, so start and arrival differ only by latency.
+ let skew = CMTimeSubtract(now, capturedTime)
+ guard CMTimeCompare(CMTimeAbsoluteValue(skew), MixFormat.foreignClockThreshold) > 0 else {
+ clockOffsets[source.rawValue] = .zero
+ return .zero
+ }
+ // Realigned so that the buffer ends where the clock stands — it was just captured.
+ let offset = CMTimeSubtract(
+ skew,
+ CMTime(value: CMTimeValue(frameCount), timescale: CMTimeScale(MixFormat.sampleRate))
+ )
+ clockOffsets[source.rawValue] = offset
+ emit([
+ "event": "warning",
+ "code": "audio-source-clock-rebased",
+ "message": "\(source == .system ? "System" : "Microphone") audio is timestamped \(String(format: "%.3f", CMTimeGetSeconds(skew))) s off the capture clock; it was realigned to arrival.",
+ ])
+ return offset
+ }
+
private func warnAboutDecodeFailure(_ source: Source, _ sampleBuffer: CMSampleBuffer) {
guard !didWarnAboutDecode.contains(source.rawValue) else {
return
@@ -308,6 +373,7 @@ public final class AudioTrackMixer {
"longestHoleSeconds": report.longestHoleSeconds,
"droppedSeconds": report.droppedSeconds,
"trimmedSeconds": report.trimmedSeconds,
+ "clockOffsetSeconds": report.clockOffsetSeconds,
]
}
emit(fields)
@@ -321,6 +387,9 @@ public final class AudioTrackMixer {
public let longestHoleSeconds: Double
public let droppedSeconds: Double
public let trimmedSeconds: Double
+ /// What `clockOffsets` added to this source's timestamps; 0 when it was already on the
+ /// capture clock (or never delivered).
+ public let clockOffsetSeconds: Double
}
public func deliveryReport(for source: Source) -> DeliveryReport {
@@ -329,7 +398,8 @@ public final class AudioTrackMixer {
undeliveredSeconds: seconds(undeliveredFrames[source.rawValue]),
longestHoleSeconds: seconds(longestHoleFrames[source.rawValue]),
droppedSeconds: seconds(sources[source.rawValue].droppedFrames),
- trimmedSeconds: seconds(sources[source.rawValue].trimmedFrames)
+ trimmedSeconds: seconds(sources[source.rawValue].trimmedFrames),
+ clockOffsetSeconds: clockOffsets[source.rawValue].map(CMTimeGetSeconds) ?? 0
)
}
diff --git a/electron/native/screencapturekit/Tests/OpenScreenCaptureCoreTests/AudioTrackMixerTests.swift b/electron/native/screencapturekit/Tests/OpenScreenCaptureCoreTests/AudioTrackMixerTests.swift
index 5b8f7ff11..d5b1f0a11 100644
--- a/electron/native/screencapturekit/Tests/OpenScreenCaptureCoreTests/AudioTrackMixerTests.swift
+++ b/electron/native/screencapturekit/Tests/OpenScreenCaptureCoreTests/AudioTrackMixerTests.swift
@@ -218,6 +218,82 @@ final class AudioTrackMixerTests: XCTestCase {
XCTAssertEqual((microphoneOnset ?? 0) - (systemOnset ?? 0), 0.090, accuracy: 0.002)
}
+ /// The microphone output is not guaranteed to be stamped on the writer's clock. On this
+ /// project's only test Mac it was — with no input device, ScreenCaptureKit's microphone
+ /// output mirrors system audio, clock included — while on a MacBook with a real microphone
+ /// every take came out with a silent track. Placed raw, audio stamped far behind the
+ /// session is trimmed as pre-roll and audio stamped far ahead is never reached; either way
+ /// the file holds silence. Both directions must come out audible, where they were spoken.
+ func testAMicrophoneOnAForeignClockIsStillHeard() {
+ for foreignOffset in [-3_600.0, -47.5, 9_000.0] {
+ let (frames, mixer) = recordLiveTake(microphoneClockOffset: foreignOffset)
+ let label = "offset \(foreignOffset)"
+ XCTAssertEqual(seconds(ofFrames: frames), 2.0, accuracy: 0.011, label)
+ // Heard from its first delivery on (the span before that is the ordinary head trim
+ // every source gets) and still heard at the end of the take.
+ XCTAssertLessThanOrEqual(firstAudibleSecond(frames, channel: 1) ?? 99, 0.111, label)
+ XCTAssertGreaterThan(peak(frames, from: 1.7, to: 1.9, channel: 1), audibleThreshold, label)
+ // System audio, on the right clock, is untouched by the realignment.
+ XCTAssertGreaterThan(peak(frames, from: 0.1, to: 1.9, channel: 0), audibleThreshold, label)
+ XCTAssertEqual(mixer.deliveryReport(for: .system).clockOffsetSeconds, 0, label)
+ // The microphone was moved by its foreign offset and nothing else: its first buffer
+ // ends where the clock stood when it arrived, which is where it was captured.
+ XCTAssertEqual(
+ mixer.deliveryReport(for: .microphone).clockOffsetSeconds, -foreignOffset, accuracy: 0.001, label)
+ XCTAssertEqual(mixer.deliveryReport(for: .microphone).droppedSeconds, 0, label)
+ }
+ }
+
+ /// The realignment must not touch a microphone that is on the clock: its buffers arrive a
+ /// little after the audio they describe, and that latency is not a foreign time base.
+ func testAMicrophoneOnTheCaptureClockIsNotRealigned() {
+ let (frames, mixer) = recordLiveTake(microphoneClockOffset: 0, microphoneLatency: 0.3)
+ XCTAssertEqual(mixer.deliveryReport(for: .microphone).clockOffsetSeconds, 0)
+ XCTAssertGreaterThan(peak(frames, from: 1.2, to: 1.4, channel: 1), audibleThreshold)
+ }
+
+ /// Two seconds of live capture, delivered the way ScreenCaptureKit does: each 100 ms
+ /// buffer describes the 100 ms that just elapsed. System audio on the left, stamped on the
+ /// writer's clock; the microphone on the right, stamped `microphoneClockOffset` seconds off
+ /// it and handed over `microphoneLatency` seconds after its span ends.
+ private func recordLiveTake(
+ microphoneClockOffset: Double,
+ microphoneLatency: Double = 0
+ ) -> ([Int16], AudioTrackMixer) {
+ let sink = RecordingSink()
+ let clock = TestClock(CMTime(value: 50, timescale: 1))
+ let mixer = makeMixer(sink: sink, clock: clock, includesMicrophone: true, microphoneGain: 1)
+ mixer.beginTimeline(at: clock.now)
+ let sessionStart = clock.now
+ let step = 0.1
+ var pendingMicrophone: [(deliverAt: Double, buffer: CMSampleBuffer)] = []
+
+ for index in 0..<20 {
+ let spanStart = CMTimeAdd(sessionStart, CMTime(seconds: Double(index) * step, preferredTimescale: 48_000))
+ clock.advance(seconds: step)
+ mixer.ingest(
+ makeSourceBuffer(burst(seconds: step, left: 0.5, right: 0), at: spanStart, nonInterleaved: true),
+ from: .system
+ )
+ pendingMicrophone.append((
+ deliverAt: Double(index + 1) * step + microphoneLatency,
+ buffer: makeSourceBuffer(
+ burst(seconds: step, left: 0, right: 0.5),
+ at: CMTimeAdd(spanStart, CMTime(seconds: microphoneClockOffset, preferredTimescale: 48_000)),
+ nonInterleaved: false
+ )
+ ))
+ let elapsed = Double(index + 1) * step
+ while let next = pendingMicrophone.first, next.deliverAt <= elapsed + 1e-9 {
+ mixer.ingest(next.buffer, from: .microphone)
+ pendingMicrophone.removeFirst()
+ }
+ mixer.tick()
+ }
+ mixer.finish(atSourceTime: clock.now)
+ return (mixedFrames(sink), mixer)
+ }
+
/// 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