A webcam works on any computer because its firmware answers a few fixed questions in a fixed format. Pick a picture size and rate, and see which USB bandwidth slot the host must choose.
Learn how a small chip describes itself, agrees a video format with the host, wraps every packet of a frame in a header, and asks the bus for just enough isochronous bandwidth.
Choose a format and a size, then drag the frame rate. Watch the need line climb past the bars. Then we build, piece by piece, every byte behind it: the descriptors, the handshake, the headers and the buffers.
You need a rough idea of what a byte is and a little C. We teach USB, descriptors and isochronous transfers from zero. Earlier reading: Buses on the Wire, chapter 6.
Built from primary sources: the Linux uvcvideo driver and its UAPI header, TinyUSB and Zephyr video-class code, USB 2.0 notes from Microsoft and Linux, and the UVC 1.5 class layout they implement. Full list in the Field Guide. No course slides are used.
Model, not silicon. Bars are an example list of six alternate settings on a USB 2.0 high-speed device (wMaxPacketSize 0x0080, 0x0100, 0x0200, 0x0400, 0x0C00, 0x1400). MJPEG sizes assume an illustrative worst case of 0.5 bytes per pixel. Each packet carries a 2-byte payload header.
Chapter 0
See how a cheap chip can introduce itself to any computer and be understood in about a second
Take a webcam out of its box. Plug it into a laptop that has never seen it. A second later a preview window shows your face. You installed nothing.
Think about how odd that is. The laptop has no idea who made the camera. It does not know the sensor, the lens or the chip inside. Yet it asks for a picture of a given size and gets one.
The trick is an agreement. Before any camera existed, engineers wrote down what every USB camera must say about itself and how it must send pictures. A camera that follows the paper works everywhere. That paper is the USB Video Class, or UVC. A class is a published contract for one kind of device. Your computer ships one driver for the whole class. On Linux that driver is called uvcvideo.
USB has a host (your laptop) and a device (the camera). The device never speaks first. The host asks, and the device answers. Even a stream of video flows only because the host asks for each slice of it, over and over, on a fixed clock.
This matters for firmware. Your camera chip cannot shout “here is a frame”. It must have the next slice ready when the host asks, and say something sensible when it has nothing.
A UVC camera answers three questions. Each one gets a chapter or two in this lesson.
Chapter 7 then looks inside the camera: the buffers and the timing that keep those packets coming. Chapter 8 shows how to find the fault when the picture is black.
When you plug in the cable, the host runs a fixed routine called enumeration. It resets the port, reads descriptors, gives the device an address, and picks a configuration. Drag the slider to walk through it. The left column is the host, the right column is your firmware.
Each row is one message on the cable. Drag the slider to reveal them in order. Bright rows have happened.
Model of the usual sequence on a full or high-speed port. The device descriptor is 18 bytes and the example configuration is 168 bytes (built in Chapter 2). The video class code 0x0E and the Miscellaneous device code 0xEF with subclass 2 and protocol 1 (the pattern for devices that use an interface association) come from the USB-IF class lists. Real hosts add small extra reads.
Look at step 4. The host asks for the configuration descriptor and receives 168 bytes. In those bytes the host finds class code 0x0E, which means video. That one number tells the operating system which driver to load. Nothing else about the camera had to be known in advance.
Steps 5 and 6 end the story. The driver switches the configuration on and a video device appears. No picture flows yet. The host still has to ask for a mode (Chapter 4) and book bandwidth (Chapter 6). That happens only when an application opens the camera.
A browser cannot talk to real USB silicon, so the devices here are models. They use the real byte layouts, the real field names and the real arithmetic. Each core chapter ends its device section with an On real hardware note that names a board and a measurement you can repeat. Our default part is an STM32 with a USB high-speed controller, such as the STM32F4 or H7 family. The Zephyr project also ships a UVC sample for boards like the FRDM-MCXN947 that shows up on a host as a webcam.
On real hardware. Plug any webcam into a Linux machine. Run lsusb and note its vendor and product IDs. Then run lsusb -v -d VID:PID and find bInterfaceClass 14 Video. You are reading the same descriptors the driver read.
Chapter 1
Meet the host, the endpoints and the four kinds of transfer, and see why video books its bandwidth in advance
Picture a one-lane road shared by a printer, a keyboard, a memory stick and your camera. Cars cannot all go at once. Someone must decide who drives when.
On USB, the host decides. It cuts time into fixed slices and hands each slice to one device. At full speed (12 Mbit/s) the slice is a frame of 1 ms. At high speed (480 Mbit/s) the host cuts each frame into eight microframes of 125 µs. A UVC camera that wants smooth video lives or dies by how well it uses these slices.
This chapter teaches the little of USB that the rest of the lesson needs. You will meet it again in Buses on the Wire, which covers the electrical side.
A USB device exposes numbered mailboxes called endpoints. Each endpoint moves data one way. IN means device to host. OUT means host to device. Endpoint 0 is special: every device has it, in both directions, and the host uses it for all the setup talk you saw in Chapter 0.
Endpoints are grouped into interfaces. An interface is one job the device does. A UVC camera has two jobs. One interface takes controls (brightness, mode requests). The other interface streams video. A configuration bundles the interfaces the host switches on together. Descriptors list all of this (Chapter 2).
Each endpoint chooses one transfer type. Think of four postal services.
Video fits live radio. A frame that arrives half a second late is not a frame, it is a stutter. Resending would steal time from the next frame. So most UVC cameras use an isochronous endpoint. The class also allows bulk, and the TinyUSB video example can be built either way. Bulk is simpler but gives no timing promise.
An isochronous endpoint declares its size in wMaxPacketSize. At high speed one microframe can carry up to three transactions of up to 1,024 bytes, so up to 3,072 bytes. Bits 12 and 11 of wMaxPacketSize hold the number of extra transactions (0, 1 or 2) and the low bits hold the size of each one (Microsoft’s isochronous endpoint documentation gives this layout).
The host books that space when the configuration or alternate setting is chosen. If the bus cannot promise it, the host refuses. The rule has a limit: periodic traffic (isochronous and interrupt together) may use at most 80% of a high-speed microframe. The Linux EHCI driver quotes section 5.6.4 of the USB 2.0 specification for that figure. At full speed the share is 90% of the 1 ms frame.
Do the sum for high speed. 480 Mbit/s is 60 million bytes per second. One microframe lasts 125 µs, so it holds 60 × 125 = 7,500 byte times. Eighty percent of that is 6,000. A camera that books 3,072 bytes uses 41% of a microframe: 3,072 ÷ 7,500 = 0.41.
Now add a second device. A sound card already booked 45%, which is 3,375 byte times. The camera wants 41%. The sum is 86%, above 80%, so the host says no. The camera must pick a smaller alternate setting. With 45% taken, 35% remains, which is 2,625 byte times. The 2,048-byte setting fits. The 3,072-byte setting does not.
The bar is one 125 µs microframe. Drag how much other devices have already booked, then choose the camera’s alternate setting. The dashed line is the 80% limit.
Model: a microframe holds 7,500 byte times (480 Mbit/s × 125 µs). Per-packet bus overhead is ignored, so a real schedule is a little fuller. The 80% limit is the USB 2.0 periodic limit as cited by the Linux EHCI driver.
Hubs share this budget. All the devices behind one high-speed port share one bus. That is why two cameras on one hub can work alone but fail together. The host does not guess later. It refuses at selection time. Linux often reports the refusal as error -ENOSPC, “No space left on device”.
On real hardware. On an STM32 with a USB high-speed core, the stack picks the endpoint size you write into the descriptor. Plug the device behind a hub that also holds a webcam or a USB audio device. Run the host’s USB tree viewer (lsusb -t) and see which port each device lands on.
Chapter 2
Build the table of bytes that tells the host what a camera is made of, and count every byte
You walk into a shop and ask what it sells. The clerk hands you a printed menu. Every line starts with its own length, so you can skip from line to line without reading the details.
A USB descriptor list is that menu. A descriptor is a short record of bytes. Byte 0 is bLength, the size of this record. Byte 1 is bDescriptorType, what kind of record it is. The rest depends on the type. The host reads the whole list in one go and hops from record to record by adding each bLength to its position.
Firmware stores the list as a constant array in flash. When the host sends GET_DESCRIPTOR, the USB stack copies bytes from that array. Most bugs in this part are counting bugs.
Why such a rigid layout? A host has no idea what a camera contains until it reads the list, and a USB packet on endpoint 0 holds at most 64 bytes at a time. So the list must be easy to cut into pieces and easy to check as it arrives. The length byte first and the type byte second let the host skip any record it does not know. That is how a newer camera with new records still works on an older host: the old host simply hops over them.
A UVC camera has a standard shape. Read it from the top.
wTotalLength, the size of everything after it too.The lengths above come from the macros in TinyUSB’s video class header: IAD 8, control interface 9, class header 12 plus one byte per streaming interface, camera terminal 18, output terminal 9, input header 13 plus the control bytes, uncompressed format 27, a discrete frame 26 plus 4 per interval, color matching 6.
Add the minimal camera: 9 + 8 + 9 + 13 + 18 + 9 + 9 + 14 + 27 + 30 + 6 + 9 + 7. That is 168 bytes. The class header must say that the control section is 13 + 18 + 9 = 40 bytes. The streaming input header must say its section is 14 + 27 + 30 + 6 = 77 bytes. Every length must match, or the host stops reading early.
Try it. Switch pieces off and watch the total change, and watch what the host would conclude.
Each row is one record, drawn as long as its byte count. Tap a piece to remove or add it. The read-out says what a host would do.
Lengths are the UVC 1.5 layouts as encoded in TinyUSB’s video class macros, for one uncompressed format, one frame with one fixed frame interval, and one alternate setting with an endpoint. The host verdicts are the usual behaviour, not a test of any one operating system.
Here are the first four records of that list in C, with the meaning of each byte. Words in little-endian order: the low byte comes first, so 168 is 0xA8, 0x00.
cstatic const uint8_t cfg_desc[] = { /* configuration */ 9, 0x02, 0xA8, 0x00, /* bLength, type CONFIGURATION, wTotalLength = 168 */ 2, 1, 0, 0x80, 0xFA, /* 2 interfaces, config value 1, no string, bus powered, 500 mA */ /* interface association: one function made of interfaces 0 and 1 */ 8, 0x0B, 0, 2, 0x0E, 0x03, 0, 0, /* first itf 0, count 2, class VIDEO, subclass COLLECTION */ /* video control interface 0, alt 0, no endpoints */ 9, 0x04, 0, 0, 0, 0x0E, 0x01, 0, 0, /* class-specific VC header */ 13, 0x24, 0x01, 0x00, 0x01, /* CS_INTERFACE, VC_HEADER, bcdUVC 1.00 */ 40, 0, 0xC0, 0xFC, 0x9B, 0x01, 1, 1, /* wTotalLength 40, clock 27 MHz, 1 stream interface: #1 */ /* ... terminals, then the streaming interface ... */ }; /* never type 168 by hand: let the compiler count */ _Static_assert(sizeof(cfg_desc) == 168, "wTotalLength must match");
The failure. You add a second frame descriptor, 30 bytes with one rate, and forget to raise wTotalLength and the input header’s total. The symptom: the camera enumerates, but the host lists one picture size, or none. Measure it: run lsusb -v and count the frame lines, then add up the bytes yourself. The fix is a sizeof check, as in the code above, so a mismatch fails the build.
One more habit helps. Give each record a comment with its name and its expected length, and keep the records in the order the host reads them. When something breaks, you can print the array as hex and walk it by eye with the same hop rule the host uses. Two minutes with a printout beats an hour of guessing.
On real hardware. On an STM32 Nucleo with a USB high-speed core, or an RP2040 with TinyUSB’s video capture example, run lsusb -v and compare wTotalLength with the number you counted. Then break it by one byte and see what the host drops.
Chapter 3
Write the exact bytes that offer one picture size and one frame rate to the host
A restaurant menu lists dishes, and each dish lists sizes. A camera does the same. The format descriptor names a kind of picture data. Each frame descriptor under it names one picture size and the frame rates that go with it.
Two formats cover most webcams. YUY2 is raw video. Each pixel takes 16 bits: a brightness byte for every pixel, plus two colour bytes shared by each pair of pixels. Two pixels therefore take four bytes. It is simple but heavy. MJPEG is Motion JPEG: every frame is a JPEG picture. It is lighter on the cable but needs a JPEG encoder in the camera. Chapter 2 of this series, Cameras on a Microcontroller, covers where the bytes come from.
The camera lists each format once and puts its frames under it. A typical webcam might offer YUY2 at three sizes and MJPEG at five. The host builds its picker from this tree. It never asks the camera to try a size that is not listed, which is why one wrong byte in a frame record makes that size vanish from the menu.
An uncompressed format record is 27 bytes long. It has the usual two bytes, then subtype 0x04, then an index: bFormatIndex, which starts at 1. The host will say “format 1” later, not “YUY2”. Next come the number of frame descriptors under it, then a 16-byte GUID that names the pixel layout. For YUY2 the first four bytes are the letters Y, U, Y, 2 in ASCII (0x59 0x55 0x59 0x32), followed by a fixed suffix (the TinyUSB header lists it in full). Then come bits per pixel (16), the default frame index, two aspect-ratio bytes, an interlace byte and a copy-protect byte.
The MJPEG format record is shorter, 11 bytes, subtype 0x06. A JPEG needs no GUID: there is only one way to lay out a JPEG.
The frame record (subtype 0x05 for uncompressed, 0x07 for MJPEG) carries the numbers that matter most. The offsets below match the ones the Linux uvcvideo parser reads.
| Offset | Field | Size | Meaning |
|---|---|---|---|
| 0 | bLength | 1 | 26 + 4 × number of rates |
| 1 to 2 | bDescriptorType, subtype | 2 | 0x24 (class-specific), 0x05 or 0x07 |
| 3 | bFrameIndex | 1 | starts at 1; the host names a frame by this |
| 4 | bmCapabilities | 1 | flags such as still-image support |
| 5, 7 | wWidth, wHeight | 2 + 2 | picture size in pixels |
| 9, 13 | dwMinBitRate, dwMaxBitRate | 4 + 4 | bits per second at the slowest and fastest rate |
| 17 | dwMaxVideoFrameBufferSize | 4 | bytes in the largest frame |
| 21 | dwDefaultFrameInterval | 4 | the usual time between frames, in units of 100 ns |
| 25 | bFrameIntervalType | 1 | 0 means a continuous range; n means n fixed rates |
| 26 … | dwFrameInterval[ ] | 4 each | the n allowed intervals (or min, max, step) |
The odd unit is the one to remember. A frame interval is a time, not a rate, counted in 100 ns ticks. One second is 10,000,000 ticks. So the interval for 30 frames per second is 10,000,000 ÷ 30 = 333,333 ticks. Linux prints a frame rate by dividing 10,000,000 by the interval. A continuous range (type 0) holds three numbers instead: minimum, maximum and step.
A fixed list is the safer choice for a small camera. The sensor has a few real modes, each with its own timing, and a list says exactly which ones. A continuous range promises every rate between two limits, and the firmware must then be able to build any of them. Most microcontroller cameras use a short fixed list.
Offer 640 × 480 YUY2 at 30 fps. Work each field in turn.
dwMaxVideoFrameBufferSize. In hex 0x00096000, sent low byte first: 00 60 09 00.15 16 05 00.bLength is 30.Build your own. Change the size and the rate, and read the bytes.
The strip shows the 30 bytes of the record in order. Each colour is one field. Change the options and the bytes rewrite themselves.
Field offsets as read by Linux uvcvideo. MJPEG sizes use an illustrative worst case of 0.5 bytes per pixel, because a real JPEG size depends on the picture. The one-rate descriptor is shown; a camera lists more rates by adding 4 bytes each.
Do not type bytes by hand. Let macros do the splitting so a typo cannot hide.
c/* 100 ns ticks per frame, and a 32-bit value as four bytes, low first */ #define INTERVAL(fps) (10000000u / (fps)) #define U32(x) (x)&0xFF, ((x)>>8)&0xFF, ((x)>>16)&0xFF, ((x)>>24)&0xFF #define U16(x) (x)&0xFF, ((x)>>8)&0xFF #define FRAME_YUY2(idx, w, h, fps) \ 30, 0x24, 0x05, (idx), 0x00, /* len, CS_INTERFACE, FRAME_UNCOMPRESSED */ \ U16(w), U16(h), /* wWidth, wHeight */ \ U32((w)*(h)*2u*8u*(fps)), U32((w)*(h)*2u*8u*(fps)), /* min, max bit rate */ \ U32((w)*(h)*2u), /* dwMaxVideoFrameBufferSize */ \ U32(INTERVAL(fps)), /* dwDefaultFrameInterval */ \ 1, U32(INTERVAL(fps)) /* one fixed rate, then that rate */
The failure. You write 30 into dwFrameInterval thinking “30 fps”. The field means 30 ticks of 100 ns, which is 3 µs. The symptom: the host lists a frame rate of 333,333 fps, or drops the mode. Measure it with v4l2-ctl --list-formats-ext and look at the interval lines. The fix is the INTERVAL macro: always convert from a rate.
On real hardware. With any UVC camera or a TinyUSB or Zephyr UVC build on an STM32 board, run v4l2-ctl --list-formats-ext -d /dev/video0. Pair each line with a frame descriptor in your array. Change the 30 to 25 and read the new interval.
dwFrameInterval for 25 frames per second?Chapter 4
Follow the short bargain in which the host asks for a mode and the camera says what it can really do
You order a coffee at a counter. “Large oat latte, extra hot.” The barista says, “We have no oat milk. Soy?” You say yes. Now the order is final, and the cup gets made.
Probe and commit works like this. The descriptors list what is possible. The host now picks one mode. It cannot just announce the choice, because it does not know the camera’s limits at this moment (a rate may drop when two streams share a sensor). So it asks first, probes, reads the camera’s counter-offer, and only then commits.
Both messages carry the same record, the probe and commit control. Its size depends on the UVC version. The Linux driver chooses 26 bytes for versions below 1.1, 34 bytes for 1.1 and up to 1.4, and 48 bytes for 1.5. The 34-byte form has these fields:
bmHint (2 bytes): which field the host cares about most. Bit 0 means “keep my frame interval”.bFormatIndex, bFrameIndex (1 byte each): the mode, by the numbers from Chapter 3.dwFrameInterval (4): the time between frames, in 100 ns ticks.wKeyFrameRate, wPFrameRate, wCompQuality, wCompWindowSize) and wDelay (2 bytes each). Many cameras leave them at zero.dwMaxVideoFrameSize (4): bytes in the largest frame. The camera fills this in.dwMaxPayloadTransferSize (4): the most bytes the camera will send in one go. The camera fills this in too. It decides which alternate setting the host books.dwClockFrequency (4), bmFramingInfo, and three version bytes close the record.The host sends these on endpoint 0 with class requests. For the probe, the setup packet is: bmRequestType 0x21 (host to device, class, interface), bRequest 0x01 (SET_CUR), wValue 0x0100 (selector 1, VS_PROBE_CONTROL, in the high byte), wIndex the streaming interface number (1 here), wLength 34. A read uses 0xA1 and 0x81 (GET_CUR). The commit uses selector 2, so wValue 0x0200. Linux builds wValue as the selector shifted left by 8, and wIndex as unit << 8 | interface.
dwMaxPayloadTransferSize. Linux picks the smallest one that is big enough.Run the bargain below. The camera on the right offers YUY2 at 640×480 and at 1280×720, and MJPEG at 1280×720 and at 1920×1080. Choose what the host asks for, then press Next message.
Pick a request. Each press of Next message sends one control transfer. The table compares what the host asked with what the camera answered. Changed fields glow.
Model of the exchange, using the field layout of the 34-byte control and the Linux request sequence. The camera’s mode list is made up for this lesson. A real camera may answer an unknown index by STALLing the request or by correcting the index; both are seen. Payload sizes use this lesson’s model (2-byte headers, 0.5 bytes per pixel for MJPEG).
In the camera, the handler for SET_CUR(PROBE) copies the host’s record, checks each index and the interval against a table, rewrites what is not possible, computes the two size fields, and keeps the result for GET_CUR. It must not touch the sensor yet. Probing is cheap and may happen many times. Only SET_CUR(COMMIT) moves the sensor.
Why split the bargain in two? Because the host may want to compare several options without disturbing a running stream. Another application may already use the camera, and a probe must not break its picture. A probe reads the future. A commit changes the present. Keeping them apart lets a host try three modes in a row, pick the best, and only then pay the cost of reconfiguring the sensor.
ctypedef struct __attribute__((packed)) { uint16_t bmHint; uint8_t bFormatIndex, bFrameIndex; uint32_t dwFrameInterval; uint16_t wKeyFrameRate, wPFrameRate, wCompQuality, wCompWindowSize, wDelay; uint32_t dwMaxVideoFrameSize, dwMaxPayloadTransferSize, dwClockFrequency; uint8_t bmFramingInfo, bPreferedVersion, bMinVersion, bMaxVersion; } vs_ctrl_t; /* 34 bytes */ static vs_ctrl_t cur; /* what GET_CUR returns */ void on_probe_set(const vs_ctrl_t *req) { cur = *req; const mode_t *m = find_mode(req->bFormatIndex, req->bFrameIndex); if (!m) { usb_stall_ep0(); return; } /* unknown index */ cur.dwFrameInterval = nearest_interval(m, req->dwFrameInterval); cur.dwMaxVideoFrameSize = m->frame_bytes; cur.dwMaxPayloadTransferSize = payload_per_uframe(m, cur.dwFrameInterval); } void on_commit_set(const vs_ctrl_t *req) { active = *find_mode(req->bFormatIndex, req->bFrameIndex); sensor_configure(&active, req->dwFrameInterval); /* only now touch the sensor */ }
The failure. The handler leaves dwMaxPayloadTransferSize at zero. The symptom: the picture is choppy or frozen at a high mode. The driver treats zero as the smallest request and logs that it is defaulting to the lowest setting, so it books the smallest alternate setting. Measure it: compare the frame rate you get with the rate you asked for (v4l2-ctl --stream-mmap --stream-count=300 prints it). The fix is to compute the payload size as Chapter 6 shows.
On real hardware. On a Linux host, load the usbmon module and capture the camera with Wireshark. Find the control transfers with wValue 0x0100 and 0x0200. Read the dwFrameInterval that came back. The uvcvideo module also has a trace option that prints probe steps to the kernel log.
Chapter 5
Cut a frame into packets, stamp each one, and let the host glue the frame back together
You mail a long letter as a stack of postcards. If you number nothing, the reader gets a heap of cards and cannot tell where one letter ends and the next begins.
A video frame is bigger than one USB packet. A 640×480 YUY2 frame is 614,400 bytes, and one packet carries at most 1,024. So the camera sends the frame in many pieces. The host needs two answers: which frame does this piece belong to? and is this the last piece? The tool for that is the payload header, a few bytes the camera puts at the front of every packet.
The header is 2 to 12 bytes. The first two bytes are always there.
bHeaderLength (byte 0): how long this header is, counting itself. The host skips this many bytes to reach the video data. The Linux driver rejects a packet whose header length is below 2 or longer than the packet.bmHeaderInfo (byte 1): eight flag bits. They are listed below.dwPresentationTime) when the PTS bit is set, and a 6-byte source clock reference when the SCR bit is set. With both, the header is 2 + 4 + 6 = 12 bytes.| Bit | Name | Value | Meaning |
|---|---|---|---|
| 0 | FID, frame ID | 0x01 | flips from 0 to 1 or back at each new frame |
| 1 | EOF, end of frame | 0x02 | set on the last packet of a frame |
| 2 | PTS | 0x04 | a presentation time field follows |
| 3 | SCR | 0x08 | a source clock reference follows |
| 4 | RES | 0x10 | reserved |
| 5 | STI, still image | 0x20 | this packet belongs to a still picture |
| 6 | ERR, error | 0x40 | the camera had a problem with this frame |
| 7 | EOH, end of header | 0x80 | always 1 on the last header byte |
These bit values are the ones in the Linux kernel’s UVC header (UVC_STREAM_FID is 1 << 0 up to UVC_STREAM_EOH at 1 << 7).
The host follows three rules.
A good camera sets EOF, so the host sees the frame the moment the last packet lands. Some cameras forget EOF. The Linux driver copes: it notices the FID flip on the next frame’s first packet. But then every frame arrives one frame time late. At 30 fps that is 33 ms of added delay, for every frame.
Take a tiny frame of 38,400 bytes (160×120 YUY2) and packets of 1,024 bytes. Each packet holds a 2-byte header and 1,022 bytes of video. 38,400 ÷ 1,022 = 37.57, so 38 packets: 37 full ones and a last one carrying 38,400 − 37 × 1,022 = 586 video bytes.
02 80 on packets 1 to 37. The last one is 02 82 (EOH plus EOF).02 81 on packets 1 to 37, and 02 83 on the last.Add the PTS and the header grows to 6 bytes: 06 84 … followed by four time bytes. Each packet then holds 1,018 video bytes. The frame still takes 38 packets, but the last one carries 38,400 − 37 × 1,018 = 734 video bytes. Try it below, and try a smaller packet size.
Each box is one packet: a thin pink header and a purple body. Frame A is the bright run, frame B the dim run. A green rim marks the packet with the EOF flag. Change the packet size and toggle the options.
Illustrative small frame of 38,400 bytes, so the whole run of packets fits on screen. The flag bits and header lengths are the UVC ones used by Linux. Which packets carry a PTS is a choice of the camera; here every packet does when the toggle is on.
The sending side is a small loop. It fills a packet buffer with the header, copies the next slice of the frame, and sets EOF on the last one. Flip FID once per frame, after the last packet.
cstatic uint8_t fid; /* toggles per frame */ size_t build_packet(uint8_t *pkt, size_t max, const uint8_t *frame, size_t *off, size_t frame_len) { const size_t hdr = 2; size_t n = frame_len - *off; if (n > max - hdr) n = max - hdr; pkt[0] = hdr; /* bHeaderLength */ pkt[1] = 0x80 | fid; /* EOH | FID */ memcpy(pkt + hdr, frame + *off, n); *off += n; if (*off == frame_len) { pkt[1] |= 0x02; fid ^= 1; *off = 0; } /* EOF, next frame */ return hdr + n; }
The failure. The loop never flips fid. The symptom: frames glue together, or the host shows a frozen image, because it never sees a frame boundary. Measure it: in a USB capture, look at byte 1 of the packets across a frame boundary. The fix is the one line fid ^= 1 at the end of each frame.
On real hardware. On an STM32 Nucleo or RP2040 running a UVC example, capture the isochronous IN endpoint with Wireshark on usbmon. Filter on the endpoint and read the first two bytes of each payload. You should see 02 8x repeating, and the last bit flipping once per frame.
Chapter 6
Work out how many bytes a camera needs in every microframe, and why the host picks one alternate setting from a list
A conveyor belt passes your window 8,000 times a second. You may put one box on it each time. If the pictures you sell weigh more than the boxes can hold in one second, no trick makes them fit.
That is the isochronous pipe. The host offers a fixed number of slots, and each slot carries at most the endpoint’s packet size. Chapter 1 showed the booking rules. This chapter works out what a given video mode needs, and how the camera tells the host.
dwMaxPayloadTransferSize.Now the host looks at the camera’s list of alternate settings. Each one has an endpoint with its own wMaxPacketSize. For high speed the choices are the size of a packet (up to 1,024) times one, two or three transactions per microframe, so up to 3,072 bytes per slot. The Linux driver picks the smallest setting whose size is at least 2,316. In our example list that is the 3,072-byte one.
Notice the waste. The video itself needs 18.4 million bytes per second (614,400 × 30). The booked slot is 3,072 × 8,000 = 24.6 million bytes per second. The unused 25% is not free for other devices, because the booking holds for as long as the stream runs. Isochronous trades efficiency for a promise.
Try 1280×720 YUY2 at 30 fps. A frame is 1,843,200 bytes. Divide by 266 slots: 6,930 bytes per slot, plus 14 header bytes for 7 packets, 6,944 in all. The best setting carries 3,072. It cannot fit, however the firmware is written.
The camera has four honest options. Lower the rate: at 10 fps a frame lasts 800 slots, so 1,843,200 ÷ 800 = 2,304 bytes per slot, plus 6, which is 2,310. It fits. Lower the size. Compress the video (MJPEG). Or offer more bandwidth, which a high-speed USB 2.0 link cannot do beyond 3,072 bytes per slot. This is why many cheap webcams offer 1280×720 raw only at a low rate such as 10 fps, and why they offer MJPEG for 30 fps.
At full speed the numbers shrink. A slot is 1 ms and an isochronous packet holds at most 1,023 bytes, so about 1 MB per second. A 160×120 YUY2 stream at 15 fps (576,000 bytes per second) fits. A VGA stream does not.
Each bar is the bytes per slot that a mode needs, headers included. The vertical line is the size of the alternate setting you choose. Green modes fit. Red modes do not. Switch the bus speed to see why full-speed cameras are small.
Model, using the arithmetic above with 2-byte headers. High-speed slots are 125 µs and the chosen setting is your capacity per slot. Full speed uses 1 ms slots and one packet of at most 1,023 bytes; the alt buttons are ignored. MJPEG assumes an illustrative 0.5 bytes per pixel worst case.
The firmware does two jobs. It builds the list of alternate settings in the descriptors, one per packet size it supports. And it computes dwMaxPayloadTransferSize during probe, using the arithmetic above.
c/* bytes per 125 us microframe for one frame mode, headers included */ uint32_t payload_per_uframe(uint32_t frame_bytes, uint32_t interval_100ns) { uint32_t uf = interval_100ns / 1250; /* 125 us = 1250 ticks of 100 ns */ uint32_t pay = (frame_bytes + uf - 1) / uf; /* round up */ uint32_t pkts = (pay + 1023) / 1024; /* packets of up to 1024 */ return pay + 2 * pkts; /* 2-byte header each */ } /* wMaxPacketSize: bits 10:0 = size, bits 12:11 = extra transactions */ #define WMAX(bytes, extra) ((bytes) | ((extra) << 11)) static const uint16_t alt_size[] = { 128, 256, 512, 1024, WMAX(1024, 1) /*0x0C00*/, WMAX(1024, 2) /*0x1400*/ };
The failure. You report a payload size larger than every alternate setting. The symptom: the preview never starts and the application reports an input/output error. Linux searches for an alternate setting that is big enough, and if none exists the start fails with an I/O error. Measure it: list your alternate settings with lsusb -v, and compare their largest size with the dwMaxPayloadTransferSize from the probe capture. The fix is to lower the frame rate in the probe answer until the number fits.
On real hardware. On an STM32 board with a USB high-speed core, set the endpoint to the 0x1400 size and run a test pattern at 640×480 and 30 fps. Capture with usbmon and count the bytes per microframe. You should see about 2,316 bytes in each, as computed here.
Chapter 7
Follow one frame from sensor to USB packet, and see how many buffers keep the stream smooth
A baker pulls trays from the oven and a driver collects them at fixed times. If the baker has only one tray, the oven waits while the driver loads. If the driver is late, trays pile up. The fix is more trays and a plan for the pile.
A UVC camera has the same two clocks. The sensor makes a frame every 33 ms. The USB host asks for a packet every 125 µs, no matter what. Between them sit frame buffers, blocks of RAM that hold a frame while it is written by one side and read by the other.
The send step has a hard deadline. At a 168 MHz clock, 125 µs is 21,000 cycles. The handler for the endpoint must queue the next packet inside that time, every time. Use DMA for the copy, and measure the handler with the cycle counter (see Seeing Inside a Running Chip). In TinyUSB’s video class the application hands over a whole frame with tud_video_n_frame_xfer() and the stack cuts it into packets with headers.
If there is no new frame data in a slot, the camera still answers the host. An idle packet that carries only the 2-byte header is the safe answer. Silence on an isochronous endpoint just means the host sees nothing.
Do the sum first. A 640×480 YUY2 frame is 614,400 bytes. An STM32F407 has 192 KB of SRAM, which is 196,608 bytes. The frame is three times bigger than the whole memory. Even one buffer does not fit, and you want at least two.
You have three ways out. Use a smaller mode (320×240 YUY2 is 153,600 bytes, still large). Use MJPEG, where a frame might take tens of kilobytes (illustrative; it depends on the picture). Or use a part with more memory, such as an STM32H7 with about 1 MB of internal RAM, or add external RAM. Frame-buffer planning is the real limit on a microcontroller webcam.
Say a frame takes 0.9 of a frame time to capture, and the USB side needs a share D of a frame time to send it. The rules are short.
With one buffer and D = 0.5, the capture ends at 0.9 and the send runs until 1.4. The next frame starts at 1.0, but the buffer is busy. That frame is dropped. The camera delivers every other frame, 15 fps from a 30 fps sensor. With two buffers the sender uses buffer 0 while the sensor fills buffer 1, and every frame passes. With D above 1, even two buffers lose: the sender falls further behind each frame until the pile has no room. Then you need a lower frame rate (Chapter 6), not more RAM.
Top lane: the sensor fills buffers. Bottom lane: USB drains them. Red outline: a dropped frame. Change the number of buffers and how long the USB side needs per frame.
Model over 60 frames. A capture takes 90% of a frame time; the frame time is 33.3 ms (30 fps). Delay is measured from the start of capture to the end of sending. Toy timing; real cameras add exposure time and jitter.
The value to read is the delay. With two buffers at D = 0.7, a frame is captured in 0.9 and sent in 0.7 more, so the host sees it 1.6 frame times after capture began: 53 ms. A third buffer smooths jitter but does not shorten that chain. Low delay comes from sending while still capturing, which needs a sensor that sends line by line and a JPEG encoder that works on strips. That is how video-call cameras cut delay.
c/* the glue: two buffers, one owner at a time */ static uint8_t buf[2][FRAME_MAX]; static volatile int cap = 0, ready = -1, sending = -1; void DCMI_FrameEvent_IRQ(void) { /* sensor finished a frame */ int other = cap ^ 1; if (ready < 0 && sending != other) { /* the other buffer is free */ ready = cap; cap = other; if (sending < 0) usb_frame_done_cb(); /* sender idle: start it */ } dcmi_dma_restart(buf[cap]); /* no free buffer: rewrite cap, dropping this frame */ } void usb_frame_done_cb(void) { /* last packet of a frame has gone */ sending = -1; if (ready >= 0) { sending = ready; ready = -1; usb_send_frame(buf[sending]); } }
The failure. The symptom is a preview that runs at half the frame rate you asked for, or stutters in a pattern. Measure it: count the capture interrupts and the completed sends over ten seconds. If captures are 300 and sends are 150, the pipeline drops every other frame. The fix is a second buffer, a smaller mode, or a lower rate.
On real hardware. On an STM32 Nucleo with a camera module, toggle a GPIO in the capture interrupt and another in the send-done callback. Put both on a logic analyser. The time between the two edges is your delay. Count edges over 10 s for the drop rate.
Chapter 8
Use six host-side measurements to find which layer of the camera is at fault
You plug in your new firmware. The preview window opens and shows black. Where do you look first? A black picture has at least six possible causes, and they live in six different layers. Guessing wastes days. Measuring takes minutes.
The idea is to walk the layers from the cable inwards, as the host does. Each layer has one tool that tells you whether it works.
Write down what you expect at each layer before you look. For a 640×480 YUY2 camera at 30 fps, you expect 168 descriptor bytes, a probe reply with an interval of 333,333 and a payload size of 2,316, an alternate setting of 3,072, and packets of about 2,316 bytes, and the FID bit flipping once per 614,400 bytes of video. A number that differs from your expectation points straight at the broken layer. That is the whole method: expected value, measured value, first mismatch.
lsusb. If the device is missing, the fault is below this lesson: clocks, pull-ups, D+ and D− (see Buses on the Wire).lsusb -v -d VID:PID. Count the formats, frames and alternate settings. Compare wTotalLength with your array’s size (Chapter 2).usbmon and Wireshark. Check the interval and the two size fields in the reply (Chapter 4).Reading an isochronous capture takes a minute to learn. Each line is one packet with a time, a length and the first bytes. A healthy 640×480 stream shows a steady run of long packets, then one short packet at the end of each frame. A starved stream shows a run of 2-byte packets, which are headers with no video. A stream that stops shows gaps. The length column alone often names the layer: all 2s point at the sensor path, all maximum-length point at a bandwidth ceiling, and a pattern of long runs with periodic gaps points at the buffers.
Two helper commands are worth knowing. v4l2-ctl --list-formats-ext prints every format, size and rate the driver parsed from your descriptors. v4l2-ctl --stream-mmap --stream-count=300 asks for 300 frames and prints the rate it got.
Suppose the preview opens, but it shows one new picture every second or so. Walk the ladder with the expected numbers from above. Layers one to three pass: the camera is listed, the descriptors are whole, and the probe reply shows an interval of 333,333.
Layer four fails. The capture shows packets of 128 bytes in every microframe, not 2,316. The header takes 2 bytes, so each packet carries 126 bytes of video. A 614,400-byte frame needs 614,400 ÷ 126 = 4,876.2, so 4,877 packets. At 8,000 packets per second that is 4,877 ÷ 8,000 = 0.61 s per frame, or 1.64 frames per second. That matches what you see.
Now find the cause. Go back to the reply in layer three. The field dwMaxPayloadTransferSize reads 0. The host treats zero as a request for the smallest booking, so it chose the alternate setting with the 128-byte packet (Chapter 4). The fault is one field in the probe handler, found in four measurements, with no guessing about the sensor.
A UVC camera is two systems glued together: a sensor path and a USB path. Debug them apart. Make the firmware send a test pattern, a frame the chip makes itself, such as colour bars or a moving gradient. If the pattern shows on the host, the USB side works and the fault is in the sensor path. If not, the fault is in the USB side. The Zephyr UVC sample ships this idea as a snippet with a software test pattern that needs no camera.
Each case gives you one measurement, written the way a host would show it. Pick the likely cause. A wrong pick tells you why it is wrong.
Choose a case. Read the host evidence. Then choose the cause you believe.
The log lines are illustrative reconstructions in the style of lsusb, v4l2-ctl and a USB capture, not output from one real camera. The numbers match this lesson’s arithmetic.
On real hardware. Pick any UVC firmware you can build (TinyUSB video capture example on an RP2040 or STM32, or the Zephyr UVC sample) and break it on purpose, one case at a time: leave the payload size at zero, never flip FID, shorten wTotalLength by 4. Record what each break looks like in v4l2-ctl and in the capture. That table is your own debugging field guide.
Chapter 9
Keep the numbers, the checklist and the core code for the next time you build or debug a USB camera
A UVC camera is a chip that answers three questions in a fixed format. It describes itself in descriptors, agrees one mode with the host in probe and commit, and sends frames as headed packets over a booked isochronous pipe. Every other problem is in memory, timing or the sensor.
| Item | Value | Where it appears |
|---|---|---|
| Video class code | 0x0E; subclasses 1 control, 2 streaming, 3 interface collection | Interface and IAD descriptors (Ch 2) |
| Descriptor lengths | IAD 8, camera terminal 18, output terminal 9, YUY2 format 27, frame 26 + 4n, color matching 6 | Ch 2, 3 |
| Minimal camera list | 168 bytes (VC section 40, VS section 77) | Ch 2 |
| Frame interval | 100 ns ticks; 30 fps = 333,333 | Ch 3, 4 |
| Probe/commit size | 26 (before 1.1), 34 (1.1 to 1.4), 48 bytes (1.5) | Ch 4 |
| Control selectors | VS_PROBE_CONTROL 0x01, VS_COMMIT_CONTROL 0x02 | wValue = selector << 8 (Ch 4) |
| Requests | SET_CUR 0x01, GET_CUR 0x81, GET_MIN 0x82, GET_MAX 0x83, GET_DEF 0x87 | Ch 4 |
| Payload header | 2 to 12 bytes; FID 0x01, EOF 0x02, PTS 0x04, SCR 0x08, ERR 0x40, EOH 0x80 | Ch 5 |
| High-speed slot | 125 µs, 8,000 per second, up to 3 × 1,024 = 3,072 bytes (24.6 MB/s) | Ch 1, 6 |
| Periodic limit | 80% of a high-speed microframe, 90% of a full-speed frame | Ch 1 |
| Full-speed slot | 1 ms, up to 1,023 bytes (about 1 MB/s) | Ch 6 |
| wMaxPacketSize | bits 10:0 size, bits 12:11 extra transactions (0x1400 = 3 × 1,024) | Ch 6 |
This is the host side in short form. It is what the Linux driver does, and it is the test your firmware must pass.
c/* host: start streaming one mode */ ctrl = {.bFormatIndex = fmt, .bFrameIndex = frm, .dwFrameInterval = 10000000u / fps}; ctrl_out(SET_CUR, VS_PROBE_CONTROL, &ctrl, 34); /* ask */ ctrl_in (GET_CUR, VS_PROBE_CONTROL, &ctrl, 34); /* camera's counter-offer */ ctrl_out(SET_CUR, VS_COMMIT_CONTROL, &ctrl, 34); /* accept: sensor starts */ best = -1; for (alt = 1; alt <= n_alts; alt++) /* smallest big-enough setting */ if (ep_payload(alt) >= ctrl.dwMaxPayloadTransferSize && (best < 0 || ep_payload(alt) < ep_payload(best))) best = alt; if (best < 0) return -EIO; /* nothing big enough */ set_interface(streaming_itf, best); /* the host books bandwidth now */ while (streaming) { n = read_iso_packet(buf); hl = buf[0]; info = buf[1]; /* header length, flags */ if ((info & FID) != last_fid) finish_frame(); if (info & ERR) mark_bad(); append(frame, buf + hl, n - hl); if (info & EOF) finish_frame(); last_fid = info & FID; }
sizeof or a macro, and a static assert checks the total.This lesson covers the USB end. For the sensor end read Sensor Bring-Up and Cameras on a Microcontroller. For the Linux side of a camera, see A V4L2 Sensor Driver; a later lesson on V4L2 and the buffer queue is planned. USB audio uses the same isochronous machinery: see USB Audio and Bluetooth Audio.
uvcvideo driver: uvc_video.c (control sizes 26, 34 and 48, probe sequence, alternate-setting choice, header handling) and uvc_driver.c (frame descriptor offsets).Now press Teach and explain, from memory, how a 720p camera gets from a plug to a picture: the descriptors, the probe, the payload size and the alternate setting. Then go back to the instrument at the top, choose MJPEG at 1920×1080, and say why the host picks the setting it does.