A PC and a USB speaker run on two separate clocks. One tiny feedback number keeps the buffer between them from running dry, and Bluetooth LE Audio solves the same problem with time slots.
Learn how an audio device introduces itself to a host, how packets ride the bus, how the device tells the host to send a little faster or slower, and how Bluetooth LE Audio and the LC3 codec fit a stream into radio time slots.
Set the clock error, then press Without feedback and watch the buffer drain. Switch to With feedback and watch it hold the centre. Then we build, piece by piece, everything under that one line.
You need a rough idea of what a sample is (one number that says how loud the sound is at one instant) and a little C for the code. We build the rest from zero.
Part of the course Firmware from Zero to Expertise. Built from primary sources: the USB Audio Class 2.0 specification, Microsoft’s USB Audio 2.0 driver notes, the TinyUSB audio class driver and the Zephyr Bluetooth LE Audio presets. Every idea is re-taught here in our own words and devices.
A model, not real silicon. The host sends 48 kHz stereo audio in 1 ms frames. The device buffer holds 192 samples (4 ms) and starts half full. One second of the chart is shown in 0.2 s. The feedback loop is the one taught in Chapter 5. The clock error is illustrative: a typical crystal is within tens of ppm.
Chapter 0
See why a perfectly good USB speaker clicks every half minute, and what firmware must do about it
You plug a USB speaker into a laptop and play a song. It sounds fine. Then, every 25 seconds or so, you hear a small click. The cable is fine. The files are fine. Nothing is broken, and still the sound glitches on a schedule.
The cause is two clocks. The laptop has one clock that decides when each sample leaves. The speaker has a different one that decides when each sample is played. Both claim to run at 48,000 samples per second. Neither does exactly.
A sample is one number that says how loud the sound is at one instant. CD-quality audio takes 44,100 of them every second for each channel. Most USB gear uses 48,000. That count is the sample rate. A frame in audio talk is one sample for every channel at the same instant, so stereo has two numbers per frame.
A clock here is a crystal oscillator: a sliver of quartz that vibrates at a fixed pitch when you apply voltage. Firmware counts its vibrations to know when a second has passed. No crystal is exact. Makers rate the error in ppm, parts per million. A rating of 50 ppm means the clock may run 50 seconds fast or slow in every million seconds.
A buffer is a waiting room for samples. Samples arrive in bursts from the host and leave one by one at the speed of the speaker’s clock. The buffer smooths the gap between those two rhythms. Chapter 6 shows the code for it, and the lesson on DMA ping-pong buffers and clock drift goes deeper on the ring itself.
The hero used +80 ppm, which empties the buffer in 96 ÷ 3.84 = 25 seconds. Now take a gentler clock that is 50 ppm off. At 48,000 samples per second, 50 ppm is 48,000 × 50 ÷ 1,000,000 = 2.4 samples per second. Each second, the host sends 2.4 samples more or fewer than the device plays.
One sample is 20.8 microseconds of sound, so 2.4 samples feels like nothing. But the error never goes away. It adds up. A buffer that starts half full has some room to absorb it. Say the buffer holds 192 samples (4 ms) and starts at 96. At 2.4 samples per second it hits empty after 96 ÷ 2.4 = 40 seconds.
When the buffer runs empty, the speaker has nothing to play. That is an underrun. You hear it as a click or a short gap. When the buffer runs full instead, the firmware has to throw samples away. That is an overrun, and it also clicks. Which one you get depends on whether your clock is fast or slow. The sign of the ppm error decides.
The line shows how many samples the two clocks have drifted apart. The dashed lines are the 96 samples of room a half-full buffer has. Drag the clock error and see when the line hits the edge.
Arithmetic, not a measurement: error in samples = 48,000 × ppm ÷ 1,000,000 × seconds. The 96 samples of room is this lesson’s illustrative buffer, half of 192. Real crystals are commonly rated 10 to 50 ppm, and temperature moves them further.
Look at the slope. Double the error and you halve the time to the click. A cheap crystal at 200 ppm clicks every 10 seconds. A good one at 10 ppm clicks every 200 seconds. Better crystals only make the click rarer. They never remove it.
The first way is a bigger buffer. It delays the click and adds latency. The second is to bend the device clock to match the host. The third is to tell the host to send a little faster or slower. USB audio supports all three, and Bluetooth LE Audio uses a cousin of the second and third.
The third way is the hero at the top of this page. The device keeps its own clock and reports its real rate on a small side channel called the feedback endpoint. The host adjusts how many samples it sends in each packet. The buffer sits near the centre, and the click never comes.
To get there we need to know how the USB bus keeps time (Chapter 1), how a device introduces itself (Chapter 2), how big each audio packet must be (Chapter 3), and the three ways to handle drift (Chapter 4). Then we build the feedback loop (Chapter 5). The prerequisites are the bus basics in Buses on the Wire and the buffer ideas in the clock drift lesson. We re-teach what we need here.
Chapter 1
Follow a metronome that ticks every millisecond, and see why audio packets get one try and no second chance
Picture a conductor with a metronome. The orchestra has one rule: nobody plays unless the conductor points at them. That is USB. The host (your laptop or phone) is the conductor. The device (your speaker or microphone) is a player who never speaks first.
This matters for firmware. Your code cannot push a sample onto the bus when it feels ready. It can only fill a buffer and wait to be asked. The host decides when each turn starts, and the device lives inside that rhythm.
The metronome is a small packet called SOF, start of frame. The host sends it on a fixed schedule. At full speed (12 Mbit/s) one frame lasts 1 ms. At high speed (480 Mbit/s) the host sends one SOF every 125 µs. Each of those slices is a microframe, and eight of them make one 1 ms frame. These timings come from the USB 2.0 specification as explained in Microchip’s USB frames note.
Everything on the bus happens inside these slices. Your audio stream gets one slot per frame or microframe. The beat of the SOF is the only shared clock between the host and the device, and it is the host’s clock.
USB offers four transfer types. Think of four ways to send things. Control is a registered letter: small, checked and re-sent if lost. Descriptors travel this way. Bulk is freight: it fills any free space, but it has no promise about when. Interrupt is a scheduled courier for small, timely data like a keyboard. Isochronous is a live radio broadcast.
An isochronous endpoint gets a reserved slot in every frame, so its timing is guaranteed. The price is that it gets no retries. Each packet has a checksum, and the receiver throws away any packet that fails it. Nobody asks for a re-send. Bulk and control use handshakes to confirm delivery; isochronous does not.
Why accept that? Because late audio is useless. If you re-send a lost packet 3 ms later, the sound it carries should already have played. A retry would also take bus time from the packets that are on schedule. So the design says: deliver on time or not at all.
The reservation has a practical effect. At setup the host adds up the slots every device asked for, and it refuses a request the bus cannot hold. Plug a webcam, a microphone array and a headset into one full-speed hub and the headset may fail to start, not because it is broken, but because its slot did not fit. Chapter 3 shows how to size that slot.
Now the problem for audio. One frame lasts 1 ms. At 48,000 samples per second, 1 ms holds exactly 48 samples. Every packet carries 48. Easy. At 44,100 samples per second, 1 ms holds 44.1 samples, and you cannot send a tenth of a sample.
The answer is a pattern. Nine frames carry 44 samples and the tenth carries 45. Over 10 ms that is 9 × 44 + 45 = 441 samples, exactly right. The sender keeps a running total of the leftover tenths, and when the total passes one whole sample, that frame carries one extra.
Each bar is one packet in one slot. The number on it is the samples it carries. Pick a rate and a bus speed, then switch on the noise burst to see what a lost isochronous packet costs.
Stereo, 16-bit samples, so 4 bytes per sample. The extra-sample pattern is the leftover-total rule described above, computed live. The noise burst marks slots 7 and 8 as failing their checksum. This is a model of the rule, not a bus capture.
Look at which side picks the size. For a speaker, the host fills the packets, so the host does the leftover-total sum. For a microphone, the device sends the packets, so your firmware must do it.
Suppose your microphone always sends 44 samples at 44.1 kHz. The symptom is a small glitch in the recording about once a second. The measurement: count the samples the host received in ten seconds. You get 440,000, not 441,000. The device is 0.1 sample short every frame, which adds up to 100 samples per second. The fix is the leftover-total rule: keep a running remainder, and send one extra sample when it passes one.
That rule is the seed of everything in this lesson. The next chapters generalise it from tenths to any fraction the real clock produces.
Chapter 2
Walk through the six exchanges that turn a bare cable into a speaker the operating system knows how to play to
You plug in a new coworker’s laptop and nothing is set up. Your computer asks three questions in order: who are you, what can you do, and how do I use you. A USB device answers those questions with descriptors. This process is called enumeration.
The device never announces itself. The host asks and the device answers. All of it happens on endpoint 0, the default control channel every USB device has, using control transfers (the registered letters from Chapter 1).
Every descriptor starts with two bytes. The first, bLength, says how many bytes the record has. The second, bDescriptorType, says what kind it is. The rest is fields. A parser reads the length, handles the record, and jumps ahead that many bytes. That is the whole trick, and it lets a configuration be a long chain of records.
The device descriptor is always 18 bytes. The configuration descriptor is a chain: configuration, then interfaces, then endpoints, with class-specific records in between. The class-specific records use type 0x24 for an interface and 0x25 for an endpoint. This is where audio gets its own vocabulary.
A USB audio device has one AudioControl interface and one or more AudioStreaming interfaces. Control describes the wiring inside the box. Streaming carries the samples. In UAC2 both use interface class 0x01 and protocol 0x20. Control has subclass 0x01, streaming 0x02 (values as defined in TinyUSB’s audio.h for the 2.0 spec).
Inside the control interface sit entities, small boxes the host can wire together in its head. An input terminal is where audio enters the function, here from the USB stream. An output terminal is where it leaves, here the speaker. A clock source is the entity new in version 2: every terminal names the clock it runs on. The host reads and sets the sample rate by talking to that clock source, not to the terminal.
Microsoft’s driver notes spell out the rules a device must follow: each terminal needs a valid clock path ending in a clock source, and the clock source must at least answer the sampling-frequency GET RANGE and GET CUR requests. A fixed-rate device may skip SET CUR (Windows USB Audio 2.0 drivers).
The streaming interface has alternate settings, which are named modes of one interface. Alternate setting 0 has no endpoints, so it reserves no bus bandwidth. Alternate setting 1 has an isochronous OUT endpoint for the samples, plus (for asynchronous devices) a feedback endpoint. When you press play, the host sends SET_INTERFACE to switch to setting 1 and the bandwidth is reserved. When you stop, it switches back to 0.
That is why the Windows driver insists that the first alternate setting is empty: an idle speaker must not hold a slot on the bus. It also explains a neat trick: a device may list several alternate settings with the same format but different wMaxPacketSize, and the driver picks the smallest that carries the chosen rate.
Press Next exchange to run each step. Blue is what the host sends, orange is what our device answers. Then switch on the bug and run step 3 again.
A model of one possible UAC2 speaker we made up (vendor 0xCAFE, product 0x4001, as in open examples). Field layouts follow the Audio 2.0 class as implemented in TinyUSB’s audio.h and Microsoft’s driver notes; check each byte against the specification before shipping. Not a capture of a real device.
One request deserves a close look. To ask which rates the speaker supports, the host sends GET RANGE (bRequest = 0x02) to the clock source with control selector 0x01, sampling frequency. The answer is a count followed by triples of minimum, maximum and resolution, each a 4-byte number in hertz. Our device lists two discrete rates by giving each a minimum equal to its maximum and a resolution of 0, which is exactly how Microsoft says a discrete rate must be written.
Count the reply: 2 bytes for the count, then 12 bytes for each of two ranges. That is 26 bytes, 0x1A, which the host already put in wLength. If your firmware answers with the wrong length, the host sees garbage rates or no rates.
The symptom is a device that appears in the list but makes no sound, or never appears. The measurement: capture the enumeration, or on Linux read the kernel log, and find the first request your device answered with a STALL (a refusal) or with the wrong length. The most common causes are a missing GET RANGE on the clock source, an alternate setting 0 that has an endpoint, or a wTotalLength in the configuration header that does not match the real length of the chain. The fix is to implement the missing request or to recount the bytes. A small unit test that walks your own descriptor chain using bLength catches the third problem before the board is ever plugged in.
lsusb -v -d cafe:4001 (use your own IDs). Walk the output. Find the clock source, the two terminals, both alternate settings and the feedback endpoint, and check that each matches your source file.Chapter 3
Size the box the host must reserve for your stream, and see which sample rates fit on a full-speed or a high-speed wire
A removal company asks one question before it books a truck: how big is the biggest load? It books that size every trip, even when the load is smaller. The USB host does the same for isochronous audio. At setup time it needs to know the biggest packet you will ever send, and it reserves that slot every frame.
The biggest packet is your wMaxPacketSize, a field in the endpoint descriptor. If the bus cannot hold the reservation, the host refuses to start your stream. Getting this number right is the first real design decision of a USB audio device.
A packet holds the samples of one slot. Each sample is stored in a subslot: 2, 3 or 4 bytes. A 24-bit sample often sits in a 3-byte subslot. A 24-bit sample can also sit in a 4-byte subslot. Each channel has its own subslot, so the packet size follows from four numbers.
wMaxPacketSize.48 kHz, 2 channels, 16-bit, full speed: ⌈48,000 ÷ 1,000⌉ × 2 × 2 = 48 × 4 = 192 bytes
That is the packet in Chapter 2’s descriptor: C0 00, which is 192 in little-endian bytes. For 44.1 kHz the same sum gives ⌈44.1⌉ = 45 samples, so 45 × 4 = 180 bytes. Most packets carry 176 and one in ten carries 180. The reservation must cover the large one.
At full speed an isochronous packet may be at most 1,023 bytes. At high speed a single packet may be 1,024 bytes, and the endpoint may ask for two or three packets per 125 µs microframe, for 3,072 bytes in a microframe. That is the high-bandwidth option. The extra packets are requested with two bits (12 and 11) of wMaxPacketSize. These limits come from the USB 2.0 specification, and Microchip’s USB frames note repeats them.
One more rule is about honesty. Microsoft’s driver requires that the real packet size stay within plus or minus one audio slot of the nominal size, where an audio slot is one sample for every channel. Send more and the driver drops the packet. This is why Chapter 5’s feedback loop only ever changes the size by one sample at a time.
Pick a format. Each bar shows how much of one slot your largest packet fills, at full speed and at high speed. A red bar means the host would refuse the stream.
Limits used: 1,023 bytes per full-speed isochronous packet and 3 × 1,024 = 3,072 bytes per high-speed microframe. This model checks only the packet size; the host also checks the total reservation across every device on the bus, which we do not model.
Try 192 kHz, stereo, 32-bit slots. At full speed you need 192 × 2 × 4 = 1,536 bytes in a 1 ms slot. That is above 1,023, so full speed cannot carry it. At high speed the slot is 125 µs, so you need only 24 samples × 8 = 192 bytes. The same audio is easy on a faster wire because the slots are eight times more frequent.
Try 8 channels at 96 kHz, 32-bit slots. Full speed needs 96 × 8 × 4 = 3,072 bytes per ms: far too big. High speed needs 12 × 32 = 384 bytes per microframe: comfortable.
The symptom: a headset works at 48 kHz but the operating system lists 96 kHz and then refuses it, or plays at the wrong rate. The measurement: do the sum above for the listed format and compare with the limit for the speed your device really enumerates at. Many dev boards run full speed even when the part supports high speed, because the PHY (the chip block that drives the wire) is external or unwired. The fix is to list only the formats that fit, or to offer several alternate settings so the host can choose a smaller packet.
dmesg says “high-speed” or “full-speed”). Offer 96 kHz stereo 24-bit in 3-byte slots. By the formula the largest packet is 12 samples × 6 bytes = 72 bytes per microframe. Confirm that length with a capture.Chapter 4
Compare the three ways a USB audio endpoint can agree with the host, and see what each one costs in firmware
Two dancers must stay in step. One of three things can happen. The first dancer watches a beat only the leader hears and locks to it. The second dancer watches the leader’s feet and speeds up or slows down to match. The third dancer keeps their own tempo and calls out to the leader, “I am a bit faster, please adjust.”
USB audio has exactly these three, named in the USB 2.0 specification. Microsoft’s driver notes list them as synchronous, adaptive and asynchronous endpoints (Windows USB Audio 2.0 drivers). The endpoint descriptor records which one you chose, in two bits of bmAttributes.
The only clock both sides share is the SOF tick from Chapter 1. A synchronous device derives its sample clock from that tick. Inside the chip, a PLL (phase-locked loop, a circuit that makes a fast clock follow a slow one) multiplies the 1 kHz tick up to 48 kHz or 12.288 MHz. Because both sides count the same ticks, there is no drift and no extra endpoint.
The catch is jitter. Jitter is timing wobble. The SOF ticks come from the host’s controller and its own scheduler, so they wobble, and your audio clock inherits that wobble. A DAC (the chip that turns numbers into voltage) is sensitive to it. Synchronous mode is simple and most often found in older or low-cost gear.
An adaptive device does not trust SOF alone. It looks at how fast samples arrive, usually by watching its buffer fill level, and nudges its own clock to match. If the buffer grows, the device speeds up a little. If it drains, the device slows down. The host sends at its pace and the device follows.
The firmware must run a control loop and a clock whose rate can be trimmed, for example a fractional PLL. The result is a clock steered by a noisy measurement, so it can be good but never better than the loop allows.
In asynchronous mode the device runs from its own crystal and never bends it. A dedicated low-noise oscillator next to the DAC is the best clock you can give it, which is why high-end USB DACs choose this. But the host does not know the device clock, and the two will drift, as Chapter 0 showed.
So the device reports its rate on a second endpoint, the feedback endpoint. The host changes how many samples it puts in each packet. The device keeps its clean clock and the host does the bending. Chapter 5 builds this.
Choose a type and set the device crystal error. The arrow shows who corrects whom. The read-out says what your firmware must do.
A diagram of who controls whom, with arithmetic at 48 kHz. It does not measure real jitter. The statement that asynchronous clocks are usually the cleanest is a design rule of thumb, not a number from this page.
Here is one worked case at 48 kHz with a crystal 80 ppm fast. The error is 48,000 × 80 ÷ 1,000,000 = 3.84 samples per second. A synchronous device ignores its crystal and follows SOF, so it drifts 0. An adaptive device sees its buffer shrink by 3.84 samples per second, and trims its clock down by 80 ppm. An asynchronous device keeps the 80 ppm and reports 48 × 1.00008 = 48.00384 samples per frame. Same error, three different jobs for your firmware.
| Type | Who follows whom | Extra endpoint | Firmware job |
|---|---|---|---|
| Synchronous | Device locks to host SOF | None | Run a PLL from the 1 kHz tick |
| Adaptive | Device clock follows the stream rate | None | Watch buffer fill, trim a fractional PLL |
| Asynchronous | Host follows the device | Feedback endpoint (for sinks) | Measure your own rate, report it |
One more detail from Microsoft: for an asynchronous OUT stream the Windows driver supports explicit feedback only. A separate feedback endpoint must be in the same alternate setting. It does not support the other idea in the class, implicit feedback, where the rate is inferred from a paired stream going the other way. If you want your speaker to work on Windows, build the explicit endpoint.
The symptom is a speaker that sounds slightly rough or has a faint tone on top of music, even though no click ever happens. The measurement: record the DAC output and compare against a clean reference; a wobbling sample clock puts sidebands (extra tones) near each real tone. In a synchronous device the cause is often SOF jitter passing through a weak PLL. The fix is a PLL with a slow loop that smooths the SOF tick, or moving to asynchronous mode with its own oscillator.
Chapter 5
Build the loop that lets the host send exactly as many samples as the device plays, using one 4-byte number
Imagine you pour water into a glass that drains slowly through a hole. You cannot see the hole. A friend watches the glass and calls out, once in a while, “it drains 0.4 cups a minute.” Now you pour 0.4 cups a minute and the glass stays half full. That friend is the feedback endpoint.
In an asynchronous USB speaker, the feedback endpoint is a second isochronous endpoint in the opposite direction (device to host). Each time the host polls it, the device answers with one number: how many samples it consumes per frame. The host reads the number and plans its next packets to match.
The rate is rarely a whole number. 48,000 samples per second at 1 ms frames is 48. A device running 80 ppm fast consumes 48.00384. We need a way to send fractions in a few bytes. The answer is a fixed-point number: an integer with an agreed position of the decimal point.
For UAC2 the format is 16.16: 16 bits for the whole part, 16 bits for the fraction, four bytes in all. Multiply the real value by 65,536 and round. TinyUSB’s class driver sends UAC2 feedback this way, and its code notes that the unit is samples per frame at full speed and samples per microframe at high speed (audio_device.c). The older USB audio 1.0 class used a three-byte 10.14 format at full speed. TinyUSB’s own code for the older class does exactly that. The same driver also clamps the report to within one sample of nominal, because the Windows driver requires packet sizes within that limit (Chapter 3).
48 kHz, high speed: 48,000 ÷ 8,000 = 6 samples per microframe = 6 × 65,536 = 0x00060000
44.1 kHz, high speed: 44,100 ÷ 8,000 = 5.5125 × 65,536 = 361,267 = 0x00058333, sent as bytes 33 83 05 00
The host cannot send half a sample, so it runs the leftover-total rule from Chapter 1 with the fraction the device reported. Here is 5.5125 samples per microframe, step by step. The host keeps a running total, adds 5.5125 each microframe, sends the whole part, and keeps the leftover.
| Microframe | Total before | After adding 5.5125 | Sends | Keeps |
|---|---|---|---|---|
| 1 | 0.0000 | 5.5125 | 5 | 0.5125 |
| 2 | 0.5125 | 6.0250 | 6 | 0.0250 |
| 3 | 0.0250 | 5.5375 | 5 | 0.5375 |
| 4 | 0.5375 | 6.0500 | 6 | 0.0500 |
| 5 | 0.0500 | 5.5625 | 5 | 0.5625 |
| 6 | 0.5625 | 6.0750 | 6 | 0.0750 |
| 7 | 0.0750 | 5.5875 | 5 | 0.5875 |
| 8 | 0.5875 | 6.1000 | 6 | 0.1000 |
Over the first four rows the host sent 5 + 6 + 5 + 6 = 22 samples, and 4 × 5.5125 = 22.05. The leftover 0.05 stays in the total and comes back later. Over all 8 microframes it sends 44 and keeps 0.1, and 8 × 5.5125 = 44.1. The average is exact; each single packet is off by at most one sample, and that is the ±1 slot rule from Chapter 3.
The device must know how fast it consumes samples, to a precision of a few ppm. The obvious plan is to count samples played between two SOF ticks. It does not work well. Over 64 ms the I2S port consumes only 3,072 samples, and one sample of counting error is 1 in 3,072, which is 326 ppm. That is coarser than the drift you are trying to fix.
A better plan is to count a faster clock. An audio chip usually gets a master clock (MCLK) of 256 times the sample rate: 12.288 MHz for 48 kHz. A hardware timer counts MCLK edges and latches its count at every SOF. Over 64 frames you collect 786,432 counts, and one count of error is 1.3 ppm. The sum is a shift: the count difference divided by 256 counts per sample and by 64 frames, shifted up 16 bits to the 16.16 format.
c// Sketch, not a finished driver. MCLK = 256 x fs, full-speed 1 ms frames. #define WIN_LOG2 6 // measure over 64 frames static uint32_t last_cnt; static uint8_t n; static volatile uint32_t fb_16_16 = 48u << 16; // bytes the feedback IN endpoint sends void usb_sof_isr(void) { // runs once per frame if (++n < (1u << WIN_LOG2)) return; n = 0; uint32_t cnt = mclk_count_latched_at_sof(); // timer counting MCLK edges uint32_t d = cnt - last_cnt; last_cnt = cnt; // edges in 64 frames // samples per frame = d / 256 / 64, in 16.16 = that << 16 fb_16_16 = (uint32_t)(((uint64_t)d << 16) >> (8 + WIN_LOG2)); }
Check the code with the ideal numbers. d = 12,288 × 64 = 786,432. Shift up 16, down 14, and you get 786,432 × 4 = 3,145,728 = 48 × 65,536. The feedback reads exactly 48.0.
Choose what the device counts and over how many frames. A coarse count rounds the reported rate, and the buffer settles off-centre. Watch for the red clicks.
A model of the Chapter 0 buffer (192 samples, starts at 96) with 48 kHz, 1 ms frames. The device adds a small fill-level correction to its report, a common design choice and not part of the class specification. Counting samples gives steps of 1 ÷ N samples per frame; counting a 256 × fs master clock gives steps of 1 ÷ (256 × N). Illustrative, not a measured board.
The symptom: music plays but sounds slow or stutters, and the buffer is always empty. The measurement: capture the feedback endpoint and read its four bytes. Suppose your code encoded 48.0 in the old 10.14 format: 48 × 16,384 = 786,432 = 0x000C0000. The host reads that as 16.16, which is 12.0 samples per frame. It sends a quarter of the audio. The fix is to encode UAC2 feedback as 16.16 and to check one known value, such as 0x00300000 for 48 kHz at full speed, before testing any music.
Chapter 6
Trace one packet through the ring buffer to the codec, and choose how big the ring should be
A packet of 192 bytes arrives from the host. Somewhere in your chip a pin must now wiggle 48 times with the right voltages. Between the arrival and the wiggle sit three pieces of firmware: a USB interrupt, a ring buffer and a DMA engine. Each does one job and none waits for another.
The DMA (direct memory access) engine is a small block of hardware that copies data between memory and a peripheral without the CPU. The I2S peripheral turns each stereo frame into the serial bit pattern a codec chip expects; the digital audio lesson covers that wire. The interrupts and DMA lesson covers the engine.
Here is one millisecond of stereo, 16-bit audio at 48 kHz. The packet is 192 bytes. That is 48 frames, each frame two int16_t values (left, right). In memory it is an array of shape [48][2]. The USB peripheral raises an interrupt when the packet is complete. The handler copies the 192 bytes into a ring and returns. It does no audio math.
The ring buffer is a fixed array used as a loop. A write index moves forward as packets arrive. A read position moves forward as the DMA plays samples. When either reaches the end, it wraps to the start. The distance between them is the fill level, the same number that the hero plots.
c// 8 ms ring: 384 stereo frames of int16_t. Sketch for a Cortex-M with circular I2S DMA. #define RING_FRAMES 384 static int16_t ring[RING_FRAMES][2]; // DMA reads this, forever, in circular mode static volatile uint32_t wr; // frames written so far (never wraps by itself) void usb_out_done(const uint8_t *pkt, uint32_t bytes) { // USB interrupt uint32_t frames = bytes / 4; // 4 bytes per stereo frame for (uint32_t i = 0; i < frames; i++) { memcpy(ring[(wr + i) % RING_FRAMES], pkt + i * 4, 4); } wr += frames; } // How many frames the DMA has played. On STM32F4-class DMA, NDTR counts the // half-word transfers still to do, two per stereo frame. static inline uint32_t rd_frames(void) { return (RING_FRAMES * 2 - DMA_STREAM->NDTR) / 2; // position inside the ring } static inline int32_t fill_level(void) { return (int32_t)((wr - rd_total_frames) ); // frames waiting to play }
The names DMA_STREAM and rd_total_frames are placeholders for your board’s stream and a counter you update at each DMA half-complete event. Real code also guards wr against the interrupt that updates it. The structure is the point: the USB side writes, the DMA side reads, and the fill level feeds the feedback loop of Chapter 5.
Do not start the DMA the moment the first packet arrives. Wait until the ring holds about half its size, then start. The ring now has room on both sides. This is called prefill, and it is why the hero buffer starts at 96 of 192.
Decide what happens at the edges before you test. On an underrun (the DMA catches up with the write index) the polite choice is to fade to silence over a few samples, then resume with a fade in, instead of replaying stale memory. On an overrun (the write index laps the DMA) drop the oldest whole packet, never half of one, so the left and right channels stay together.
A bigger ring absorbs more trouble and costs latency. Latency is the delay between the host producing a sample and you hearing it. At the half-full operating point the ring adds fill ÷ 48 milliseconds. An 8 ms ring (384 frames) sits at 4 ms. What does the ring need to absorb? Two things: the slow wander of the clock (the feedback loop handles that) and packet-arrival jitter, the host delivering some packets late because its scheduler was busy.
Feedback is on and the clock error is +80 ppm. Make the ring smaller to cut latency. Raise the host jitter and watch late packets appear as red marks.
Model: a packet arrives late by a random time between 0 and the jitter value, and the device keeps playing meanwhile. A late packet is counted when the buffer would empty in that gap. Random draws are seeded, so the same settings give the same marks. Real jitter depends on the host and the operating system and must be measured.
Slide the ring down to 2 ms. The latency drops to 1 ms, and late packets pile up. Slide it up to 16 ms and the marks disappear, but the speaker now plays 8 ms behind. For a music player 8 ms is nothing. For a guitar effect you play live, it matters, and the next lesson on latency shows the budget.
Here is a sizing example. Suppose you measure that, on a busy PC, a packet can arrive up to 4 ms late. At 48 kHz, 4 ms is 4 × 48 = 192 samples. The ring must hold at least that many samples of margin below the centre line, so half of the ring is 192 frames and the whole ring is 384 frames, which is 8 ms. The price is about 4 ms of added latency. If that is too much, you must fix the cause of the jitter instead of hiding it.
The symptom is a click that never happens on an idle machine but appears when the PC compiles code or opens a browser. The measurement: log the minimum fill level your firmware sees each second. If the minimum dips toward zero when the PC is busy, packets are arriving late, not the clock drifting. The fix is a larger ring, a larger prefill, or both. Raise the target by the worst jitter you measured, converted to samples (jitter in ms × 48).
Chapter 7
Learn how Bluetooth LE schedules a stream into radio time slots, and what a retransmission buys and costs
You wear wireless earbuds on a crowded train. Dozens of phones and radios share the same 2.4 GHz band. Now and then a packet to your left ear is lost in the noise. If the radio simply resent it a second later, you would hear a hole. The radio has to be smarter: it tries again inside a small, fixed window, and gives up when the window closes.
That is Bluetooth LE Audio. It reuses the idea from Chapter 1: reserve a slot on a regular beat and accept that late data is useless. The difference is that the medium is air, so errors are common and retries are built into the schedule.
Classic Bluetooth audio (A2DP) sends audio as ordinary data packets with the sub-band codec SBC. LE Audio, built on the isochronous channels added in the Bluetooth 5.2 core specification, gives the controller (the radio’s own small processor) a stream with timing. Each unit of audio is a SDU, service data unit: one encoded frame handed down from the application. The SDU interval is how often one is produced, for example every 10 ms. Nordic’s documentation notes the SDU interval is fixed for the whole life of a stream (LE Isochronous Channels).
There are two kinds. A CIS (connected isochronous stream) runs between two devices, such as a phone and one earbud. A phone with two earbuds uses one CIS for each, grouped in a CIG, a connected isochronous group. A BIS (broadcast isochronous stream) has no connection: a transmitter sends, and any receiver in range can listen. A group of BIS is a BIG. A BIG is what an airport screen or a public speaker would send to many headphones at once.
Both use an ISO interval, the time between the starts of consecutive events for a stream. Zephyr’s headers express it in units of 1.25 ms, the same unit Bluetooth uses for connection timing (Zephyr iso.h). So an interval is always a whole multiple of 1.25 ms: 7.5 ms is 6 units, 10 ms is 8 units.
Each event starts at an anchor point. The sender transmits the SDU. The receiver answers with an acknowledgement. If none comes, the sender tries again in the same event, until it succeeds or runs out of tries. The number of extra tries is the retransmission number, RTN. Zephyr’s unicast presets use RTN 2 for 16, 24 and 32 kHz and RTN 5 for 48 kHz (header bap_lc3_preset.h).
Compute what that buys. Suppose each attempt fails with probability p. A frame is lost only if every attempt fails: pRTN+1. With p = 0.2 and RTN 0, you lose 20% of frames. With RTN 2 you lose 0.23 = 0.8%. With RTN 5 you lose 0.26 = 0.0064%. Each try is a fresh, independent chance.
Real radio errors come in bursts, so an independent-chance model is optimistic. Still, it shows the shape: every retransmission cuts the loss rate by another factor of p.
Each column is one ISO event. Each box is one try. Green means the frame got through. Red means a try was lost. Raise the loss and then add retransmissions.
Model: tries fail independently, drawn from a fixed random sequence so the picture is stable. One try is taken as 0.8 ms of airtime: a 100-octet payload plus about 15 octets of header, MIC and CRC on the 2 Mbit/s PHY is 460 µs, plus two 150 µs gaps and a short acknowledgement. That sum is our arithmetic, to be checked against the Core specification. Real controllers schedule subevents from parameters we do not model.
The two-clock problem returns. The receiver plays audio from its own output clock, but frames arrive on the radio’s schedule. LE Audio does not use a feedback endpoint. Instead the controller timestamps each SDU against the radio clock. The application uses the timestamps, and a presentation delay, to decide exactly when to play each frame, and it makes small rate corrections to its own audio clock. Nordic’s ISO time synchronization sample shows this.
Presentation delay is the key to a stereo pair. Left and right earbuds get their frames at slightly different instants. Both are told to play at the same moment after the SDU reference point. Zephyr’s unicast presets use 40,000 µs, 40 ms. That fixed wait is the price of keeping two ears in step.
The symptom is crackling that only happens in a busy place. The measurement: count the SDUs your receiver reports as lost per minute, and note how many tries each delivered frame needed. If most frames need the last try, you are at the edge. The fix is to raise RTN, if the maximum transport latency allows it, or to lower the bitrate so each try takes less airtime. Chapter 8 shows how big a frame is.
Chapter 8
Count the bytes in one LC3 frame, read a preset like a recipe, and see what one lost frame sounds like
A radio slot is small. Raw 48 kHz audio for one ear is 768,000 bits every second, far more than a battery-powered earbud wants to send. A codec (coder-decoder) squeezes the audio before it goes on air and expands it on arrival. The codec for LE Audio is LC3, the Low Complexity Communication Codec.
“Low complexity” is a promise to the firmware engineer. LC3 is built so a small processor can run it in real time without eating the battery. Nordic’s SDK ships an LC3 codec library for exactly that purpose (nrfxlib LC3 API).
LC3 works on fixed blocks of time called frames. There are two lengths: 7.5 ms and 10 ms. Zephyr’s LC3 definitions list both as the allowed frame durations (Zephyr LC3 codec API). The encoder collects one frame of samples, turns it into a short list of bytes, and sends it. The decoder rebuilds one frame of sound.
Here is the data flow for 48 kHz mono and a 10 ms frame. In: 10 ms × 48,000 = 480 samples, each an int16_t, so 960 bytes. Out: a payload of 100 bytes. The number of bytes per frame is called octets per codec frame (an octet is a byte), and it is a 16-bit field in the codec configuration. That one number sets the bitrate.
bitrate = octets × 8 bits ÷ frame duration = 100 × 8 ÷ 10 ms = 800 bits ÷ 0.010 s = 80,000 bits per second
How does LC3 shrink 960 bytes to 100? It is a transform codec. It converts the frame to a list of frequency strengths with a transform called the MDCT, spends its few bits where the ear is most sensitive, and rounds the rest. You do not implement that. You choose the three numbers that control it: sampling rate, frame duration and octets per frame.
The Bluetooth audio profile publishes named recipes. Zephyr’s header encodes six of the common ones. We read the numbers from the macros; we computed the bitrate and the ratio.
| Preset | Rate | Frame | Octets | Bitrate | Retrans. |
|---|---|---|---|---|---|
| 16_2_1 | 16 kHz | 10 ms | 40 | 32 kbps | 2 |
| 24_2_1 | 24 kHz | 10 ms | 60 | 48 kbps | 2 |
| 32_2_1 | 32 kHz | 10 ms | 80 | 64 kbps | 2 |
| 48_1_1 | 48 kHz | 7.5 ms | 75 | 80 kbps | 5 |
| 48_2_1 | 48 kHz | 10 ms | 100 | 80 kbps | 5 |
| 48_6_1 | 48 kHz | 10 ms | 155 | 124 kbps | 5 |
Notice that 48_1_1 and 48_2_1 both run at 80 kbps. The shorter frame sends 75 bytes about 33% more often. Shorter frames lower the wait before a frame can be sent, at the cost of more packets and more overhead per second. All six presets use a 40 ms presentation delay in Zephyr’s header.
Pick a preset. The bars compare raw audio with the LC3 frame for one ear. Then switch to stereo and see the airtime.
Octets, frame lengths and retransmission numbers come from Zephyr’s bap_lc3_preset.h unicast macros. Bitrate, ratio and airtime are our arithmetic. One try is (octets + about 15 for header, MIC and CRC) × 8 ÷ 2 Mbit/s, plus 352 µs of gaps and acknowledgement, as in Chapter 7. Raw audio is 16-bit mono.
If a frame is lost for good, the decoder has nothing to play for that block. LC3’s specification describes a concealment method that estimates the missing frame from earlier ones. A single lost 10 ms frame can often be hidden. Several in a row become audible. So frame duration is also the unit of damage: at 10 ms, each lost frame hides 10 ms of sound; at 7.5 ms, it hides 7.5 ms.
c// Sketch with the liblc3-style API; confirm names and signatures in your SDK's lc3.h. #define DT_US 10000 // 10 ms frame #define SR_HZ 48000 #define NBYTES 100 // octets per codec frame, from the preset static uint8_t enc_mem[ENC_MEM_BYTES]; // size it with lc3_encoder_size(DT_US, SR_HZ) static lc3_encoder_t enc; void audio_init(void) { enc = lc3_setup_encoder(DT_US, SR_HZ, 0, enc_mem); // 0: PCM rate equals SR_HZ } // Called every 10 ms with 480 mono samples (960 bytes). Fills out[100]. int encode_frame(const int16_t *pcm, uint8_t *out) { return lc3_encode(enc, LC3_PCM_FORMAT_S16, pcm, 1, NBYTES, out); }
Compare this with neural audio codecs in the neural codecs lesson. Those learn a compact code from data and can reach far lower bitrates, but they need much more compute and larger memory than a small radio chip can spare. LC3 trades some compression for a cost a Cortex-M can pay on every 10 ms tick.
The symptom is harsh noise or silence after the phone and earbud negotiate a new preset. The measurement: print the octets per frame, the frame duration and the sampling rate on both sides. A mismatch, such as a 7.5 ms decoder fed 10 ms frames, produces nonsense. The fix is to build the decoder from the configuration that was negotiated, and to rebuild it when the configuration changes.
Chapter 9
Put the same stereo stream on a USB cable and on a radio, and see what each medium charges for it
A song is the same song on a cable or on air. The notes do not change. What changes is the price. A cable is a motorway with plenty of lanes. A radio is a country lane that every neighbour shares. This chapter prices the same stream on each.
We take one stream: 48 kHz, stereo, 16-bit. That is 48,000 × 2 × 16 = 1,536,000 bits per second, or 1,536 kbps, of raw audio. Then we ask how much of the medium it uses.
USB full speed signals at 12 Mbit/s. The stream needs 1,536 kbps, so its payload is 1.536 ÷ 12 = 12.8% of the raw signalling rate. USB high speed signals at 480 Mbit/s, so the same payload is 1.536 ÷ 480 = 0.32%. Signalling rate is not usable throughput: headers, tokens and gaps take a part, and we do not model it. Still, the ratio shows why a headset at full speed has room for little else, and a high-speed one has plenty.
Bluetooth LE with LC3 sends far fewer bits. Two streams of the 48_2_1 preset are 2 × 80 = 160 kbps. On the 2 Mbit/s PHY that is 8% of the raw rate. But radio packets carry heavy overhead. From Chapter 7, one try of a 100-octet frame takes about 0.81 ms. Two streams need 2 × 0.81 = 1.62 ms of the 10 ms interval, which is 16.2% of the airtime for first tries alone. The 160 kbps looked like 8%, and the airtime is double that.
On a cable, a lost packet is rare, and nobody retries it. On air, the schedule must leave room for retries. The 48_2_1 preset allows up to 5 retransmissions, so 6 tries per frame. If every try were used for both streams, the time would be 6 × 0.81 × 2 = 9.7 ms of a 10 ms interval. That is close to the whole window.
Now take 48_6_1, the 155-octet preset. One try is (155 + 15) × 4 + 352 = 1,032 µs. Six tries for two streams is 12.4 ms, which does not fit a 10 ms interval. In our simple model the worst case cannot fit, so a real controller must grant fewer retries, or you must pick a lower bitrate. That is the real engineering trade of LE Audio: quality, retries and airtime pull against each other.
The strip is 10 ms of the medium. Blue blocks are the stream’s first tries. Hatched blocks are the retry reserve. Pick a medium and switch the reserve on.
Raw audio 1,536 kbps. USB shares divide the stream by the nominal signalling rate (12 or 480 Mbit/s) and ignore protocol overhead. Bluetooth airtime uses the Chapter 7 try model: (octets + 15) × 4 µs + 352 µs per try per stream, with retries from the Zephyr preset (5). Illustrative arithmetic, not a link-layer schedule.
USB charges little. The frame is 1 ms, and your ring adds a few more (Chapter 6). A radio with LC3 charges more. The encoder has to wait for a whole 10 ms frame before it can start. Then comes the transport window: Zephyr’s 48_2_1 preset sets a 20 ms maximum transport latency. At the end, every receiver waits out the 40 ms presentation delay so left and right match. So a LE Audio stream is at least tens of milliseconds behind the source. That is fine for music and video playback, where the player can delay the picture to match, and awkward for a live instrument.
Look at what repeated. Both media reserve a slot on a beat. Both have two clocks that drift. USB solves drift with a feedback number the host acts on. LE Audio solves it with timestamps and small clock corrections in the application. Both accept that late data is worthless. USB drops the packet. LE Audio retries inside a window and then drops it.
The cable is cheap and simple. The radio is flexible and costs airtime, delay and battery. Choose from the product’s needs: a studio interface wants the cable, a pair of earbuds wants the radio.
The symptom is a stereo link that works alone but crackles when a phone also scans for devices or a second headset joins. The measurement: add up airtime for all your streams, with the retry reserve, and compare with the interval. If the total is near 100%, there is no room for a neighbour. The fix is a lower bitrate, fewer retries, or a longer frame. The budget must be written down before the radio is tested.
Chapter 10
Keep the numbers, the checklist and the core code, and find where to go next
Two clocks never agree, so a stream between them needs a way to share its rate. On USB, an isochronous endpoint reserves a slot each frame and the host sends exactly as many samples as the device reports through its feedback endpoint. On Bluetooth LE Audio, the stream is encoded as fixed LC3 frames, each sent inside a radio window with retries, and played at a fixed presentation delay. Both media reserve time on a beat, both drop late data, and both need an honest budget before they are tested.
| Item | Value | Where from |
|---|---|---|
| USB frame, full speed | 1 ms, one SOF each | USB 2.0; Microchip frames note |
| Microframe, high speed | 125 µs, 8 per frame | USB 2.0; Microchip frames note |
| Largest isochronous packet | 1,023 B full speed; 1,024 B high speed, up to 3 per microframe | USB 2.0 (search summaries; check the spec) |
| 48 kHz stereo 16-bit packet | 192 B per frame; 24 B per microframe | Our arithmetic |
| 44.1 kHz packets | nine of 44 samples, one of 45, per 10 ms | Our arithmetic |
| Drift per ppm at 48 kHz | 0.048 samples per second | Our arithmetic |
| UAC2 interface codes | class 0x01; AudioControl 0x01, AudioStreaming 0x02; protocol 0x20 | TinyUSB audio.h; Microsoft compatible IDs |
| UAC2 feedback | 4 bytes, 16.16, samples per (micro)frame | TinyUSB audio_device.c |
| Feedback examples | 0x00300000 (48 kHz, FS); 0x00060000 (48 kHz, HS); 0x00058333 (44.1 kHz, HS) | Our arithmetic; 0x00060000 also in a Linux list post |
| Packet size deviation | within ±1 audio slot of nominal | Microsoft USB Audio 2.0 notes |
| Rate measure resolution | 326 ppm counting samples; 1.3 ppm counting MCLK, over 64 frames | Our arithmetic |
| BLE ISO interval | multiple of 1.25 ms | Zephyr iso.h |
| LC3 frame durations | 7.5 ms and 10 ms | Zephyr LC3 codec API |
| Preset 48_2_1 | 100 octets, 10 ms, 80 kbps, 5 retransmissions, 20 ms max latency, 40 ms presentation delay | Zephyr bap_lc3_preset.h; bitrate is our arithmetic |
| One radio try (model) | about 0.81 ms for 100 octets | Our model; verify against the Core spec |
bLength and check wTotalLength. Alternate setting 0 has no endpoint.GET CUR and GET RANGE for the sampling frequency. Check wLength.c// Streaming interface of our fake speaker, bytes as in Chapter 2. Sketch: verify against the spec. static const uint8_t as_alt0[] = { 0x09,0x04,0x01,0x00,0x00,0x01,0x02,0x20,0x00 }; // no endpoints: no bandwidth static const uint8_t as_alt1[] = { 0x09,0x04,0x01,0x01,0x02,0x01,0x02,0x20,0x00 }; // two endpoints static const uint8_t ep_out[] = { 0x07,0x05,0x01,0x05,0xC0,0x00,0x01 }; // iso OUT, async, 192 B static const uint8_t ep_fb[] = { 0x07,0x05,0x81,0x11,0x04,0x00,0x01 }; // iso IN, feedback, 4 B // Host side, in words: a running total that turns a fractional rate into whole-sample packets. uint32_t packet_samples(uint32_t fb_16_16, uint32_t *acc) { *acc += fb_16_16; // add the reported samples per frame uint32_t n = *acc >> 16; // whole samples to send now *acc &= 0xFFFF; // keep the fraction for later return n; } // Device side: the feedback sketch of Chapter 5 reports fb_16_16; the ring of Chapter 6 absorbs the rest.
We built this lesson from primary sources, not slides. Open them to check any number.
Not verified against the full Bluetooth Core and BAP specifications, which we did not open: the exact LC3 delay figures, the packet overhead bytes behind our 0.81 ms try, and the per-event scheduling a real controller uses. Treat those parts as models.
Now press Present or Teach and explain from memory why a USB speaker clicks every 25 seconds, how the feedback number fixes it, and how an LE Audio frame is paid for in airtime. Then go back to the buffer at the top, set the clock error to ±150 ppm with feedback on, and explain why the line stays flat.