Audio DMA and Clock Drift

Two crystals never run at exactly the same speed. At 50 ppm on a 48 kHz stream, the buffer gains 2.4 samples every second, and sooner or later you hear a click.

Learn how a microcontroller streams sound with DMA double buffers, why a late refill or a slow clock makes a click, and how feedback, fill-level control and sample-rate conversion remove it.

Pick Free run and watch the ring fill until it clicks. Then pick Trim and watch a small controller hold the level still. After that we build every piece from zero.

You need a rough idea of what a sample is (one number that says how loud the wave is at one instant). We build the rest from zero.

Part of the Firmware from Zero to Expertise series, audio track. Built from the primary sources in the Field Guide. Grounded on Valvano and Yerraballi, Embedded Systems: Shape the World, Chapter 6 (their text is not copied).

Feed a buffer from a clock that drifts

50 ppm

Model, not silicon. A 256-frame ring that starts half full, a 48,000 Hz drain, and a source that runs at the chosen ppm offset. The clock runs 10 times faster than real time. The trim limit of 300 ppm and the controller gains are illustrative.

Chapter 0

Why a Speaker Clicks Every Few Seconds

See how a steady stream of sound depends on a small chip that never falls behind and never runs ahead

You build a small music player on an STM32 board. It reads a song from memory and sends it to a speaker through a chip called a DAC. For ten seconds the sound is perfect. Then you hear a tiny click. Ten seconds later, another click.

The code has no bug that you can find. The song file is fine. The click comes on a schedule, like a clock. That schedule is the clue, and this lesson explains where it comes from.

Two things can make a stream click. The first is that your code arrives late once, and the speaker runs out of sound to play. The second is quieter: two clocks that both claim to run at 48,000 ticks a second do not agree, and one slowly gets ahead. We take them in that order.

What is audio, to a chip?

Sound is a wave in the air. To store it, a chip measures the wave very often and writes each measurement as a number. One measurement is a sample. The measuring rate is the sample rate. A common rate is 48,000 samples each second, written 48 kHz.

A stereo player sends two samples at each tick, one for the left speaker and one for the right. We call that pair a frame. With 16 bits for each sample, a frame is 4 bytes. At 48 kHz that is 48,000 frames and 192,000 bytes every second.

The DAC (digital to analog converter) turns each frame into a voltage. It wants a new frame at every tick, with no gaps. It does not wait for you. If no new frame is ready, it plays the old one again, or silence. Both are a defect in the wave.

The problem with doing it one frame at a time

The simplest design is a timer that fires 48,000 times a second. Each time, an interrupt service routine (ISR, a function the chip runs at once when a signal arrives) writes the next frame to the DAC. Valvano and Yerraballi teach sound this way: a periodic interrupt writes one sample per tick.

It works for a lab piano. It is too busy for a real player. On a Cortex-M, an interrupt costs at least 12 cycles just to enter, plus the work of saving state and leaving. Do that 48,000 times a second and the chip has little time left to decode music, run a screen or talk to a radio.

So firmware uses a trick. A helper circuit moves the frames, and your code works on whole groups of frames at a time. The helper is DMA (direct memory access): a small engine that copies data between memory and a peripheral without using the CPU. Chapter 1 builds it. First we need the unit it works in.

The block

A block is a group of N frames that the code prepares in one go. The DMA plays one block while the CPU prepares the next. The block size sets two numbers. The period is how long one block lasts: N divided by the sample rate. The interrupt rate is the sample rate divided by N.

Take N = 64 at 48 kHz. The period is 64 / 48,000 = 1.333 ms. The chip takes 750 interrupts a second instead of 48,000. And the CPU has 1.333 ms to make the next 64 frames. On a 168 MHz STM32F407, 1.333 ms is about 224,000 cycles.

That is the whole game. The player must make each block before its period ends, every time, for as long as the music plays. Turn the knob below and watch the numbers move.

Cut one second of sound into blocks

The strip shows 10 ms of a 48 kHz stream. Each box is one block. Each arrow is the interrupt that asks the code for the next one. Drag the block size.

64 frames

Sample rate 48,000 Hz, stereo, 16-bit, so 4 bytes a frame. Cycle counts assume a 168 MHz Cortex-M4 (STM32F407, its maximum clock). Interrupt entry of 12 cycles is the Arm figure for Cortex-M3 and M4 with zero-wait-state memory. The 100-cycle exit and bookkeeping cost is illustrative.

On real hardware. On an STM32 Nucleo (F4 class), toggle one pin in the interrupt that serves each block. Measure the time between edges on a scope or logic analyzer. With one interrupt for every block of N = 64 frames at 48 kHz, expect 1.333 ms between edges.

Small blocks mean low delay but many interrupts. Large blocks mean few interrupts but a long delay between a button press and a sound. Chapter 5 turns that trade into a map. For now keep one fact: every block has a deadline, and the deadline is its own period.

Two kinds of failure

When the deadline is missed once, the DAC has nothing new to play. We call that an underrun. The opposite also exists. If the source delivers frames faster than the speaker plays them, the buffer overflows. We call that an overrun. Both are heard as a click or a dropout.

Chapters 1 to 2 handle the late block. Chapters 3 to 7 handle the drifting clock. Chapter 8 shows how to find either one on a real board with a probe. Chapter 9 is the field guide.

  1. Ping-pong buffers: how DMA plays one half while you fill the other.
  2. Deadlines and underruns: what happens when the fill is late once.
  3. Two clocks that disagree: parts per million, and how fast a buffer drains.
  4. Hear the click: what a slipped sample sounds like.
  5. Buffer count versus latency: choose how much safety you can afford.
  6. Following the master clock: USB feedback and fill-level control.
  7. Resampling: asynchronous sample-rate conversion.
  8. On the bench: find the bug with a logic analyzer.
  9. Field Guide: numbers, checklist, code and sources.
A 48 kHz stereo player uses a block of 96 frames. How long does the CPU have to make each block?

Chapter 1

Ping-Pong Buffers

Let the DMA play one half of a buffer while your code fills the other half, then swap

