Writing an OS Kernel from Scratch | 350: Audio Subsystem — How ALSA Plays Sound

Abstract: Audio is one of the most commonly used peripheral functions of computers, indispensable from playing music to video calls. This article takes you through the PCM principles, HDA audio architecture, Linux ALSA driver, and aplay hands-on practice to help you understand the codec chain of digital audio.


1. PCM: The Essence of Digital Audio

1.1 Sampling, Quantization, Encoding

Analog sound is a continuously varying waveform. To turn it into a digital signal, three steps are needed:

Bash
Analog Signal (Continuous) → Sampling (Discrete Time) → Quantization (Discrete Amplitude) → Encoding (Binary)

Sample Rate: How many points are sampled per second. Common values:

  • 44100 Hz (CD quality)
  • 48000 Hz (DVD/professional audio)
  • 96000 Hz (Hi-Res)

Bit Depth: How many bits describe the amplitude per sample point. Common values:

  • 16 bit (CD quality)
  • 24 bit (professional recording)
  • 32 bit float (DSP internal processing)

Channels: 1=Mono, 2=Stereo, 5.1=Surround, 7.1=…

1.2 PCM Data Stream

Bash
Time →  0    1    2    3    4    5    6    7
      ┌────┬────┬────┬────┬────┬────┬────┬────┐
Ch L  │ S0 │ S1 │ S2 │ S3 │ S4 │ S5 │ S6 │ S7 │  ← 16-bit LE
Ch R  │ S0'│ S1'│ S2'│ S3'│ S4'│ S5'│ S6'│ S7'│  ← 16-bit LE
      └────┴────┴────┴────┴────┴────┴────┴────┘

For 44100Hz/16bit/stereo:
Bytes per second = 44100 × 2 × 2 = 176,400 bytes/sec
Bitrate = 1.411 Mbps

1.3 Fun ASCII Waveform

Bash
Original analog waveform:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
          ╱╲        ╱╲╱╲      ╱╲
~~~~~~~~ ╱    ╲____╱      ╲__╱  ╲________________

PCM samples (4-bit quantization, illustrative only):
Sample points: *   *   *   *   *   *   *   *
        ↓   ↓   ↓   ↓   ↓   ↓   ↓   ↓
     ┌──┬──┬──┬──┬──┬──┬──┬──┐
     │0307│0F│0B│0307│0F│0B│  (4-bit sample values)
     └──┴──┴──┴──┴──┴──┴──┴──┘

1.4 Interleaved vs Non-interleaved

Interleaved — the most common format:

Bash
[L0][R0][L1][R1][L2][R2]...
  ↑   ↑
  Stereo frame (a pair of samples)

Non-interleaved — used for multi-channel or complex layouts:

Bash
[L0][L1][L2][L3]...
[R0][R1][R2][R3]...

2. ALSA: Linux Audio Architecture

2.1 ALSA Layers

Bash

User Space
├── aplay / arecord (alsa-utils)
├── PulseAudio / PipeWire (sound servers)
└── libasound (alsa-lib, application programming interface)
    ↓
Kernel ALSA Core (sound/core/pcm_native.c)
├── PCM Native API (playback/capture open/read/write)
├── Control API (volume, switches)
└── Raw MIDI API
    ↓
Platform Driver Layer
├── HDA Intel (sound/pci/hda)
├── USB Audio (sound/usb)
├─... [truncated]
Last modified: 2024年1月30日

Author

Comments

Write a Reply or Comment

Your email address will not be published.