Introduction
The Audio Hardware Abstraction Layer (HAL) bridges the Android audio framework (AudioFlinger and AudioPolicyService) with the underlying vendor-specific audio drivers (typically ALSA - Advanced Linux Sound Architecture). Because audio requires extreme low-latency processing, the design of the Audio HAL is highly complex, relying heavily on shared memory rather than standard IPC payloads.
Audio HAL Interfaces (IDevice, IStream)
The core of the Audio HAL is divided into two primary interfaces:
IDevice/IPrimaryDevice: Represents the physical audio hardware. It handles global configurations like routing audio to specific ports (speakers, headphones) and managing microphone focus.IStream(IStreamOut/IStreamIn): Represents an active audio session. When a user plays a song, the framework opens anIStreamOut. When recording, it opens anIStreamIn.
// Example of opening an output stream in the Audio HAL
Result openOutputStream(
int32_t ioHandle,
const DeviceAddress& device,
const AudioConfig& config,
// ...
sp<IStreamOut>* outStream);
Audio Policy Engine
The Audio Policy engine lives in the system server and is responsible for making routing decisions (e.g., deciding that audio should switch from the speaker to Bluetooth when headphones are connected). The HAL provides the hardware capabilities to the Policy engine via an XML configuration file (audio_policy_configuration.xml).
The HAL implements setParameters to listen to routing commands from the Policy engine and physically manipulates the underlying ALSA mixer controls (like tinymix) to route the electrical signals to the correct DAC (Digital-to-Analog Converter).
Audio Effects HAL
Audio processing effects (Equalizers, Bass Boost, Acoustic Echo Cancellation, Noise Suppression) are managed by a secondary HAL: the Audio Effects HAL.
Instead of doing expensive DSP (Digital Signal Processing) math on the CPU, vendors can implement the Effects HAL to offload these computations to dedicated hardware DSPs on the SoC. The framework passes the audio buffer to the Effects HAL before sending it to the final output stream.
HAL and AudioFlinger Interaction
To achieve sub-20ms latency, passing raw PCM audio data over Binder would be far too slow. Instead, AudioFlinger (the framework audio mixer) and the vendor HAL establish a Fast Message Queue (FMQ) and a block of shared memory (Ashmem or DMA-BUF).
AudioFlingerwrites mixed PCM data into the shared memory buffer.AudioFlingersends a tiny control command over FMQ saying "Data is ready."- The HAL reads the shared memory and passes it to the kernel ALSA driver.
This zero-copy architecture is what allows Android to support high-fidelity, low-latency "Pro Audio" applications.