Picture a baker with two trays. One tray sits in front of the customer, who eats one roll at a steady pace. The other tray is behind the counter, where the baker loads fresh rolls. When the customer finishes a tray, the trays swap places. The customer never waits, as long as the baker finishes before the swap.

That is a ping-pong buffer, also called a double buffer. One half is being read by the hardware. The other half is being written by your code. Each time the hardware finishes its half, the roles swap.

One block of memory, two halves

On an STM32, you set up the DMA once. You give it three things. The source address is a block of RAM. The destination address is the data register of the I2S or SAI peripheral (the part that sends the bits to the DAC over a standard audio wire format, covered in the previous lesson). The count is how many items to move before it stops.

Now the key setting. You turn on circular mode. When the DMA reaches the end of the buffer, it jumps back to the start and carries on. It never stops. The count register reloads itself.

Take our block size from Chapter 0, N = 64 frames. The buffer holds two blocks, so 128 frames. Each frame is 2 samples of 16 bits, so the buffer is 128 × 4 = 512 bytes, or 256 half-words. At 48 kHz the DMA walks that buffer in 2.667 ms and starts again, forever.

Two flags tell you which half is free

The DMA raises an interrupt at two moments. When it has moved half of the items, it sets the half-transfer flag (HT). When it has moved all of them, it sets the transfer-complete flag (TC), and then wraps.

Read that again for playback. At HT the DMA has just finished reading the first half. It is now reading the second half. So the first half is free, and your code must write it now. At TC the second half is free.

The ST HAL driver names these events HAL_I2S_TxHalfCpltCallback and HAL_I2S_TxCpltCallback. You start the stream once with HAL_I2S_Transmit_DMA. In normal mode the stream stops after one pass, so the usual fix for continuous sound is circular mode.

Play the ping-pong

The purple marker is the DMA reading. When it crosses a boundary, the interrupt fires and the CPU fills the half it just left. Switch on Skip the refill and watch an old block play twice.

Model, not silicon. Real playback of a 64-frame half takes 1.333 ms at 48 kHz. Here it is slowed to about 1.4 seconds so you can watch. Block numbers stand for 64 frames of audio.

On real hardware. On an STM32 Nucleo with an I2S DAC board, toggle one pin in each callback. You should see two pulses per buffer pass, evenly spaced, 1.333 ms apart. Fill the buffer with a ramp and check the sound output on a scope.

Your code looks like the sketch below. The buffer is one array. The two callbacks fill the two halves. Nothing else touches the DMA after the start call.

c, STM32 HAL/* 48 kHz stereo, 16-bit. Two blocks of 64 frames in one circular buffer. */
#define N_FRAMES 64
#define CH       2
static int16_t tx[2 * N_FRAMES * CH];        /* 256 half-words = 512 bytes */

void audio_start(void) {
    fill_block(&tx[0],            N_FRAMES);  /* prime both halves   */
    fill_block(&tx[N_FRAMES * CH], N_FRAMES);
    HAL_I2S_Transmit_DMA(&hi2s3, (uint16_t *)tx, 2 * N_FRAMES * CH);
}
void HAL_I2S_TxHalfCpltCallback(I2S_HandleTypeDef *h) {  /* first half just played */
    fill_block(&tx[0], N_FRAMES);
}
void HAL_I2S_TxCpltCallback(I2S_HandleTypeDef *h) {      /* second half just played */
    fill_block(&tx[N_FRAMES * CH], N_FRAMES);
}

The size argument counts 16-bit items for 16-bit data. Check the HAL header for your part and your data width, because 24-bit and 32-bit frames count differently.

The other way: double-buffer mode

Some STM32 DMA controllers offer a second method. In double-buffer mode you turn on the DBM bit in the stream control register. The stream then has two memory addresses, M0AR and M1AR, and swaps between them each time a transfer completes. The CT bit tells you which one is playing now.

The two buffers can sit anywhere in RAM, and you get one interrupt per block. There is a rule to respect. The reference manuals say you may write M1AR only while CT is 0, and M0AR only while CT is 1. Writing the one in use sets the transfer-error flag and stops the stream.

Which is better? Circular with two halves is simpler and works on every DMA. Double-buffer mode lets you point at buffers a decoder already filled, so you avoid a copy. Both give the same promise: one block plays while you make the next.

One trap on bigger chips

Cortex-M7 parts such as the STM32F7 and H7 have a data cache: a small, fast memory that sits between the core and RAM. Your code writes samples into the cache, but the DMA reads RAM. If the samples are still in the cache, the DMA plays old data. Clean the cache for that range before the DMA reads it (CMSIS offers SCB_CleanDCache_by_Addr), or put the audio buffer in a region that the MPU (memory protection unit, which sets rules for each memory region) marks as non-cacheable.

A circular DMA plays a 2-half buffer. The half-transfer callback fires. What should your code do?

Chapter 2

Deadlines and Underruns

Find out how late your code may be before the speaker runs dry, and measure it

A player works for an hour. Then you plug in a screen and it clicks every time the screen redraws. Nothing in the audio code changed. Something else now takes the chip away for a few milliseconds, and the audio cannot wait.

This chapter is about that late block. It is the first of the two failures from Chapter 0, and it has a clean rule you can compute.

The deadline, in numbers

With two halves of N = 64 frames, each half lasts 1.333 ms. When the DMA enters one half, your code has until it leaves that half to finish the other one. Miss it, and the DMA reads a half that still holds old samples. That repeat is an underrun.

Your code needs time to do its job. Say filling a block takes 0.33 ms (a quarter of the period). Then the code can afford to start up to 1.0 ms late and still make it. We call that spare time the slack. Slack equals the period minus the work.

Slack is small for two halves. A 1 ms stall is enough to break it. A flash erase can stall a Cortex-M much longer. A UART printf inside the ISR can take milliseconds. A higher-priority interrupt that runs long does the same. A decoder that spends 3 ms on one hard music frame does the same.

More blocks in the queue buy more slack

The fix is a queue. Instead of two halves, keep k blocks in the ring. The DMA plays one. The others wait, already filled. If your code stalls, the DMA drains the waiting blocks one by one. Each waiting block buys one more period of delay.

The rule is short. With k blocks of period P, k − 1 are normally full and waiting. A stall can last up to about (k − 1) × P before the speaker runs dry, minus the work time. The price is delay: the sound you hear is about k × P behind the code that made it.

