Record your screen, ship a demo. Free and open-source, GPU-accelerated, no watermarks, no subscriptions. Windows, macOS, Linux. Actively maintained.
TypeScript cross-platformelectronffmpegopen-sourceproduct-demorustscreen-capturescreen-recorderscreen-recordingscreen-studioscreencastspeech-to-texttypescriptvideo-editingvideo-editorwaylandwgpuwhisper
fix(macos): decode 24-bit integer microphone audio
Etienne Lescot97263b99f7e3
diff --git a/electron/native/screencapturekit/Sources/OpenScreenCaptureCore/AudioTrackMixer.swift b/electron/native/screencapturekit/Sources/OpenScreenCaptureCore/AudioTrackMixer.swiftindex 042347394..d188949f8 100644--- a/electron/native/screencapturekit/Sources/OpenScreenCaptureCore/AudioTrackMixer.swift+++ b/electron/native/screencapturekit/Sources/OpenScreenCaptureCore/AudioTrackMixer.swift@@ -470,11 +470,13 @@ public final class AudioTrackMixer {/// Decodes one capture buffer into gain-applied 48 kHz interleaved-stereo Float.///- /// Both SCStream audio outputs are configured for 48 kHz stereo, so in practice this is a- /// straight Float32 de-interleave. The format-adaptive paths (Int16/Int32, interleaved or- /// not, off-rate sources) exist because the format is the stream's to choose, not ours —- /// and because a resampled source's rounding drift is absorbed by timeline placement- /// rather than accumulating, unlike in a FIFO mixer.+ /// Both SCStream audio outputs are configured for 48 kHz stereo, but only system audio+ /// honours that reliably: the microphone output can arrive in the input device's own format+ /// — 48 kHz mono 24-bit integer on a MacBook Pro's built-in and USB microphones (#709). So+ /// the format-adaptive paths (integers of any width up to 32 bits, interleaved or not,+ /// off-rate sources) are not defensive extras; the format is the stream's to choose, not+ /// ours. A resampled source's rounding drift is absorbed by timeline placement rather than+ /// accumulating, unlike in a FIFO mixer.private func decodeInterleavedStereo(_ sampleBuffer: CMSampleBuffer, gain: Float) -> [Float]? {guard let formatDescription = CMSampleBufferGetFormatDescription(sampleBuffer),let streamDescription = CMAudioFormatDescriptionGetStreamBasicDescription(formatDescription)@@ -487,11 +489,24 @@ public final class AudioTrackMixer {let sourceChannels = Int(asbd.mChannelsPerFrame)let bitsPerChannel = Int(asbd.mBitsPerChannel)let isFloat = asbd.mFormatFlags & kAudioFormatFlagIsFloat != 0+ let isNonInterleaved = asbd.mFormatFlags & kAudioFormatFlagIsNonInterleaved != 0+ // The container each sample sits in, which is not always `bitsPerChannel / 8`: a+ // microphone commonly arrives as 24-bit integer, either packed into 3 bytes or held in 4.+ // Measured on a MacBook Pro (M1, macOS 26.6): the ScreenCaptureKit microphone output+ // delivered 48 kHz mono 24-bit interleaved, which the Float32/Int16/Int32-only decoder+ // rejected buffer by buffer — every take's microphone was silent (issue #709).+ let bytesPerSample = sourceChannels > 0 && asbd.mBytesPerFrame > 0+ ? Int(asbd.mBytesPerFrame) / (isNonInterleaved ? 1 : sourceChannels)+ : (bitsPerChannel + 7) / 8guard asbd.mFormatID == kAudioFormatLinearPCM,+ asbd.mFormatFlags & kAudioFormatFlagIsBigEndian == 0,sourceChannels > 0,asbd.mSampleRate > 0,sourceFrames > 0,- isFloat ? bitsPerChannel == 32 : (bitsPerChannel == 16 || bitsPerChannel == 32)+ isFloat+ ? bitsPerChannel == 32 && bytesPerSample == 4+ : (8...32).contains(bitsPerChannel) && (2...4).contains(bytesPerSample)+ && bitsPerChannel <= bytesPerSample * 8else {return nil}@@ -503,7 +518,6 @@ public final class AudioTrackMixer {// outputs disagree here: system audio arrives non-interleaved, the microphone// interleaved, so sizing this off the channel count alone silently drops every// microphone buffer.- let isNonInterleaved = asbd.mFormatFlags & kAudioFormatFlagIsNonInterleaved != 0let bufferCount = isNonInterleaved ? sourceChannels : 1let bufferList = AudioBufferList.allocate(maximumBuffers: bufferCount)defer { free(bufferList.unsafeMutablePointer) }@@ -524,7 +538,6 @@ public final class AudioTrackMixer {}return withExtendedLifetime(blockBuffer) { () -> [Float]? in- let bytesPerChannelSample = bitsPerChannel / 8// `bufferList` is subscripted against its own count, not the format's channel// count: indexing past `count` would trap rather than degrade.guard bufferList.count > 0 else {@@ -545,11 +558,15 @@ public final class AudioTrackMixer {readers.append(ChannelReader(base: UnsafeRawPointer(data),- sampleCount: Int(buffer.mDataByteSize) / bytesPerChannelSample,+ sampleCount: Int(buffer.mDataByteSize) / bytesPerSample,stride: isNonInterleaved ? 1 : sourceChannels,start: isNonInterleaved ? 0 : sourceChannel,- bytesPerSample: bytesPerChannelSample,- isFloat: isFloat+ bytesPerSample: bytesPerSample,+ isFloat: isFloat,+ // Where the significant bits sit when they do not fill the container.+ // Irrelevant to packed formats, where the two coincide.+ padBits: bytesPerSample * 8 - bitsPerChannel,+ isAlignedHigh: asbd.mFormatFlags & kAudioFormatFlagIsAlignedHigh != 0))}@@ -691,6 +708,8 @@ public final class AudioTrackMixer {let start: Intlet bytesPerSample: Intlet isFloat: Bool+ let padBits: Int+ let isAlignedHigh: Boolfunc value(at frame: Int) -> Float {let index = start + frame * stride@@ -702,10 +721,18 @@ public final class AudioTrackMixer {if isFloat {return base.loadUnaligned(fromByteOffset: offset, as: Float.self)}- if bytesPerSample == 2 {- return Float(base.loadUnaligned(fromByteOffset: offset, as: Int16.self)) / 32_768+ // Integer of any width up to 32 bits: assemble the little-endian bytes at the top of+ // a 32-bit word, so the sign bit lands on bit 31 and one full scale serves every width.+ var word: UInt32 = 0+ for byte in 0..<bytesPerSample {+ let value = UInt32(base.load(fromByteOffset: offset + byte, as: UInt8.self))+ word |= value << UInt32(8 * (4 - bytesPerSample + byte))+ }+ if padBits > 0 && !isAlignedHigh {+ // Low-aligned: the padding is on top, so shift it out to put the sign bit on 31.+ word <<= UInt32(padBits)}- return Float(base.loadUnaligned(fromByteOffset: offset, as: Int32.self)) / 2_147_483_648+ return Float(Int32(bitPattern: word)) / 2_147_483_648}}diff --git a/electron/native/screencapturekit/Tests/OpenScreenCaptureCoreTests/AudioTrackMixerTests.swift b/electron/native/screencapturekit/Tests/OpenScreenCaptureCoreTests/AudioTrackMixerTests.swiftindex 5b8f7ff11..56bef6942 100644--- a/electron/native/screencapturekit/Tests/OpenScreenCaptureCoreTests/AudioTrackMixerTests.swift+++ b/electron/native/screencapturekit/Tests/OpenScreenCaptureCoreTests/AudioTrackMixerTests.swift@@ -455,6 +455,47 @@ final class AudioTrackMixerTests: XCTestCase {XCTAssertLessThan(loudest, 16_500)}+ /// A microphone does not have to arrive as Float32. A MacBook Pro (M1, macOS 26.6) handed+ /// the ScreenCaptureKit microphone output over as 48 kHz mono 24-bit integer, which the+ /// decoder rejected — Float32, Int16 and Int32 were the only formats it read — so every take+ /// recorded there had a silent microphone and one `audio-source-undecodable` warning to show+ /// for it (issue #709). Every integer container CoreAudio describes must decode, at the right+ /// level and with the right sign.+ func testIntegerMicrophoneFormatsAreHeardAtTheirLevel() {+ let layouts: [(bits: Int, bytes: Int, alignedHigh: Bool, label: String)] = [+ (24, 3, false, "24-bit packed (the reported format)"),+ (24, 4, false, "24-bit in 4 bytes, low-aligned"),+ (24, 4, true, "24-bit in 4 bytes, high-aligned"),+ (16, 2, false, "16-bit"),+ (32, 4, false, "32-bit"),+ ]+ for layout in layouts {+ let sink = RecordingSink()+ let clock = TestClock(.zero)+ let mixer = makeMixer(sink: sink, clock: clock, includesMicrophone: true, microphoneGain: 1)+ mixer.beginTimeline(at: clock.now)+ mixer.ingest(+ makeIntegerMonoBuffer(+ alternating: 0.5, frames: sampleRate / 5, at: clock.now,+ bits: layout.bits, bytes: layout.bytes, alignedHigh: layout.alignedHigh+ ),+ from: .microphone+ )+ clock.advance(seconds: 0.2)+ mixer.finish(atSourceTime: clock.now)++ let frames = mixedFrames(sink)+ XCTAssertEqual(seconds(ofFrames: frames), 0.2, accuracy: 0.011, layout.label)+ // Mono feeds both sides at half scale, and +0.5 stays positive: a byte-order or+ // sign-extension mistake shows up as the wrong level or a flipped first sample.+ for lane in 0..<channelCount {+ XCTAssertEqual(Int(peak(frames, from: 0, to: 0.2, channel: lane)), 16_384, accuracy: 2, layout.label)+ XCTAssertGreaterThan(frames[lane], 16_000, layout.label)+ XCTAssertLessThan(frames[channelCount + lane], -16_000, layout.label)+ }+ }+ }+// MARK: - Fixturesprivate func makeMixer(@@ -588,6 +629,79 @@ final class AudioTrackMixerTests: XCTestCase {// MARK: - Readback+ /// A mono, interleaved integer capture buffer, `bits` significant bits in a `bytes`-wide+ /// little-endian container, alternating +amplitude / -amplitude frame by frame.+ private func makeIntegerMonoBuffer(+ alternating amplitude: Float,+ frames frameCount: Int,+ at presentationTime: CMTime,+ bits: Int,+ bytes: Int,+ alignedHigh: Bool+ ) -> CMSampleBuffer {+ var asbd = AudioStreamBasicDescription(+ mSampleRate: Float64(sampleRate),+ mFormatID: kAudioFormatLinearPCM,+ mFormatFlags: kAudioFormatFlagIsSignedInteger+ | (bits == bytes * 8 ? kAudioFormatFlagIsPacked : 0)+ | (alignedHigh ? kAudioFormatFlagIsAlignedHigh : 0),+ mBytesPerPacket: UInt32(bytes),+ mFramesPerPacket: 1,+ mBytesPerFrame: UInt32(bytes),+ mChannelsPerFrame: 1,+ mBitsPerChannel: UInt32(bits),+ 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 byteCount = frameCount * bytes+ let memory = UnsafeMutableRawPointer.allocate(byteCount: byteCount, alignment: 16)+ defer { memory.deallocate() }+ let fullScale = Double(Int64(1) << (bits - 1))+ for frame in 0..<frameCount {+ let sample = Double(frame % 2 == 0 ? amplitude : -amplitude)+ var value = Int64((sample * fullScale).rounded())+ value = min(max(value, -Int64(fullScale)), Int64(fullScale) - 1)+ // High-aligned puts the padding below the value; low-aligned sign-extends above it.+ let word = UInt32(truncatingIfNeeded: alignedHigh ? value << Int64(bytes * 8 - bits) : value)+ for byte in 0..<bytes {+ memory.storeBytes(of: UInt8(truncatingIfNeeded: word >> UInt32(8 * byte)),+ toByteOffset: frame * bytes + byte, as: UInt8.self)+ }+ }+ let bufferList = AudioBufferList.allocate(maximumBuffers: 1)+ defer { free(bufferList.unsafeMutablePointer) }+ bufferList[0] = AudioBuffer(mNumberChannels: 1, mDataByteSize: UInt32(byteCount), mData: memory)+ XCTAssertEqual(+ CMSampleBufferSetDataBufferFromAudioBufferList(+ sampleBuffer!, blockBufferAllocator: kCFAllocatorDefault,+ blockBufferMemoryAllocator: kCFAllocatorDefault, flags: 0,+ bufferList: bufferList.unsafePointer+ ),+ noErr+ )+ XCTAssertEqual(CMSampleBufferSetDataReady(sampleBuffer!), noErr)+ return sampleBuffer!+ }+private func mixedFrames(_ sink: RecordingSink) -> [Int16] {var samples = [Int16]()for buffer in sink.buffers {