Audio capture pipeline
The audio capture pipeline turns a selected macOS input into session-safe mono PCM for dictation. It waits for a usable route and real audio before it reports readiness, keeps idle capture private, and hands audio to the recognition flow without allowing device changes or teardown work to corrupt a session.
Capture role
The capture layer sits between microphone hardware and the speech-recognition providers. It owns device choice, capture lifetime, packet timing, sample conversion, audio levels, and the boundary that says which samples belong to one dictation session.
The wider lifecycle is described in Voice dictation pipeline. Recognition providers consume the resulting 16 kHz mono samples through the contract described in Speech recognition engines. Text handling starts only after capture has ended, as described in Dictation processing and typing.
Microphone selection
Input priority
The microphone preference coordinator resolves an input from the app's saved priority. It first uses the highest-priority available device, then the separately saved preferred device, and finally the macOS default or another available input. The result is an app choice rather than an automatic response to every macOS default-input change. References: Sources/…/MicrophonePreferenceCoordinator.swift• L337-371, Sources/…/ASRService.swift• L867-885
The selection uses a device UID as the stable identity. A device must have input channels, must be alive, and must not be suppressed. A built-in input that is not usable while the MacBook lid is closed is excluded in that state. References: Sources/…/MicrophonePreferenceCoordinator.swift• L412-419, Sources/…/AudioDeviceService.swift• L16-63, Sources/…/AudioDeviceService.swift• L248-280
Device change observation
Core Audio device changes update the cached view of input availability. The service checks those changes away from the main thread, then reconciles the saved priority when a device appears, disappears, changes identity, or becomes unusable. This prevents a temporary hardware transition from silently selecting a different microphone during a live session. References: Sources/…/AudioDeviceService.swift• L421-481, Sources/…/AudioDeviceService.swift• L590-649, Sources/…/ASRService.swift• L3916-4019
Startup and readiness
Framework startup gate
Audio framework work waits until the initial SwiftUI work has settled. AudioStartupGate opens once after a short delay and lets later permission, device, preview, and capture work proceed through one shared boundary. This keeps Core Audio setup out of the most fragile part of application launch. References: Sources/…/AudioStartupGate.swift• L3-51, Sources/…/ASRService.swift• L1385-1427
Capture preparation
Preparation creates the selected input's capture state and checks its current format without starting hardware input. This removes setup work from the hotkey path while keeping the microphone inactive until recording or level preview begins. References: Sources/…/ASRService.swift• L797-865, Sources/…/ASRService.swift• L888-925, Sources/…/CoreAudioCaptureSupport.h• L34-43
First audio readiness
Starting a route is not enough to make a dictation session ready. The pipeline arms a session and attempt identity, enables recording, and waits for the first accepted PCM. The service confirms the selected input only when first audio arrives and the route has stayed stable. References: Sources/…/ASRService.swift• L1755-1783, Sources/…/ASRService.swift• L1860-1900, Sources/…/AudioCaptureReadinessGate.swift• L3-9
The readiness gate binds one wait to one session and capture attempt. It completes that wait only once, and it ignores signals from an older attempt. Cancellation, format invalidation, and timeout return explicit non-ready results; a wait for a replaced session is marked stale. Failed attempts may retry the same device or move through the remaining input priority. Bluetooth inputs receive a short settling window so route changes during headset microphone startup do not cause an immediate, unnecessary fallback. References: Sources/…/AudioCaptureReadinessGate.swift• L11-42, Sources/…/AudioCaptureReadinessGate.swift• L44-125, Sources/…/AudioCaptureReadinessGate.swift• L136-168, Sources/…/ASRService.swift• L1791-1978, Sources/…/AudioCaptureIdlePolicy.swift• L101-127
The startup sequence is summarized below. It shows why the recording state follows first usable audio rather than the initial start request.
flowchart TD
A[Start request] --> B[Check permission]
B --> C[Resolve usable input]
C --> D[Prepare capture]
D --> E[Start hardware input]
E --> F{First PCM and stable route?}
F -->|yes| G[Mark session ready]
F -->|no| H[Retry or select next input]
H --> C
G --> I[Begin live recognition]
References: Sources/…/ASRService.swift• L1713-1809 Sources/…/ASRService.swift• L1867-2027 Sources/…/AudioCaptureReadinessGate.swift• L44-125
Idle capture policies
Direct capture prewarm
When direct capture is enabled, the app may prepare the selected input while idle. Preparation allocates the capture path but does not start device input, show the microphone privacy indicator, or keep a Bluetooth headset in microphone mode. The prepared state can then be reused when dictation starts. References: Sources/…/ASRService.swift• L797-865, Sources/…/ASRService.swift• L1425-1427
Microphone preview
The onboarding microphone preview uses the same direct capture path as dictation but enables level monitoring instead of recording. A preview can be handed directly to a dictation start so the transition does not discard opening audio. References: Sources/…/ASRService.swift• L1519-1621, Sources/…/ASRService.swift• L1654-1679
Legacy engine suppression
The older AVAudioEngine path is not prewarmed while idle when direct capture is disabled. Creating that engine can change a Bluetooth route to its lower-bandwidth headset mode even when the user is not recording. The pipeline therefore releases an idle engine instead of trading playback quality for faster startup. References: Sources/…/ASRService.swift• L819-833, Sources/…/ASRService.swift• L1027-1044
Silent input recovery
The pipeline watches health windows after direct capture starts. If an internal microphone first produces signal and then produces several effectively silent windows, the service treats the route as unhealthy and schedules recovery. This targets a known silent-input condition without treating every quiet utterance as a device failure. References: Sources/…/AudioCaptureIdlePolicy.swift• L71-99, Sources/…/ASRService.swift• L1185-1208
Audio packet path
Hardware packet intake
The native capture boundary receives hardware-cycle PCM through a Core Audio input callback. The callback does only the work needed to copy each cycle into a fixed ring and publish its timing. A separate consumer drains the ring before it performs conversion, level measurement, or session delivery. References: Sources/…/CoreAudioCaptureSupport.c• L262-355, Sources/…/DirectCoreAudioInput.swift• L367-381
The ring has finite capacity. If the consumer falls behind or a packet is too large, the native layer drops the packet and exposes a count for diagnostics. A dropped packet creates a timing gap; the Swift resampler resets rather than inventing samples across that gap. References: Sources/…/CoreAudioCaptureSupport.c• L10-13, Sources/…/CoreAudioCaptureSupport.c• L284-299, Sources/…/ASRService.swift• L5391-5400
Packet consumption
The Swift wrapper starts a high-priority consumer away from the Core Audio callback. It drains every packet already published when capture stops, then reports packet samples with host and sample-time information to the shared pipeline. This ordering preserves the tail of the recording. References: Sources/…/DirectCoreAudioInput.swift• L367-385, Sources/…/DirectCoreAudioInput.swift• L461-557, Sources/…/ASRService.swift• L2351-2369
Shared backend delivery
Direct Core Audio and the legacy AVAudioEngine tap both call the same AudioCapturePipeline. The common path makes timestamps, session checks, conversion, levels, and buffering consistent even when the source backend differs. References: Sources/…/ASRService.swift• L927-1077, Sources/…/ASRService.swift• L5174-5181, Sources/…/ASRService.swift• L5305-5335
Buffering and conversion
Session boundaries
Each capture attempt carries a session ID, an attempt ID, and a host-time start. The pipeline accepts only packets that fall inside the current time range. At stop it records a host-time end before hardware shutdown, then trims the final packet to that boundary. This prevents pre-start audio and next-session audio from entering the recording. References: Sources/…/ASRService.swift• L5232-5263, Sources/…/ASRService.swift• L5284-5297, Sources/…/ASRService.swift• L2351-2368, Sources/…/ASRService.swift• L5464-5498
Mono PCM conversion
The native boundary accepts supported linear PCM formats and reduces all input channels to one normalized floating-point stream. The shared pipeline then converts that stream to the 16 kHz mono form expected by the recognition layer. A stateful resampler keeps fractional position across hardware packets so non-16 kHz sources do not lose time or create packet-edge breaks. References: Sources/…/CoreAudioCaptureSupport.c• L135-208, Sources/…/CoreAudioCaptureSupport.c• L305-338, Sources/…/ASRService.swift• L5402-5409, Sources/…/ASRService.swift• L5530-5584
The AVAudioEngine and other AVFoundation paths use the shared converter when they receive an AVAudioPCMBuffer. It produces the same mono Float32 target and can downmix or resample source formats before the samples reach recognition. Stereo conversion uses both channels, while a matching mono 16 kHz Float32 buffer keeps its samples unchanged. References: Sources/…/AudioBufferConverter.swift• L31-98, Sources/…/ASRService.swift• L5305-5317, Tests/…/AudioBufferConverterTests.swift• L5-64
Thread-safe recording buffer
The session buffer stores converted samples while capture callbacks and recognition tasks run at the same time. It protects append, range reads, full reads, and clear operations so live previews and final transcription can use stable copies. References: Sources/…/ThreadSafeAudioBuffer.swift• L3-57, Sources/…/ASRService.swift• L1095-1114
Levels and health
The pipeline measures RMS and peak values from converted samples. It turns those values into smoothed display levels and also reports periodic health data for silent-input recovery. Level monitoring can remain active for a microphone preview without enabling recording. References: Sources/…/ASRService.swift• L5265-5282, Sources/…/ASRService.swift• L5349-5461, Sources/…/ASRService.swift• L5586-5657
Engine retirement
Stop ordering
Stopping first closes the session's acceptance boundary and marks the exact end time. The active backend then stops, the direct ring is drained, and the pipeline finishes the recording. Only after live recognition work has completed does the service copy and clear the shared audio buffer for final recognition. References: Sources/…/ASRService.swift• L2317-2414, Sources/…/DirectCoreAudioInput.swift• L493-557
Prepared direct state
After dictation stops, a direct input may remain prepared but stopped. This state keeps fixed capture setup ready for the next session without active microphone input. If preparation cannot be retained, the service invalidates the direct state and retires the older AVAudioEngine path. References: Sources/…/ASRService.swift• L2371-2385, Sources/…/DirectCoreAudioInput.swift• L917-977
Off-main engine release
AVAudioEngine owns an internal audio unit that can wait on its own queue during destruction. The retirement drain releases old engine instances on a serial utility queue and provides a barrier that capture startup and route recovery await before creating another engine. References: Sources/…/AudioEngineRetirementDrain.swift• L21-77, Sources/…/ASRService.swift• L723-795, Sources/…/ASRService.swift• L1037-1044
Route recovery
Topology quiet period
A device, stream, format, clamshell, or audio-service change invalidates the active route. The service stops accepting new session samples, waits for a short quiet period, and then rebuilds the route in one serialized recovery task. This avoids rebuilding while Core Audio is still changing its topology. References: Sources/…/ASRService.swift• L3219-3307, Sources/…/ASRService.swift• L3361-3383
Active route rebuild
During recording, recovery stops the current backend, retires any legacy engine, and starts the resolved input again. It uses the same first-PCM readiness rule as normal startup. If no replacement route becomes ready, it stops the recording without allowing stale audio to continue. References: Sources/…/ASRService.swift• L3467-3627, Sources/…/ASRService.swift• L3631-3669
Idle route rebuild
While idle, recovery rebuilds only when a prepared capture, a microphone preview, or an idle-prewarm request needs it. It invalidates the old prepared state and then restores the preview or prepares the newly resolved input. References: Sources/…/ASRService.swift• L3434-3465, Sources/…/AudioCaptureIdlePolicy.swift• L182-199
Native Core Audio boundary
Capture contract
Sources/…/CoreAudioCaptureSupport.h defines the narrow C boundary between Swift lifecycle control and native input capture. Swift asks the boundary to create, start, stop, destroy, wait for, inspect, and gate a prepared input. Native code returns immutable packet views with Float32 samples and timing metadata. References: Sources/…/CoreAudioCaptureSupport.h• L12-21, Sources/…/CoreAudioCaptureSupport.h• L34-66
Realtime safety boundary
The native callback avoids allocation, locks, resampling, logging, and recognition work. It checks whether capture is running and whether the format is clean, converts the current hardware cycle into a fixed mono packet, and publishes it to the ring. Swift owns the slower work after publication. References: Sources/…/CoreAudioCaptureSupport.c• L262-355, Sources/…/DirectCoreAudioInput.swift• L367-372
Format invalidation
The direct lifecycle records a format fingerprint for the selected device and stream. Core Audio listeners mark the capture dirty when the device, stream, format, sample rate, buffer size, or service changes. The packet gate closes until the lifecycle verifies a matching format after preparation or start. References: Sources/…/DirectCoreAudioInput.swift• L50-71, Sources/…/DirectCoreAudioInput.swift• L1207-1355, Sources/…/CoreAudioCaptureSupport.c• L582-606
Native build bridge
The Swift package owns the single native capture implementation. The app target reaches that implementation through a small bridge so the realtime code remains shared rather than having separate app and package copies. References: Sources/…/CoreAudioCaptureSupportBridge.h• L1-6, Sources/…/CoreAudioCaptureSupportBridge.c• L1-3, Sources/…/CoreAudioCaptureSupport.c• L1-12
Change checklist
When these files or sections are changed, remember to consider these:
- Keep device selection, confirmed active selection, and route recovery aligned. A new fallback must not bypass the user's priority or leave a prepared capture on another device.
- Keep first-PCM readiness tied to the same session and attempt identity used by packet delivery. A stale callback must not release a newer start.
- Keep the native packet layout and Swift packet handler contract aligned. Changes to frame count, sample rate, timing, or pointer lifetime can break the buffer boundary silently.
- Keep the ring's maximum packet size in agreement with device buffer-size checks. A larger hardware cycle must produce a clear unsupported result or a deliberate capacity change.
- Keep session host-time trimming and resampler state together. A change to stop ordering can reintroduce next-session audio or lose the last phoneme.
- Keep direct capture invalidation ahead of route replacement and engine retirement ahead of new AVAudioEngine construction.
- Keep idle prewarm behavior separate from active recording and microphone preview. A setup change can affect privacy indicators and Bluetooth playback mode even when no dictation is running.
Important failure modes
| Trigger | Consequence | Guard |
|---|---|---|
| Permission is denied or no usable input matches the priority | Capture does not start and the dictation session stays inactive | Check authorization, liveness, suppression, and clamshell availability before preparation |
| The selected input starts but sends no first PCM | Startup retries, falls back, or reports a recording error | Use the attempt-scoped readiness gate with a timeout and first-audio signal |
| Bluetooth topology changes during startup | A healthy headset can be rejected or the route can start in an unstable state | Keep same-device retries inside the bounded Bluetooth settling window |
| A device or stream format changes during capture | New packets are rejected and the route is rebuilt; an unrecoverable change stops recording | Mark the generation dirty, close the packet gate, and require a matching fingerprint before reuse |
| The ring consumer falls behind | Packets are dropped and the recording has a timing gap | Track dropped packets and reset resampling across a discontinuity |
| A stop clears the buffer before capture or live recognition drains | The last audio can be lost or an in-flight task can read cleared storage | Mark the end boundary, stop and drain capture, then await streaming work before clearing |
| AVAudioEngine is released on the main actor or overlaps replacement creation | Core Audio can block or deadlock during engine teardown | Detach the engine and await the serial retirement drain before constructing a replacement |
| An internal microphone produces sustained silence after signal | Dictation can appear active while receiving unusable audio | Use periodic RMS and peak health windows to schedule route recovery |
Key files
| File | Why to read it |
|---|---|
| Sources/…/ASRService.swift | Follow the product-level capture lifecycle from prewarm and start through readiness, stop, buffering, and route recovery. |
| Sources/…/MicrophonePreferenceCoordinator.swift | Understand how the app resolves and confirms the user's microphone priority. |
| Sources/…/AudioDeviceService.swift | See how Core Audio devices, liveness, default devices, and clamshell state become usable-input decisions. |
| Sources/…/DirectCoreAudioInput.swift | See the direct capture lifecycle, format validation, packet handoff, and invalidation rules. |
| Sources/…/AudioCaptureReadinessGate.swift | See how first PCM readiness stays tied to one capture attempt and how cancelled or stale waits are isolated. |
| Sources/…/AudioCaptureIdlePolicy.swift | See the policies for prewarm, Bluetooth settling, silent input recovery, and route changes. |
| Sources/…/ThreadSafeAudioBuffer.swift | See the synchronized sample store shared by capture and recognition work. |
| Sources/…/AudioBufferConverter.swift | See the common AVFoundation path for mono Float32 conversion and resampling. |
| Sources/…/AudioEngineRetirementDrain.swift | See why legacy engine release uses an off-main serial barrier. |
| Sources/…/CoreAudioCaptureSupport.h | Read the native-to-Swift packet and lifecycle contract. |
| Sources/…/CoreAudioCaptureSupport.c | See the realtime Core Audio callback and fixed packet ring at the native boundary. |
| Sources/…/CoreAudioCaptureSupportBridge.c | See how the app target reuses the shared native capture implementation. |
| Tests/…/AudioBufferConverterTests.swift | Check the supported mono fast path, stereo downmix, and sample-rate conversion behavior. |
| docs/voice-dictation.md | Read the end-to-end dictation lifecycle around this capture subsystem. |
| docs/speech-recognition-engines.md | Follow how captured 16 kHz mono PCM reaches speech providers. |
| docs/dictation-processing-and-typing.md | Follow what happens after capture and recognition produce the final transcript. |