Before the work time: k = 2, P = 1.333 ms covers 1.33 ms. k = 4 covers 4.00 ms, with a delay of 5.33 ms. Take off the work time (a quarter period, 0.33 ms) and k = 4 covers 3.67 ms.

Try it. The page below runs three stalls through a model of the queue. Set the block size, the number of blocks and the stall length. Find the smallest k that survives a 6 ms stall at N = 64.

Stall the filler, watch the queue

The line is the number of ready blocks waiting. Yellow bands are the times your code is stalled. A red mark is a deadline the queue could not meet.

Block size
Blocks in the ring
3.0 ms

Model, not silicon. Three stalls at 0.6 s, 1.5 s and 2.4 s. Filling one block takes a quarter of its period (illustrative). The queue starts with k − 1 blocks ready and one playing. A missed deadline replays the old block.

On real hardware. On an STM32 Nucleo, set a pin high when the fill starts and low when it ends, then trigger a long operation, such as a flash erase or a UART print. Read the longest gap. That is the stall the ring must cover.

Failure mode: the click, the measurement, the fix

Symptom. A click that appears when something else happens: a redraw, a log line, a flash write, a radio event. It can sound like a short crackle or a tiny gap.

Measurement. Set a spare pin high when the half-transfer interrupt starts. Set it low when the refill ends. A logic analyzer or scope on that pin shows two numbers: how long the work takes, and how long after the DMA event it starts. On Cortex-M3, M4 and M7 you can also read the cycle counter in the DWT unit, and divide cycles by the clock rate to get time.

Fix. First move slow work out of the ISR. The ISR should only note which half is free and wake a task. The task, running at a high priority in your RTOS, does the fill. Second, add blocks until the worst measured stall fits inside (k − 1) × P with margin. Third, remove the cause if you can: keep flash erases away from playback, and send logs from a low-priority task.

c, ISR does almost nothingstatic volatile uint8_t free_half;          /* 0 = first, 1 = second */
void HAL_I2S_TxHalfCpltCallback(I2S_HandleTypeDef *h) { free_half = 0; xSemaphoreGiveFromISR(audio_sem, &woken); }
void HAL_I2S_TxCpltCallback(I2S_HandleTypeDef *h)     { free_half = 1; xSemaphoreGiveFromISR(audio_sem, &woken); }

void audio_task(void *arg) {                      /* highest priority task */
    for (;;) {
        xSemaphoreTake(audio_sem, portMAX_DELAY);
        uint32_t t0 = DWT->CYCCNT;
        fill_block(&tx[free_half * N_FRAMES * CH], N_FRAMES);
        worst_cycles = max(worst_cycles, DWT->CYCCNT - t0);  /* compare with cycles per period */
    }
}

This pattern has one weakness. If the task is late by more than one period, it sees one semaphore (a counter that wakes a task) for two events, and one half is never filled. A queue of block numbers, as in the lesson on rings and queues in the real-time track (planned), fixes that. For the interrupt basics, see Interrupts, DMA and the 12 Cycles and Embedded RTOS.

A ring holds 4 blocks of 64 frames at 48 kHz. Roughly how long a stall can the filling code survive?

Chapter 3

Two Clocks That Disagree

Compute exactly how long a buffer lasts when the source and the speaker run on different crystals

Two runners start side by side. Both say they run one lap a minute. One has a watch that is a hair fast. After a few laps, one runner is a few steps ahead. Nobody lied. The watches just differ a little, and the gap only grows.

Now put a bucket between them. The first runner pours water in. The second drinks it. If the pour is a hair faster than the drink, the bucket fills, slowly, and sooner or later it overflows. This is the second failure from Chapter 0.

Where the two clocks come from

A crystal is a small slice of quartz that rings at a fixed frequency when you apply a voltage. A chip counts the rings to make time. No crystal is perfect. The maker states an error range in ppm, parts per million. An error of 50 ppm means the clock is off by 50 in every million ticks, or 0.005%.

Audio crosses between clock domains all the time. A USB host sends audio frames on its own clock, and your board plays them on the codec clock. A network stream arrives on the sender's clock. A microphone chip and a DAC chip each have their own oscillator. In each case the sample rate is nominally 48,000 Hz on both sides, but never exactly.

The size of the error varies. Crystals are sold with tolerances of tens of ppm, and temperature moves them further. Check the datasheet of the part you use. A two-crystal link can be off by the sum of the two errors. Chapter 10 of the acoustic echo cancellation lesson uses 100 ppm as a common value. This lesson uses 20, 50 and 100 ppm as round, illustrative numbers.

The arithmetic

Say the source runs fast by d parts per million. Each second it delivers 48,000 × (1 + d × 10−6) frames, but the speaker consumes only 48,000. The extra is the drift rate.

r
The drift rate: how many extra frames pile up in the ring each second.
fs
The sample rate, here 48,000 frames a second.
d
The clock mismatch in ppm. A positive number means the source is faster.
T
The time until the ring is full or empty, and the first click is heard.
R / 2
The room in the ring: a ring of R frames that starts half full has R / 2 frames of room.
r
The same drift rate from the first equation.

Work it with d = 50 and a ring of R = 256 frames. The drift rate is 48,000 × 50 / 1,000,000 = 2.4 frames a second. The room is 128 frames. So T = 128 / 2.4 = 53.3 seconds. One click, then another about every 27 seconds if each click drops a 64-frame block.

Now change the numbers. At 100 ppm, r is 4.8 and T is 26.7 s. At 20 ppm, r is 0.96 and T is 133 s. A ring of 1,024 frames at 50 ppm gives T = 512 / 2.4 = 213 s. A bigger ring only delays the click. It never removes it, because the drift never stops.

Over longer spans the numbers get large. At 50 ppm one hour of playback gathers 0.18 s, or 8,640 frames. That is 135 blocks of 64. This is why a bug of this kind passes a 10-minute test and fails in a long demo.

Count down to the first click

The blue line is the ring fill, starting half full. The grey lines are half and double your mismatch. Drag the mismatch, then pick a bigger ring and see how little it buys.

Ring size
50 ppm

Arithmetic is exact for a constant offset at 48,000 Hz. Real crystals also wander with temperature, so real times vary. The ppm values are round illustrative numbers, not a datasheet.

On real hardware. Take two boards with separate crystals, such as an RP2040 board sending I2S and an STM32 Nucleo receiving it as a slave without a shared clock. Print the ring fill once a second for ten minutes. Divide the slope in frames per second by 48 to get the mismatch in ppm.

The pitch is fine. The buffer is not.

A 50 ppm speed error shifts pitch by about 0.09 cents, since 1200 × log2(1.00005) = 0.087. A cent is a hundredth of a semitone. No one can hear that. The harm is not in the pitch. The harm is that the buffer level moves, and moves without end. That is why the fix of Chapters 6 and 7 watches the buffer, not the pitch.

A source runs 100 ppm fast at 48 kHz. The ring holds 1,024 frames and starts half full. About when does it first overflow?

Chapter 4

Hear the Click

See what one dropped sample does to a wave, then listen to it repeat at the drift rate

Hum a steady note and clap once, very softly, in the middle. Your ear hears the clap even though the note is louder. A click is not about loudness. It is about a sudden change in the wave, and the ear is very good at noticing sudden changes.

A slipped sample is exactly that. It is a tiny jump in a smooth wave. This chapter shows the jump, measures it, and lets you hear it.

What the DMA does when the buffer is wrong

There are three ways the stream goes wrong, and each leaves a different mark.

The first is a dropped sample. The buffer was too full, so the code threw one frame away. The wave skips ahead by one step. The second is a repeated sample. The buffer was too empty, so one frame played twice. The wave stalls for one step. The third is a lost block. An underrun replays old data or plays zeros for a whole block, for instance 64 frames, which is 1.33 ms.

Look at the stream as numbers. A sine tone at frequency f, sampled at 48,000 Hz, moves by up to A × 2π × f / 48,000 between two neighbouring frames, where A is the amplitude. For a 1 kHz tone that is 0.131 × A. Drop one frame and the wave jumps by that much at once, on top of its usual step.

Take A = 0.5 of full scale. The extra jump is 0.5 × 0.1309 = 0.0654, which is 20 × log10(0.0654) = −23.7 dB below full scale. At 8 kHz the step is eight times larger, 0.524, about −5.6 dB. Higher tones click louder, because their samples change faster.

Here is how the sign of the drift tells you which slip you will see. If the source is faster, the ring fills, and the code must drop a frame. If the source is slower, the ring empties, and the code must repeat one. Play a counter instead of music and read the steps in the capture, as the bench test below does: a +2 step says the source is fast, a 0 step says it is slow. Mixed steps point to jitter, not drift.

Take the lost block. At 48 kHz, 64 zero frames last 1.33 ms. A 1 kHz tone loses 1.33 cycles of wave. The output jumps from the tone to zero and back. Each edge is a jump as large as the tone itself, 0.5 of full scale in our example, so about 18 dB louder than the one-frame slip.

Why a small jump is so audible

A smooth tone has all its energy at one frequency. A sudden jump is not smooth. It has energy at every frequency, from low to high, with no pattern. That broad spread of energy is what the ear hears as a tick, even when the jump is small.

The rate matters too. At 50 ppm, a 48 kHz stream slips 2.4 frames a second. If each slip is a jump, you hear a tick about every 0.42 s: a soft, steady ticking rhythm under the music. Steady rhythms are easy to notice. Loud music hides the ticks. A quiet room with a pure tone does not.

Slip a sample, then listen

Grey dots are the samples the DAC should play. The blue line is what it plays after the slip. Pick a kind of slip and a tone. Press Play to hear it repeat at the rate your mismatch causes. Turn your volume down first.

1,000 Hz
50 ppm

Model, not silicon. The sound is made in your browser at your speaker's own rate: a sine of amplitude 0.15 with a phase jump of one 48 kHz sample (or 64 silent frames) at each slip time. Your speakers and room change how it sounds. Real music masks more of the click than a pure tone does.

On real hardware. On an STM32 Nucleo with an I2S DAC board, make the firmware play a counter instead of music: frame number n in the left channel. Capture the I2S lines with a logic analyzer and its I2S decoder. In the captured numbers, each step should be +1. A step of +2 is a dropped frame. A step of 0 is a repeated frame. Count them over ten minutes and compare with your ppm estimate.

python, check a captured counterdef find_slips(frames):                    # frames: left-channel values from the capture
    slips = []
    for i in range(1, len(frames)):
        step = (frames[i] - frames[i - 1]) % 65536   # the counter wraps at 16 bits
        if step != 1:
            slips.append((i, "repeat" if step == 0 else "drop", step))
    return slips                           # slips per minute = drift in frames per minute

Failure mode: the faint tick

Symptom. A faint tick on a quiet pure tone or a quiet intro, at a steady rate, only after the player has run a while.

Measurement. The counter test above. Divide the slips per minute by 60 and by the sample rate, then multiply by a million. That gives the mismatch in ppm. If it is 2.4 slips a second, you have 50 ppm.

Fix. The click rate tells you the size of the drift. The cure is not a larger buffer. Chapters 6 and 7 show how to follow the source clock so the slips never happen.

Why does a 6 kHz tone click louder than a 600 Hz tone of the same amplitude when one frame is dropped?

Chapter 5

Buffer Count Versus Latency

Choose how many blocks to keep, and see what safety costs in delay and in RAM

You sing into a microphone and hear yourself in headphones. If the headphones play your voice 5 ms late, it feels like singing with a friend about 1.7 metres away. As the delay grows to a few tens of milliseconds, many people start to hear an echo and stumble (a rough rule that varies from person to person). Now think of a music player on a bus. Nobody cares if the song starts 100 ms late.

The same buffer choice is right for one case and wrong for the other. This chapter gives you the numbers to choose.

Delay: what a buffer costs

Latency is the delay between the moment your code writes a sample and the moment the speaker plays it. A ring of k blocks, each of N frames, holds k × N frames. At 48 kHz, the worst-case delay is the time to play them all.

latency = k × N / 48,000 s.   4 blocks of 64 frames: 256 / 48,000 = 5.33 ms.

Sound in air travels about 343 metres a second. So 5.33 ms is the delay of listening from 1.8 metres away. That gives you a feel for what each millisecond means. A full audio path has more delays than the ring: the input buffer on the way in, the converter chips and their digital filters, and any USB or radio link. Read the datasheets, then add them up.

Safety: what a buffer buys

From Chapter 2, a ring of k blocks keeps k − 1 of them waiting. A stall can last until those are gone. Your own fill work eats part of the last block, so we count 0.25 of a period for the work.

cover = (k − 1.25) × N / 48,000 s.   4 blocks of 64: 2.75 × 1.333 = 3.67 ms.

Two numbers from your own board decide whether a design is safe. The first is the worst stall you measured: the longest time the fill code was delayed. The second is the delay your product can accept. Safe means cover is at least the worst stall, and latency is at most the budget.

RAM: what it all weighs

Blocks live in RAM. A frame of stereo 16-bit audio takes 4 bytes, so k blocks of N frames take k × N × 4 bytes. For 4 blocks of 64 frames that is 1,024 bytes. For 8 blocks of 256 frames it is 8,192 bytes. If the codec wants 24-bit samples in 32-bit slots, a frame is 8 bytes and everything doubles. On a small chip with 32 KB of RAM, that matters.

Small blocks cost CPU instead. Chapter 0 showed that block size sets the interrupt rate. Eight blocks of 32 frames means 1,500 interrupts a second. Each carries its own entry cost and its own fill call. A long, slow block is cheaper per frame than a short one.

Find a design that is safe and quick

Each cell is one design, with its latency in ms. Green meets both limits. Yellow is too slow for your budget. Red does not survive your stall. Set the two limits, then click cells.

10.0 ms
3.0 ms

Model, not silicon. Cover is (k − 1.25) periods, with the fill taking a quarter of a period (illustrative). RAM is for stereo 16-bit. The star marks the passing design with the least RAM. Sound speed 343 m/s.

On real hardware. On an nRF52840 DK or a Nucleo board, toggle one pin when your fill code starts and when it ends. Leave the player running while you use the buttons, the radio and the display. Read the longest gap between a DMA event and the fill start on a logic analyzer. That is your worst stall. Pick k from it, with some margin.

Here is a worked path for the voice-monitor example. The microphone side uses 2 blocks of 32 frames, so its ring holds 64 frames, 1.33 ms. The speaker side uses 3 blocks of 32, 96 frames, 2.0 ms. Add 0.5 ms for the two converters (illustrative). The total is 3.83 ms, about 1.3 metres of air. That passes a 5 ms budget. Now change both sides to blocks of 128: 5.33 ms plus 8.0 ms plus 0.5 ms is 13.8 ms, and it fails.

Failure mode: a safe design on the bench, a click in the field

Symptom. No clicks in the lab. Clicks on a customer's unit, now and then.

Measurement. Your lab test never made the rare stall. Record the maximum stall over days, not minutes, with the radio and the storage active. Keep a counter of underruns in firmware and report it.

Fix. Size the ring from the rare worst case. If the delay then grows too large, cut the stall at its source rather than keep adding blocks.

The worst stall is 4 ms and the latency budget is 6 ms. Using cover = (k − 1.25) × N / 48,000, which design passes?

Chapter 6

Following the Master Clock

Pick one clock to be the boss, then measure it well enough that the other side can keep up

Two drummers play in a band. If both follow their own watch, they drift apart. If one listens to the other and nudges the tempo a hair, they stay together for hours. The listener never stops the song. It only leans a little.

Firmware does the same. Chapter 3 showed that a bigger buffer only delays the click. The lasting fix is to make the two sides follow one clock, or to measure the gap and correct it a little at a time.

Five ways to follow

You can choose which side leans. Each choice has a different price.

MethodWho adaptsHowPrice
One shared clockNobodyThe DAC clock also drives the source, or the MCU takes its I2S clocks from the codecNeeds a source you control
Feedback to the sourceThe sourceThe device reports its true rate. The USB host sends a few more or fewer frames per packetNeeds a protocol that has it
Trim your own clockThe consumerA fill-level controller nudges a fractional PLL (a circuit that builds a fast clock from a slow one) by a few ppmNeeds a trimmable clock
ResampleThe dataConvert the stream by a ratio very near 1 (Chapter 7)CPU or chip, a little noise
Drop or repeat a frameThe dataSkip one frame when the fill leaves a band (the hero's middle choice)A small click each time

USB asynchronous feedback

A USB sound card is the classic case. The host sends audio in packets on its own 1 ms clock. The device plays on its own audio clock. In asynchronous mode the device owns the audio clock and tells the host how fast it really consumes, using a feedback endpoint: a small channel that carries one number back to the host.

That number is the average number of frames per USB frame, in fixed point. For full speed (1 ms frames) it is a 3-byte value in 10.14 format: 10 bits of whole frames, 14 bits of fraction. For high speed (125 µs microframes) it is a 4-byte value in 16.16 format. Implementers cite section 5.12.4.2 of the USB 2.0 specification for this.

Worked example at 48 kHz. Full speed wants 48.0 frames per ms. In 10.14 that is 48 × 16,384 = 786,432, or 0x0C0000. High speed wants 6.0 frames per microframe: 6 × 65,536 = 393,216, or 0x00060000. A device that runs 50 ppm fast would report 48.0024 and the host would soon send a 49-frame packet now and then.

How well can you measure the clock?

The device measures by counting. It counts ticks of its audio master clock (MCLK) during a window set by the host's timing. The count is a whole number, so the answer is off by up to one tick. The relative error is 1 / (MCLK × window).

With MCLK at 12.288 MHz (256 × 48 kHz) and a 1 ms window, one tick is 81 ppm. That is bigger than the drift you want to measure. A longer window averages it out: 8 ms gives 10 ppm and 64 ms gives 1.3 ppm. The report format has a floor too. The 10.14 format steps by 1 / (48 × 16,384) = 1.3 ppm at 48 kHz.

Measure the clock you must follow

The curves show the worst error of one count against the window length. The dashed line is the finest step the 10.14 report can show. Pick a clock, set the true mismatch and a window, and read what the host would be told.

Audio master clock
8 ms
+35 ppm

Model, not silicon. The count is the whole number of MCLK ticks in the window, taken with a fixed phase of 0.37 tick. The report is the full-speed 10.14 value. Format details follow the USB 2.0 text as quoted by implementers (TinyUSB, Rockbox). Check the specification for your product.

On real hardware. On a Nucleo or an RP2040 board acting as a USB sound card, log the feedback value the firmware reports each second, and the host's packet sizes if your OS shows them. A steady value near 48.000 with a small wobble tells you the measurement window is long enough. A value that jumps by about 0.004 frames per ms means your window is only 1 ms.

Fill-level control: a small PI loop

When there is no feedback channel, watch the ring. If it fills, the consumer is too slow and should speed up a little. If it empties, slow down. This is the hero's third choice. A PI controller (proportional plus integral) makes the nudge from the error e, the fill minus the target.

trim
How many ppm to speed up the consumer clock (or slow the source). The hero limits it to ±300 ppm.
Kp · e
The quick part. Each frame of error asks for 1.5 ppm. It reacts at once but cannot cancel a steady drift alone.
Ki · ∫ e dt
The slow part. It adds up the error over time, at 0.04 ppm per frame-second, and learns the steady 50 ppm gap.

Numbers from the hero. One ppm of rate moves the fill by 48,000 × 10−6 = 0.048 frames a second. With these gains the loop settles smoothly, and at 50 ppm the fill peaks about 23 frames from target, then returns. The ring has 128 frames of room each way, so it never clicks.

c, run once per blockfloat fill_trim_ppm(int fill_frames, float dt_s) {
    static float integ;                              /* frame-seconds of accumulated error */
    const float KP = 1.5f, KI = 0.04f, TARGET = 128.0f;
    float e = (float)fill_frames - TARGET;           /* positive: ring too full */
    integ += e * dt_s;
    integ = clampf(integ, -7500.0f, 7500.0f);          /* anti-windup */
    float trim = KP * e + KI * integ;
    return clampf(trim, -300.0f, 300.0f);               /* hand to the PLL or the resampler ratio */
}

How to apply the trim depends on the chip. Some parts have a fractional PLL divider that can move the audio clock by a few ppm (STM32H7 is one; confirm in your reference manual). Others use the trim as the ratio of a resampler, which is Chapter 7.

A high-speed USB device at 48 kHz reports 0x00060000 in 16.16 format. What does that mean?

Chapter 7

Resampling: Reading Between the Samples

Absorb the drift by reading the stream at a slightly different pace, with no dropped frame

A film runs at 24 pictures a second, and your screen shows 60. Some film pictures stay on screen for two refreshes, others for three. You see motion, not a stutter, because the eye blends them. Audio has a better answer than repeating a frame. It can compute the value that lies between two samples.

That is resampling: producing samples at new times from samples at old times. When the new rate is only a hair different from the old one, it is the cleanest cure for drift.

Where the new samples sit

Say the source is faster than the speaker by 50 ppm. Output frame m needs the wave at input time m × 1.00005, counted in input frames. The first output sits right on input 0. Output 10,000 sits at input 10,000.5, half way between two input frames. Output 20,000 sits at input 20,001.0, exactly on a frame again, and one input frame has been used up that we never played.

That is the drift being absorbed. Nothing was dropped. The read position slid across the input grid, one full frame every 20,000 outputs (0.42 s at 48 kHz). The fraction of a frame between two input points is the phase. It sweeps from 0 to 1 and wraps.

Slide the read position

Top: the output grid (orange) reads the input grid (blue) a little faster, so it slides across. Bottom: how accurate each way of reading between two samples is, for the tone you pick. Choose a method.

5,000 Hz

The strip is a toy: a 4% rate difference so the sliding is visible (a real gap is 0.005%). The bars are computed live by resampling a sine at 16 fractional phases and measuring the error at 48 kHz. Sinc means 16 taps with a Blackman window, one common way to build it, not the design of any particular chip.

Four ways to read between two samples

Nearest copies the closest frame. It costs nothing and sounds rough. Linear draws a straight line between two neighbours and reads along it. Cubic fits a smooth curve through four neighbours. Windowed sinc uses many neighbours, weighted by the ideal low-pass shape, cut off smoothly by a window. More taps (neighbouring frames used) give a more accurate answer for more arithmetic.

For linear interpolation the worst error is small for low tones and grows with the square of the tone's frequency. With θ = 2π f / 48,000, the largest error is about θ2 / 8 times the amplitude, halfway between samples. At 1 kHz that is 0.0021, or −53 dB. At 10 kHz it is 0.21, or −13 dB, and the approximation is only rough. Try the tone slider and watch the bars.

The cost is small. Linear interpolation needs one subtract, one multiply and one add for each sample, plus the position update. Suppose that takes 10 cycles. Two channels at 48 kHz give 96,000 samples a second, so about 0.96 million cycles, which is 0.6% of a 168 MHz core. A 16-tap sinc might take 24 cycles for each sample, or 2.3 million cycles a second, about 1.4%. These cycle counts are illustrative guesses. Measure your own with the cycle counter from Chapter 2.

ASRC: the chip that does this for you

An asynchronous sample rate converter (ASRC) does all of this in hardware or software, with a ratio that it estimates all the time from the two clocks. The input and output clocks have no fixed relation. Analog Devices' AD1896 is a well-known example. Its datasheet lists a 24-bit data path, sample rates up to 192 kHz, and input to output ratios from 7.75:1 down to 1:8, with THD+N (distortion plus noise) of −117 dB in its product overview. I read these figures in a datasheet listing, not in the PDF, so check the sheet before you design with it.

In software, the ratio comes from the fill-level controller of Chapter 6. The controller's trim in ppm is the ratio offset. On a Linux or desktop system, libraries such as libsamplerate and the Speex resampler do this job. On a Cortex-M you write a short interpolation loop yourself, or let a codec with an ASRC do it.

On real hardware. On a Nucleo and an I2S codec board, feed a 1 kHz tone through a software linear-interpolation resampler with a trim of +50 ppm. Capture the output with a logic analyzer and decode it. Compare the spectrum with FFT software. You will see low-level distortion products, but no ticks at 2.4 per second.

c, linear resampler, ratio near 1/* in[]: input frames. pos: read position in input frames. step: 1.0 + trim_ppm * 1e-6. */
int resample_block(const float *in, float *out, int n_out, double *pos, double step) {
    for (int m = 0; m < n_out; m++) {
        int   i  = (int)*pos;               /* whole frame     */
        float mu = (float)(*pos - i);        /* phase, 0 to 1   */
        out[m] = in[i] + mu * (in[i + 1] - in[i]);
        *pos += step;                          /* slides by step, not by 1 */
    }
    int used = (int)*pos;                   /* input frames consumed */
    *pos -= used;
    return used;                           /* n_out +/- a rare extra or missing frame */
}

Look at the return value. Mostly it equals n_out. Every 20,000 frames at 50 ppm it is one larger, and that is the slip the ring would otherwise have suffered, made smooth.

Why does a resampler remove the 2.4-per-second ticks that dropping a frame causes?

Chapter 8

On the Bench: Find the Click with a Probe

Read a logic analyzer trace of an audio stream and name the fault from its shape

A teammate hands you a board and says, "It clicks sometimes." There is no debugger output, and printing from the audio code would only make it worse. What do you do? You add a few pins and look.

This chapter is the method. It uses what the earlier chapters taught: a late fill leaves a mark, a wrong half leaves a mark, and a drifting clock leaves a mark that shows only over minutes.

Four probes tell most of the story

A logic analyzer records many digital pins at once against a shared time axis. Many are small USB devices, and the open sigrok and PulseView tools read their captures. You need one pin for each of these four signals.

The first is the DMA event pin. Toggle it at the start of the half-transfer and transfer-complete callbacks. It shows when the hardware needs a block. The second is the fill pin. Set it high when your fill code starts and low when it ends. Its length is the work. Its start, measured from the DMA event, is the response time.

The third is the half pin. Set it to 0 when the code writes the first half and 1 for the second. Compare it with which half the DMA is reading. They must be opposite. The fourth is whatever else runs on the chip: a UART TX line, an SPI chip select, a display line. If a stall lines up with a burst on another pin, you have found the cause.

The deadline rule from Chapter 2 now has a picture. Each fill pulse must start after its DMA event and end before the next one. A pulse that is still high when the next DMA event fires is a missed deadline.

Set the analyzer sample rate high enough to see the shortest thing you care about. To resolve 10 µs you need at least 100 kS/s, and 1 MS/s is comfortable. A fill pulse of 0.33 ms then spans 330 samples. Connect a ground wire next to the signal wires, and keep them short, so edges stay clean. Now try the five boards below.

Name the fault from the trace

Pick a board to see its capture, then choose a diagnosis. The ring trend row shows the last three minutes, not 16 ms. Red marks are deadlines the fill missed.

Board
Diagnosis

Model, not silicon. Traces are generated from the same period of 1.333 ms (64 frames at 48 kHz) and a fill that takes 0.33 ms when healthy. The faults are the ones this lesson explains. A real capture is noisier. Score: boards you named right.

On real hardware. Use an STM32 Nucleo and a four-channel analyzer. Wire GPIO pins for the events above, start your player, and record 50 ms, then 10 minutes of the ring-fill counter printed once a second by a low-priority task. Repeat after each fix and compare.

Instrument without disturbing the stream

The probe must not cause the fault it hunts. A GPIO toggle is one store to a bit-set register, a few cycles, so it is safe inside a callback. A printf over a UART is not: it can take milliseconds. So record into RAM, and print later from a task that has low priority.

For timing inside the chip, use the DWT cycle counter on Cortex-M3, M4 and M7. Switch it on once at start-up. Then read it at the start and end of the fill. Divide the difference by the core clock to get seconds. Keep the worst value you have seen.

c, cycle counter/* once, at start-up (Cortex-M3/M4/M7) */
CoreDebug->DEMCR |= CoreDebug_DEMCR_TRCENA_Msk;
DWT->CYCCNT = 0;
DWT->CTRL  |= DWT_CTRL_CYCCNTENA_Msk;

/* around the fill */
uint32_t c0 = DWT->CYCCNT;
fill_block(blk);
uint32_t used = DWT->CYCCNT - c0;            /* unsigned subtraction survives the wrap */
if (used > worst) worst = used;               /* worst / core_hz = seconds; compare with the period */

The same stream in Zephyr

Zephyr wraps all of this in its I2S API. You give it a memory slab, a pool of equal blocks. The slab count is your k. You write blocks with i2s_write and the driver plays them in order. If you are late, the driver enters an error state, flagged as an underrun, and you recover with I2S_TRIGGER_PREPARE.

c, Zephyr I2S playback/* 48 kHz stereo 16-bit, 64-frame blocks, 4 blocks in the slab: k = 4 */
#define BLOCK_BYTES (64 * 2 * sizeof(int16_t))
K_MEM_SLAB_DEFINE(tx_slab, BLOCK_BYTES, 4, 4);

struct i2s_config cfg = {
    .word_size = 16, .channels = 2, .format = I2S_FMT_DATA_FORMAT_I2S,
    .options = I2S_OPT_BIT_CLK_MASTER | I2S_OPT_FRAME_CLK_MASTER,
    .frame_clk_freq = 48000, .mem_slab = &tx_slab, .block_size = BLOCK_BYTES, .timeout = 1000,
};
i2s_configure(dev, I2S_DIR_TX, &cfg);

void *blk;
for (int i = 0; ; i++) {
    k_mem_slab_alloc(&tx_slab, &blk, K_FOREVER);   /* blocks when all k are in flight */
    fill_block(blk);
    if (i2s_write(dev, blk, BLOCK_BYTES) < 0) {      /* underrun: driver is in the error state */
        k_mem_slab_free(&tx_slab, blk);
        i2s_trigger(dev, I2S_DIR_TX, I2S_TRIGGER_PREPARE);
        underruns++;
    }
    if (i == 3) i2s_trigger(dev, I2S_DIR_TX, I2S_TRIGGER_START);   /* start once the queue holds k blocks */
}

Read the shape: a blocking allocate gives you natural back-pressure, and the slab count is the knob from Chapter 5. The example is a sketch from the API's documented calls. Check argument names and return codes in the header of the Zephyr version you build against.

Failure mode: fixing the wrong fault

Symptom. You add blocks, the clicks thin out, and then return after a few minutes.

Measurement. The fill-pin trace of a 50 ms window looked fine, so you decided the stalls were rare. The three-minute ring trend would have shown a straight line toward the edge.

Fix. Look at both time scales: milliseconds for deadlines, minutes for drift. Keep an underrun counter, the minimum and maximum ring fill, and the current trim in a status report.

The fill pulse starts 0.05 ms after each DMA event and lasts 0.33 ms, yet clicks come every 27 seconds. Where do you look next?

Chapter 9

Field Guide

Keep the numbers, the checklist and the core code for the next audio board you bring up

An audio stream on a microcontroller rests on two ideas. First, the DMA plays one block while your code makes the next, so every block has a deadline equal to its period. Second, the source and the speaker run on different clocks, so any finite buffer eventually fills or empties unless something follows the clock. Buffers buy time. Following the clock buys forever.

The numbers

QuantityFormulaWorked value
Frame sizechannels × bytes per sampleStereo 16-bit: 4 bytes. 48,000 frames/s = 192,000 bytes/s
Block periodN / fsN = 64 at 48 kHz: 1.333 ms
Interrupt entryArm Cortex-M3/M4 figure12 cycles
Drift ratefs × ppm / 10650 ppm at 48 kHz: 2.4 frames/s (1 ppm = 0.048 frames/s)
Time to first click(R / 2) / drift rateR = 256, 50 ppm: 53.3 s
Drift in an hourdrift rate × 3,60050 ppm: 8,640 frames = 0.18 s
Latency of a ringk × N / fsk = 4, N = 64: 5.33 ms
Stall a ring covers(k − 1.25) × N / fsk = 4, N = 64: 3.67 ms (fill = a quarter period, illustrative)
Pitch error1200 × log2(1 + ppm / 106) cents50 ppm: 0.087 cent
USB feedback, full speedframes per 1 ms, 10.14 fixed point48.0 = 0x0C0000
USB feedback, high speedframes per 125 µs, 16.16 fixed point6.0 = 0x00060000
Count error1 / (MCLK × window)12.288 MHz, 8 ms: 10.2 ppm
Linear interpolation errorabout θ2 / 8 of amplitude1 kHz at 48 kHz: about −53 dB

The checklist

  1. Choose N and k from your measured worst stall and your delay budget, not from a guess.
  2. Start the DMA in circular mode, or use double-buffer mode and respect the CT rule for M0AR and M1AR.
  3. Prime every block before you start the stream.
  4. In the callback, only note which half is free. Do the fill in a high-priority task.
  5. On a Cortex-M7, clean the data cache for the buffer, or place it in non-cacheable memory.
  6. Keep an underrun counter and report it. Log the minimum and maximum ring fill.
  7. Find out which side owns the master clock. If it is not yours, plan the follow method: feedback, fill-level trim or resampling.
  8. Test for hours with the radio, storage and display active.
  9. Look at the bench at two time scales: milliseconds for deadlines, minutes for drift.
  10. Play a counter and check that every step is +1.

The core as code

c, ring with fill-level trim/* One producer (task), one consumer (DMA callback). Counters only ever grow, so no lock is needed. */
typedef struct {
    int16_t   buf[RING_FRAMES * 2];       /* stereo frames; RING_FRAMES is a power of two */
    _Atomic uint32_t wr, rd;           /* frames written, frames read */
    uint32_t  underruns, overruns;
} ring_t;

static inline uint32_t ring_fill(const ring_t *r) { return r->wr - r->rd; }   /* wraps correctly in uint32 */

/* Producer: returns false and counts an overrun if there is no room. */
bool ring_put(ring_t *r, const int16_t *src, uint32_t n) {
    if (RING_FRAMES - ring_fill(r) < n) { r->overruns++; return false; }
    for (uint32_t i = 0; i < n * 2; i++) r->buf[((r->wr * 2) + i) & (RING_FRAMES * 2 - 1)] = src[i];
    r->wr += n; return true;
}
/* Consumer (DMA half/full callback): plays silence and counts an underrun if the ring is short. */
void ring_get(ring_t *r, int16_t *dst, uint32_t n) {
    if (ring_fill(r) < n) { memset(dst, 0, n * 4); r->underruns++; return; }
    for (uint32_t i = 0; i < n * 2; i++) dst[i] = r->buf[((r->rd * 2) + i) & (RING_FRAMES * 2 - 1)];
    r->rd += n;
}
/* Each block: trim = fill_trim_ppm(ring_fill(&ring), block_seconds); step = 1.0 + trim * 1e-6; then resample_block(...) */

Where it sits in the field

This lesson follows digital audio on the wire (the bits on I2S) and builds on Interrupts, DMA and the 12 Cycles. The real-time track has a planned lesson on rings, queues and drops that treats the ring in general. The bench method is explained further in the series lesson on debug, trace and observability.

The same drift appears in the echo canceller: see the chapter on delay and drift in Acoustic Echo Cancellation, where a speaker and a microphone on two clocks make the echo slide.

Keep going

Sources

This lesson has no slide deck. Every claim comes from these sources, read in 2026-11. Items marked (excerpt) were read as quoted excerpts and not as full PDFs, so confirm them against the document for your part.

Crystal tolerances, stall times and gains in the devices are illustrative. Use your own datasheets and your own measurements.

The takeaway. A block has a deadline: its period. A clock has an error: its ppm. Buffers absorb late blocks and delay the clock problem. Feedback, fill-level trim and resampling remove it.
Which pair of fixes handles BOTH a one-time late block and a permanent clock mismatch?

Now press Present or Teach and explain from memory why a ring clicks even when the CPU is fast, with the 53-second example. Then go back to the ring at the top, set the mismatch to +100 ppm and explain why Free run clicks twice as often and why Trim still holds.

Audio DMA and Clock Drift
Previous: digital audio on the wire · Back to Gleams