Two recorders each started at zero and each kept their own clock. After an hour, a flash and a click let you line them up to under 1 millisecond, and prove it.
Learn to find a shared event in an audio file and an EEG file, measure the offset and the drift between them, and write a residual report that shows the alignment is good.
Drag Offset and Skew until the yellow dots sit inside the green band, or press Auto-align and watch least squares do it. Then we build every step, from the first flash to the report.
You need what a sample rate is (how many readings a recorder takes each second) and a rough idea of a straight line. We build the rest from zero.
Grounded in the Lab Streaming Layer time synchronization notes, the XDF 1.0 specification and the pyxdf importer. The recorders, clocks and noise here are models; Chapter 9 lists the sources.
A model, not a recording: 13 sync events, one every 300 s over an hour, with a true offset of 2413.7 ms, a true skew of +37 ppm and 0.2 ms of detection noise, all illustrative and seeded. The vertical axis is a signed log scale, so 0.1 ms and 100 ms both fit.
Chapter 0
See why two recordings of the same hour never line up on their own, and what it takes to prove that you lined them up
A volunteer sits in a quiet room. She wears an EEG headset (electroencephalography: a cap that measures tiny voltages on the scalp, a few millionths of a volt). A microphone records the room. Every few minutes a beep plays, and you want to know what her brain did 200 milliseconds after each beep.
The hour ends. You have two files. One is the audio file. The other is the EEG file. Each file counts time from its own zero, the moment its own recorder started.
Those two zeros are not the same moment. The EEG recorder started 2.4 seconds before the audio recorder, because a person pressed two buttons. That gap is a constant, and it is the easy part.
Each recorder counts time with a crystal, a tiny quartz part that ticks at a fixed rate. No two crystals tick at exactly the same rate. One may run 37 parts per million faster than the other. A part per million (ppm) is one microsecond of error for every second that passes.
Do the sum. One hour is 3,600 seconds. At 37 ppm, the error grows by 37 microseconds each second, so after an hour it is 3,600 × 37 µs = 133.2 ms. The EEG samples arrive at 250 per second, 4 ms apart. So the drift after one hour is more than 33 EEG samples.
The lesson fw-sync-01 explains why crystals drift. Lesson fw-sync-03 builds a live sync layer that keeps the boards of one device on a shared timeline. This lesson asks the next question: did it work, and how well? You answer it later, offline, with the recordings in hand.
The offset is the constant gap between the two zeros. Here it is 2,413.7 ms. The skew is the speed difference between the two clocks, in ppm. Here it is +37 ppm. Together they say where any moment in the audio file lands in the EEG file: an offset plus a stretch.
The jitter is the small random error in each measurement. You never find an event time exactly, so every event carries a little noise. The residual is what is left after you apply your best offset and skew: for each event, the gap between where the EEG file says the event is and where your mapping says it should be. Residuals are the proof. If they are small and look like noise, the mapping is right. If they show a shape, something is still wrong.
The line shows how far apart the same moment sits in the two files. Drag the time along the audio file and read how much the gap has changed since the start.
Illustrative: offset 2413.7 ms, skew +37 ppm. The gap at time t is 2413.7 ms plus 37 microseconds for every second of t. Real skew between two crystals depends on the parts and the temperature, so you measure it; you do not assume it.
The line is straight, and that matters. A constant skew means the gap grows by the same amount each minute. So two numbers describe the whole hour: where the line starts (the offset) and how steeply it climbs (the skew). Finding those two numbers from the recordings alone is the job of this lesson.
The audio file knows nothing about the EEG file. They cannot compare clocks. But the world is shared. If a click is heard by the microphone and a flash is seen by a light sensor wired into the EEG amplifier, both recordings hold the same event. That event is a sync marker: one real moment, written into both files by the world.
The Lab Streaming Layer (LSL), a widely used system for recording many sensor streams together, says the same for devices that do not speak its protocol. Synchronizing such a device needs a separate solution, and the notes name "a shared hardware pulse with cross-correlation" as one option. Offline, they say a linear regression is usually enough. We will do exactly that, and we will check our work.
Chapter 1
Design a flash and a click that both recorders see, and shape them so that only one alignment can fit
Think of a film clapperboard. A person snaps it shut in front of the camera. The picture shows the stick closing. The sound track holds a sharp crack. The editor finds both and slides the sound until the crack meets the frame where the stick closes. One sharp event, written into two recordings, ties them together.
Our EEG session needs the same trick, built into the hardware. The event has to show up in the audio file as a click and in the EEG file as a flash. Four properties make a marker good.
Light crosses a 1.5 metre room in about 5 nanoseconds. That is far below one EEG sample, so a flash is a clean anchor. Sound is slower. In air at 20 °C it travels at about 343 metres per second, which is 2.9 ms for every metre.
A speaker 1.5 m from the microphone adds 1.5 × 2.9 = 4.4 ms before the click is heard. That is more than one EEG sample. If the speaker and the microphone never move, the delay is a constant, and it hides inside the offset. If a person walks about, the delay changes and looks like noise. So the best click is electrical: the same pin that fires the LED also drives a line into the audio input, with no air in between.
Many boards have one microcontroller (MCU, the small chip that runs your firmware) that already owns the recorders. In fw-sync-03 you built a sync layer between boards. Here one board gets one extra job: it fires the marker. One pin, three loads.
c/* NUCLEO-G474RE (Cortex-M4). PA5 drives the sync LED (the board's LD2), PA6 drives the click line into the audio input. Clock and pin setup are omitted. TIM2 is a 32-bit counter at 1 MHz. */ #include "stm32g4xx.h" #define SYNC_ON (GPIO_BSRR_BS5 | GPIO_BSRR_BS6) /* set both pins in ONE write: same edge */ #define SYNC_OFF (GPIO_BSRR_BR5 | GPIO_BSRR_BR6) static const uint16_t gap_ms[4] = { 164, 268, 116, 332 }; /* 41, 67, 29, 83 EEG samples x 4 ms */ volatile uint32_t pulse_stamp[5]; /* TIM2->CNT at each rising edge, 1 us ticks */ static uint8_t n_sent; static uint16_t countdown = 1; /* first pulse fires on the next tick */ static uint8_t width_left; void SysTick_Handler(void) { /* every 1 ms */ if (width_left && --width_left == 0) GPIOA->BSRR = SYNC_OFF; /* 5 ms wide pulse */ if (n_sent < 5 && --countdown == 0) { GPIOA->BSRR = SYNC_ON; /* LED and click rise together */ pulse_stamp[n_sent] = TIM2->CNT; /* a log for debugging, not the alignment */ width_left = 5; countdown = (n_sent < 4) ? gap_ms[n_sent] : 0; n_sent++; } }
Look at what the code does not promise. The interrupt runs on a 1 ms tick, so the absolute moment of each edge is only good to about a millisecond. That is fine. Both recorders see the same edge, so its true time cancels when you compare the two files. What the code must get right is the spacing between the five edges.
On real hardware. Use a Nucleo-64 board such as the NUCLEO-G474RE. Put one scope probe on PA5 and the other on the light-sensor amplifier output. Measure the delay and the rise time of the light. Then measure the acoustic delay of a speaker click at 0.5 m, 1 m and 2 m. You should see about 1.5, 2.9 and 5.8 ms.
Suppose you send five pulses spaced exactly 60 samples apart. The pattern looks the same when you slide it by 60. A recorder that misses the first pulse, or a noise bump that mimics one, can make the wrong slide look almost as good as the right one. The pattern has the same ambiguity that a repeating wallpaper has: you cannot tell which repeat you are looking at.
The fix is to make every gap different. Our pattern puts pulses at samples 0, 41, 108, 137 and 220. The gaps are 41, 67, 29 and 83. Now check every pair of pulses. The ten distances between them are 41, 67, 29, 83, 96, 112, 108, 137, 179 and 220, and no two match. So if you slide the pattern to any wrong place, at most one pulse can land on a pulse. At the right place, all five do.
Top: a recording that holds your pattern at lag 137. Bottom: how well the pattern matches at every lag. Try the three patterns. Then lose a pulse, add a stray click, and raise the noise.
A model: pulses are Gaussian bumps 1.5 samples wide on a 250 Hz grid, the score is the normalized cross-correlation of Chapter 3, and the noise is random. The true lag is 137 samples. The numbers are illustrative; the ranking of the three patterns is not.
A pattern also needs room around it. Keep the pulses far enough apart that the light sensor and the amplifier recover between them, about 5 ms wide with at least 100 ms of quiet is a safe start. And keep the whole pattern short, under a second, so that the skew cannot stretch it by a measurable amount while it plays: at 37 ppm a one second pattern stretches by 37 microseconds.
Read the second peak, not only the first. The ratio of the second-best peak to the best one is your safety margin. A ratio near 1.0 means two answers fit almost equally well, and noise may choose between them. A ratio near 0.4 means the answer stands out. The coded pattern keeps the ratio low even when it loses a pulse. The even train does not.
Chapter 2
Read an event time off a recording to a fraction of one sample, and see what limits how well you can do it
You open the EEG file. It is a long list of numbers, 250 for every second. Somewhere in the list the light sensor channel jumps from near zero to near one. That jump is your flash. You must write down when it happened.
A recording does not hold the moment. It holds snapshots. At 250 samples per second a new snapshot arrives every 4 ms. The flash may have started anywhere between two snapshots. So the question is how to turn snapshots into a time better than the 4 ms grid.
A threshold crossing is the moment the signal rises past a chosen level. Choose the level halfway between the quiet value (the baseline) and the lit value (the top). Halfway is the steepest part of the edge, so a small noise error there moves the crossing the least.
The simplest rule says: the event is at the first sample that is above the threshold. This rule is easy and it is wrong in a predictable way. The real crossing happened somewhere in the 4 ms before that sample. On average it happened 2 ms earlier. So the rule is late by half a sample, on average, and any single event can be off by anything from 0 to 4 ms. Averaged over many events, the error has a typical size (RMS, the root of the mean of the squares) of 2.3 ms: 2 ms of bias from the lateness, plus 1.15 ms of spread, since a flat spread over 4 ms has a standard deviation of 4 ÷ √12 = 1.15 ms.
That error is large. It is half a sample, and it does not shrink when you collect more events in a row, because the bias is the same each time. We can do much better.
The edge is not a step. The light sensor, its amplifier and the converter's own digital filter spread the edge over a few milliseconds. This is the rise time. If the rise time is longer than one sample, several samples sit on the slope. Two of them straddle the threshold: one just below, one just above.
Draw a straight line between those two. Where the line meets the threshold is your estimate. This is linear interpolation, and it gives a time that lies between the samples.
Work one by hand. The threshold is 0.5. The sample at 24 ms reads 0.31. The next sample, at 28 ms, reads 0.62. The signal climbed 0.31 in 4 ms. It needed to climb 0.19 to reach 0.5. The fraction is 0.19 ÷ 0.31 = 0.613. So the crossing is at 24 + 4 × 0.613 = 26.45 ms. The first-sample-above rule would have said 28 ms, which is 1.55 ms late.
Dots are the 250 Hz samples. The grey line is the real analog edge. Green is the true crossing, grey is the first-sample rule, purple is interpolation. Change the rise time and the noise, then press New edge.
A model: the edge is a straight ramp of height 1, the noise is Gaussian on every sample, and the sample period is 4 ms (250 SPS, a rate the ADS1299 supports). The statistics come from 400 seeded edges that start at random phases inside the sample grid.
Slide the rise time down to 2 ms. The ramp now fits inside one sample gap. At most one sample can sit on it, so the line between samples is a poor stand-in for the edge. The interpolated error climbs back toward the sample size. Interpolation needs a rise time of at least about one sample period.
Now raise the noise. A noisy sample moves the crossing sideways. A steep edge hides noise better than a shallow one. A rule of thumb: the timing error is about the noise divided by the slope. The slope is the height divided by the rise time. With noise 0.03 and a rise of 8 ms, that is 0.03 × 8 = 0.24 ms. The simulation gives about 0.2 ms, the same size.
The audio file samples at 48,000 per second, so its sample period is 20.8 µs, about 190 times finer than the EEG grid. Find the click by taking the absolute value of the audio, smoothing it, and applying the same halfway rule. The audio-side error is tens of microseconds. The EEG side, at 0.2 ms or so, sets the limit for the whole alignment. That is why we spend our effort on the EEG edge.
c/* 50% crossing of the first rising edge in x[0..n), as a fractional sample index. */ float edge_time(const int16_t *x, int n, int16_t base, int16_t top) { float thr = 0.5f * (base + top); for (int i = 1; i < n; i++) { if (x[i - 1] < thr && x[i] >= thr) return (i - 1) + (thr - x[i - 1]) / (float)(x[i] - x[i - 1]); /* the formula above */ } return -1.0f; /* no edge found */ }
One rule matters more than any other: use the same rule on every event, in both files. If the audio rule marks the 50% point and the EEG rule marks the 20% point, the two differ by a fixed amount. That amount slides into the offset and is harmless. A rule that changes from event to event is not harmless. It adds noise you cannot remove.
On real hardware. Use a Nucleo-64 board with an ADC triggered by a timer at 250 Hz and a photodiode on one input. Fire a flash from a second board 200 times at random phases. Plot a histogram of the first-sample error and of the interpolated error. You should see a flat 4 ms spread for the first, and a narrow lump near zero for the second.
Chapter 3
Use cross-correlation to find how far apart two recordings sit, even when you cannot yet say which pulse is which
You have the marker pattern in the audio file. You have it in the EEG file. You do not yet know how far apart they sit. You could hunt for the first pulse by eye, but a noisy file makes that slow, and the next file will need a new hunt. A machine can do it by trying every shift.
Picture two strips of tracing paper. Each has the pattern drawn on it. Lay one over the other and slide it along. At each position, ask: how well do the marks line up? One position will make them line up far better than any other. That position is the answer.
Cross-correlation turns that question into a number. At a shift of l samples (the lag), multiply the two signals sample by sample, then add up the products. Where both signals are high at the same time, the products are large. Where one is high and the other is quiet, the products are small. So the sum is large when the pulses coincide.
Work a tiny case by hand. The template is x = [0, 1, 3, 1, 0]. The recording is y = [0, 0, 0, 1, 3, 1, 0, 0]. At lag 0 only one pair overlaps: 1 × 1 = 1. At lag 1 the products are 3 × 1 and 1 × 3, so c = 6. At lag 2 the template sits exactly on the bump: 1 × 1 + 3 × 3 + 1 × 1 = 11. At lag 3 the score falls back to 6, and at lag 4 to 1. The scores 1, 6, 11, 6, 1 form a hill. Its top is at lag 2, so the recording is the template delayed by two samples.
One fix makes the score fair. A loud passage produces a big sum for any shift, just from its volume. So divide by the length (the norm) of both pieces. The result is the normalized cross-correlation. It lies between −1 and 1, and it equals 1 when the shapes match exactly. Chapter 1 used this score already.
Blue is the EEG trigger channel. Warm is the audio click envelope, slid by your lag. The curve below scores every lag. Drag the lag to the top of the hill, or press Snap to peak.
A model on a 250 Hz grid: the coded pattern of Chapter 1 as Gaussian bumps 1.7 samples wide. The true lag is 2413.7 ms = 603.425 samples. The audio side has a little fixed noise; the EEG-side noise is your slider.
The sum needs one sample from each signal at each step, so both signals need the same sample rate. The audio runs at 48,000 samples per second and the EEG at 250. The audio click is short, so bring the audio down to 250 first: take the absolute value, smooth it (a low-pass filter lets slow changes through and blocks fast ones), and keep one sample in every 192, because 48,000 ÷ 250 = 192. The result is an envelope: a curve that rises where there is sound.
The peak lag is a whole number, so it sits on the 4 ms grid. The true lag is rarely a whole number. Here is the trick. Take the score at the peak and at its two neighbours, and fit a parabola (a smooth U shape) through the three points. The top of the parabola is the refined peak.
Take scores 8, 11 and 5 at lags l−1, l and l+1. The shift from the peak is ½ × (8 − 5) ÷ (8 − 2 × 11 + 5) = 1.5 ÷ (−9) = −0.17 samples. The left neighbour scored higher, so the true peak lies a bit to the left, by about 0.17 × 4 = 0.67 ms.
pythonimport numpy as np from scipy.signal import correlate, correlation_lags def lag_samples(a, e): """Lag in samples (fractional) at which e best matches a. Both on one 250 Hz grid.""" a = (a - a.mean()) / a.std() e = (e - e.mean()) / e.std() c = correlate(e, a, mode="full", method="fft") # FFT: fast for an hour of data lags = correlation_lags(len(e), len(a), mode="full") k = int(np.argmax(c)) y0, y1, y2 = c[k-1], c[k], c[k+1] return lags[k] + 0.5 * (y0 - y2) / (y0 - 2*y1 + y2) # parabola through the peak and its neighbours
The device shows the limit. With little noise the refined lag lands within a fraction of a millisecond of the truth. With much noise the correlation peak itself wanders, and the refinement wanders with it. In a test of this model, a single burst of five pulses gave an RMS error of 0.15 ms at noise 0.05, 0.7 ms at noise 0.3 and 1.4 ms at noise 0.6. That is not reliable enough for a 1 ms budget, and it is not meant to be.
So cross-correlation does a different job. It is robust: it uses the whole pattern at once, so it survives a noisy pulse and a missed one, and it tells you which pulse in the EEG file matches which click in the audio. Once the pulses are paired, Chapter 2's edge timing gives each event time to about 0.2 ms. The pair of steps, coarse then fine, is the standard plan.
There is one trap with doing the sliding over a whole hour. The skew stretches the EEG file by 133 ms by the end, so the pattern at the end no longer lines up where the pattern at the start did. A single hour-long correlation smears the peak. Correlate each burst separately, in a short window around where you expect it. Each burst gives its own lag, and the next chapter fits a line through those lags.
On real hardware. Record 10 seconds on an STM32 Nucleo board with a microphone on I2S or the ADC and a photodiode on a second ADC channel, both at the same rate. Fire the coded pattern, compute the lag with the code above, and compare it with the lag you get when you move the microphone 1 m away. A 1 m move should add about 2.9 ms of acoustic delay.
Chapter 4
Turn pairs of event times into one straight line, and learn where to place the events so the line is trustworthy
After Chapters 2 and 3 you hold a list. For each sync event you know when the audio file heard it and when the EEG file saw it. Thirteen events give thirteen pairs of times. Each pair says: at audio time t, the EEG file reads t plus a gap.
Plot the gap against the audio time. Chapter 0 promised a straight line, because a steady skew adds the same few microseconds every second. The line starts at the offset and climbs at the skew. You only need to find that line.
Every event has a little noise, so no line passes through all the points. Pick the line whose misses are smallest overall. The least squares line does that: it minimises the sum of the squared vertical misses. A squared miss punishes big errors more than small ones and has a tidy closed form.
Work three events by hand. The events sit at audio times 5, 1,805 and 3,605 s. The gaps are 2,413.9, 2,480.4 and 2,546.8 ms (example numbers). The averages are t̄ = 1,805 s and ḡ = 2,480.37 ms. The top sum is (−1,800)(−66.47) + 0 + (1,800)(66.43) = 239,220. The bottom sum is 1,8002 + 0 + 1,8002 = 6,480,000. So b = 0.036917 ms per second, a skew of 36.9 ppm. The offset is 2,480.37 − 0.036917 × 1,805 = 2,413.73 ms.
That fits the truth of 2,413.7 ms and 37 ppm. The same two lines of arithmetic run on 13 events or on 13,000. This is the "linear regression" that the LSL notes call usually sufficient offline.
One more habit saves confusion. The offset is the gap at audio time zero, a moment that may come before any event you fired, so it carries the slope’s uncertainty with it. For a number you can trust, also quote the gap at the middle of the session. The line pivots around the centre of its data, so that value is pinned down best.
The slope is the fragile number. A tiny slope error grows with distance: 1 ppm of skew error is 3.6 ms after an hour. How sure is the slope? Its uncertainty is the event noise divided by the square root of the spread S: σb = σ ÷ √S. A large spread in time shrinks it.
Now compare two plans with 5 events and 0.2 ms of noise. In plan A all five fire in the first minute. S is small, the slope is uncertain by about 4.2 ppm, and the line misses the one-hour mark by about 15 ms. In plan B the five events are spread across the hour. The slope is uncertain by 0.07 ppm, and the miss at one hour is about 0.15 ms. Same events, same noise, a hundred times better, only because they cover the hour.
The plot shows how wrong the fitted line is (yellow) against the truth (zero), with the band you should expect (purple). Choose where the events go and how many. Pink ticks mark the events.
A model: true offset 2413.7 ms, true skew +37 ppm, 0.2 ms of noise on each event, all seeded. The band is the one-sigma prediction error, sigma times the square root of (1/n + (t minus the mean time) squared over S). The yellow line is the actual error for this noise.
Two bursts, one at the start and one at the end, are as good as an even spread. That is the rule of thumb: fire markers at the very start and the very end of the session, plus a few in between so you can check the line is straight. A recording with markers only at the start can never prove its own end.
On real hardware. Use two Nucleo boards, one logging a photodiode at 250 Hz and one logging a microphone at 48 kHz, with a third board firing the marker pattern. Run for an hour. Fit the line from only the first minute, then from the whole hour. The two skews should differ by several ppm, and the late events show which one you can trust.
Chapter 5
Look at what the line could not explain, and learn to name each shape from its symptom, its measurement and its fix
You fitted a line and it printed an offset and a skew. Those two numbers look like an answer. They are not yet a proof. A line can be fitted to anything, even to events that do not follow a line. You need a way to ask the data: did the line really describe you?
The question has a plain form. After you apply the line, how far is each event from where the line says it should be? That distance is the residual of the event. If the line is right, the residuals are only noise: small, random, with no pattern. If the line is wrong, the leftover has a shape, and the shape tells you what is wrong.
Take five residuals: +0.1, −0.2, +0.3, −0.1 and −0.1 ms. Square each, average, and take the root: √((0.01 + 0.04 + 0.09 + 0.01 + 0.01) ÷ 5) = √0.032 = 0.18 ms. This is the RMS (root mean square) of the residuals. It is your measured precision.
What RMS should you expect from a good fit? The noise of one event is 0.2 ms (Chapter 2). The fit spends two numbers, the offset and the skew, to match the data, so the residuals come out slightly smaller than the noise. With 13 events the expected RMS is 0.2 × √(11 ÷ 13) = 0.18 ms. If you see about that, the line explains everything it can.
The RMS is only half the proof. The other half is a picture, because two plots can share one RMS and mean opposite things. Plot each residual against its event time. Then look for a shape.
Plot against time, not against event number. The events are not evenly spaced in time, and a shape that follows the clock, like a temperature swing, only looks like itself on the clock. Use milliseconds on the vertical axis, and a signed log scale if some residuals could be tens of milliseconds, so that both the big faults and the small noise stay visible.
Pick what the fit is allowed to do, then pick what went wrong in the data. The green band is plus or minus 1 ms. Yellow dots are residuals. The purple band is the noise you expect.
A model: 13 events, true skew 37 ppm, 0.2 ms noise. Wobble adds 1.2 ms with a 30 minute period (a temperature swing on one crystal). Step adds 6 ms to the last six events (a clock reset). Bad event adds 9 ms to event 6 (a stray click taken for a pulse). The verdict uses simple rules, not a statistical test.
A noise cloud. Dots scatter above and below zero with no order, and the RMS is near the expected 0.18 ms. This is the good case. Note that a least squares fit forces the residuals to average zero, so a zero mean proves nothing. The proof is the size and the lack of shape.
A ramp. Pick “Offset only” in the device. The residuals climb in a straight line from about −67 ms to +67 ms. Symptom: a smooth tilt. Measurement: the slope of the ramp is 37 ppm, the skew you left out. Fix: add the skew term.
A wave. With the skew included, choose “Wobble”. The residuals rise and fall in slow swings of about a millisecond. Neighbours share a sign. Symptom: a smooth curve instead of a cloud. Measurement: RMS of 0.8 ms against the expected 0.18, with runs of same-signed dots. Cause: a crystal runs at a rate that follows room temperature, so the skew is not constant. Fix: fit a line to short windows of events (the LSL notes call piecewise or moving-window mappings more accurate but slower).
A step. Choose “Step”. Early events sit below zero and late events above, with a jump between. Symptom: two plateaus. Measurement: the jump is 6 ms and lines up with one event time. Cause: a clock reset, a dropped batch, or a recorder restart. Fix: split the recording at the jump and fit each part. Chapter 6 shows how.
One bad dot. Choose “Bad event”. One residual is 8 ms out and the others are fine. Symptom: a lone outlier. Measurement: the biggest residual is many times the typical one. Cause: a mis-detected pulse, such as a door slam taken for a click. Fix: look at that event in both files, drop it with a written reason, and refit. Never drop it silently.
pythonimport numpy as np def residuals(t_audio, t_eeg): """Event times in seconds on each file's clock. Returns residuals (ms), offset (s), skew (ppm).""" t = np.asarray(t_audio) gap = np.asarray(t_eeg) - t # EEG time minus audio time b, a = np.polyfit(t, gap, 1) # slope first, then intercept r = (gap - (a + b * t)) * 1e3 return r, a, b * 1e6
On real hardware. Record one hour on a Nucleo board with markers every five minutes. Run the function above. Then warm one board with a hair dryer for ten minutes, mid-hour, and run it again. The warm session should show the wave from the device. If it does, you have measured your own crystal’s temperature response.
Chapter 6
See how a hole in the stream can quietly shift every later timestamp, and how segments and counters contain the damage
The EEG headset sends its samples over a wireless link to a laptop. Ten seconds in, the link stalls for a moment, then recovers. The laptop keeps writing samples to the file. Does the file know that a moment went missing?
It depends on how the timestamps were made. Two problems hide here. The first is jitter: samples arrive in small batches, so the laptop’s arrival clock reads 0, 0, 8, 8, 8, 16 instead of 0, 4, 8, 12, 16, 20 ms. The second is a hole: some samples never arrived, and the timeline has a gap.
The EEG converter takes its samples from a steady clock, one every 4 ms. So the tenth sample belongs at ten steps from the start, whatever the laptop thought. Dejittering uses that fact. It fits a straight line through arrival time against sample number, and replaces every timestamp with a point on the line.
Work four samples. Arrival times are 0, 4.5, 7.2 and 12.5 ms at sample numbers 0, 1, 2, 3. The mean arrival is 6.05 ms. The slope is ∑ idx × (arrival − mean) ÷ (n(n²−1)÷12) = (0 − 1.55 + 2.30 + 19.35) ÷ 5 = 4.02 ms per sample. The fitted times are 0.02, 4.04, 8.06 and 12.08 ms. Jitter of up to 0.8 ms has become 0.08 ms, and the slope came out at 4.02 ms, close to the true 4 ms.
The Lab Streaming Layer importers do this for regular streams: they split at interruptions, fit a line between sample index and timestamp for each part, and recompute the timestamps. In pyxdf the fit is closed form, exactly the slope formula above.
A fit by sample number assumes that no sample is missing. A hole breaks that assumption. Samples after the hole carry true times that are later, but their sample numbers follow on directly, so the line gives them earlier times than the truth.
The importer protects you by cutting the stream into segments at big gaps. In pyxdf, a gap between neighbouring timestamps is a break if it is longer than the larger of 1 second and 500 sample periods. At 250 samples per second, 500 periods are 2 seconds. So a stall longer than 2 s is cut into two segments, and each one is fitted alone. A stall of 1.5 s is not cut. It stays inside one line, and the line splits the difference.
A 250 Hz stream with a stall at 10 s. The plot shows each sample’s timestamp error after the importer is done (log scale). Choose the stall length, then try the stream flag.
A model: 5,000 samples at 250 Hz, a stall at 10 s that removes the chosen time from the recording, and 6 ms of arrival jitter (illustrative). The break rule and the can_drop_samples behaviour follow the pyxdf source: a break needs a gap above max(1 s, 500 sample periods), and a stream flagged can_drop_samples keeps its original timestamps.
Try 1.5 s. The samples before the stall come out late and those after come out early, by hundreds of milliseconds. The file says everything is smooth, and it is wrong by a large fraction of the stall. Now try 3 s. The break rule fires, two segments are fitted, and the error drops to a fraction of a millisecond. Switch on the flag. The importer then skips the line fit and keeps the raw arrival times. The error is the raw jitter, but nothing is moved by a hidden fit.
The best defence is to never let a hole go silent. Add a packet counter to every packet the device sends, a number that goes up by one each packet. The receiver then sees a missing number the moment it happens, and can write down how many samples were lost and where.
pythonimport numpy as np def lost_samples(counter, modulo=256): """counter: the device's wrapping packet counter, one value per packet, in arrival order.""" step = np.diff(counter.astype(int)) % modulo # 1 when nothing is missing, also across the wrap lost = step - 1 return int(lost.sum()), np.flatnonzero(lost) # how many, and after which packets
Two more checks cost nothing. First, count: a 10 minute recording at 250 Hz should hold 150,000 samples. A file with 148,500 lost 1,500 samples, 6 seconds, somewhere. Second, look at the effective rate. The pyxdf importer recomputes it from the fitted durations and logs a warning when it differs from the nominal rate by more than 10%.
Clocks can also jump, not only stall. The XDF clock offsets (Chapter 7) are measured every few seconds, and a reset shows as an offset that suddenly moves. The pyxdf importer, by default, flags a reset when an offset jumps more than 1 s from the median, and more than 10 robust standard deviations, and then fits a separate line to each side. A sync residual plot shows the same event as the “step” of Chapter 5.
On real hardware. Use an nRF52840 DK that streams 250 Hz packets with a counter over BLE. Walk out of range for three seconds and back. Compare the number of missing counter values with the gap you see in the arrival times. If the two disagree, the firmware is hiding a hole.
Chapter 7
Read the bytes of an XDF-style recording and see why it stores raw timestamps and clock offsets, not a corrected timeline
Months from now someone opens your session folder. There is audio.wav, eeg.csv and a text note that says “started about 2 s apart”. Which flash goes with which click? Which file was corrected, and by how much? The answers lived in your head, and your head is gone.
A good recording keeps its own answers. Every stream goes into one file. Every sample keeps the timestamp its own recorder gave it. And the clock measurements that tie the recorders together are written beside the data, so the alignment can be done again later with a better method.
This rule matters most. If the recorder overwrote timestamps with its best guess, a better guess next year would have nothing to work from. The Lab Streaming Layer follows the rule. Its recorder, LabRecorder, stores the raw timestamps and every clock offset measurement in the XDF file (Extensible Data Format). The importers fit a straight line through each stream’s offsets, assuming a constant drift, and map the timestamps to the recording computer’s clock. The raw file is never changed.
The format is small enough to read by hand. An XDF file starts with the four ASCII characters XDF:. After that comes a run of chunks, each one a labelled box of bytes. A chunk has three parts, and all numbers are little-endian (the low byte comes first).
| Tag | Chunk | What it holds |
|---|---|---|
| 1 | FileHeader | One per file. XML text with the format version. |
| 2 | StreamHeader | One per stream. A 4 byte stream ID, then XML: name, type, channel count, nominal rate, channel format. |
| 3 | Samples | A stream ID, a sample count, then the samples. Each sample starts with a byte (0 or 8) that says whether an 8 byte timestamp follows. |
| 4 | ClockOffset | A stream ID, the collection time (8 byte double, seconds), the offset value (8 byte double, seconds). |
| 5 | Boundary | A fixed 16 byte code. A reader that lost its place can search for it. The spec recommends one about every 10 seconds. |
| 6 | StreamFooter | One per stream. |
Work one chunk by hand. Take the Samples chunk of three EEG samples. The content holds the stream ID (4 bytes), the sample count (2 bytes: one for “1 byte follows”, one for the value 3), and three samples of 1 + 8 + 4 = 13 bytes each (a flag byte, a timestamp, a 32-bit float). That is 4 + 2 + 39 = 45 bytes. Add the 2 tag bytes and the length field reads 47. With the length header (2 bytes) and the tag, the chunk takes 49 bytes on disk.
Pick a chunk and read its bytes. The colours show the length, the tag, the stream ID, timestamps, values and text. Then change how many EEG samples the chunk holds and whether each sample carries a timestamp.
The layout follows the XDF 1.0 specification: magic code, chunk header, tags 1 to 5, little-endian numbers, optional timestamps. This is a hand-built toy file with one EEG channel and one marker stream, not a recording. Long chunks are shortened on screen.
Look at the toggle. With a timestamp on every sample, one EEG sample takes 13 bytes. With only the first timestamped, each later sample takes 5. The format allows both. A regular stream can drop the per-sample stamps and let the reader rebuild them from the sample count, which is the dejittering of Chapter 6. An irregular stream, such as markers, must keep them.
The flash and click events belong in the same file as the data. Record them as a stream of strings: a Markers stream with nominal rate 0, which the format uses for irregular sampling. Then one file holds the EEG, the audio, and the list of sync events as every recorder saw them. The ClockOffset chunks hold the online sync layer’s own measurements. The sync events then play a new role. They are an independent check of how good that online correction was.
Your alignment result belongs next to the file, not in it. Write the offset, the skew, the residual RMS and the list of dropped events to a small report file, and leave the raw XDF as recorded. Any later reader can then repeat your steps and compare.
pythonimport pyxdf streams, header = pyxdf.load_xdf("session.xdf") # clock sync and dejitter are on by default by_name = {s["info"]["name"][0]: s for s in streams} eeg, marks = by_name["EEG"], by_name["Markers"] t_eeg = eeg["time_stamps"] # seconds, mapped by the importer to the recording computer's clock trig = eeg["time_series"][:, 0] # the trigger channel: run Chapter 2's edge timing on this events = marks["time_stamps"] # the marker stream's own timestamps
On real hardware. Install LabRecorder and a Lab Streaming Layer outlet on an nRF52840 DK or a laptop that sends a 250 Hz test signal and a marker every few seconds. Record one XDF file, open it in a hex viewer, and find the XDF: magic, the first tag-2 chunk, and the first ClockOffset chunk. Check that their bytes match what the device above shows.
Chapter 8
Test the alignment on events it never saw, set the budget in advance, and write the one page that lets a stranger trust the result
Imagine a teacher who grades a student on the very problems the student copied from the answer key. The score is perfect and means nothing. A fitted line has the same weakness. It was chosen to pass close to the events you gave it, so small residuals on those events are no surprise. The honest test uses events the line has never seen.
So hold some events back. Fit the line on most of them. Then use the line to predict where the held-out events should be, and measure how far off it is. These are the held-out errors. They are the real size of your uncertainty, because they were never part of the fit.
Take only the first three events of the hour, at 5, 305 and 605 s. The line passes through them almost exactly, and the residuals are tiny. But those three events are packed into the first ten minutes. By Chapter 4, the slope is uncertain by about 0.5 ppm, so the line is typically wrong by about 1.4 ms at the 55 minute mark and 1.6 ms at the hour. The residual plot looked perfect. The held-out events, late in the hour, would have shown the error.
Set the budget before you look. The budget is the largest timing error your science can tolerate. If you compare brain responses that differ by 20 ms, a budget of 1 ms is generous. If you study responses that differ by 2 ms, it is not. Choose it from the question, not from the result, or you will be tempted to move it to fit the data.
Which events should you hold out? Hold out the ones that make the line work hardest: the latest ones, and one or two from the middle. Error is smallest near the centre of your fitted events and largest beyond their ends. A held-out event near the end of the hour is a hard test. A held-out event in the middle of the fitted ones is an easy test that proves little.
Pick which events the line may use. Pink rings are the three held-out events at 50, 55 and 60 minutes. Yellow dots are the fitted events. Set a budget and read the report.
A model: 13 events at 5, 305, … 3605 s, true offset 2413.7 ms, true skew +37 ppm, 0.2 ms noise, all seeded. Events 11, 12 and 13 (3005, 3305 and 3605 s) are always held out. The wobble is 1.2 ms with a 30 minute period. The budget is yours to set.
A fail is information, so read it like a residual plot. If the held-out errors all lean the same way and grow toward the end of the hour, the slope is uncertain: fire markers nearer the end next time, and for this session try the windowed fit of Chapter 5. If they scatter at random, the event noise is the limit: time the edges more carefully or add more events. If one jumps, look for a step or a bad event.
Once the check passes, fit the line again on all the events for the final numbers. The held-out test judged the method. The last fit uses every piece of evidence. Report both: the held-out error that shows how far to trust the method, and the final offset and skew.
Now every step of the lesson sits in one line of work. Read it as the checklist for a real session.
pythonimport numpy as np def sign_off(t_audio, t_eeg, held, budget_ms=1.0): """Event times in seconds on each clock. `held` = indices kept out of the fit.""" t_audio, t_eeg, held = np.asarray(t_audio), np.asarray(t_eeg), np.asarray(held) keep = np.setdiff1d(np.arange(len(t_audio)), held) gap = t_eeg - t_audio b, a = np.polyfit(t_audio[keep], gap[keep], 1) r_fit = (gap[keep] - (a + b * t_audio[keep])) * 1e3 r_held = (gap[held] - (a + b * t_audio[held])) * 1e3 worst = max(np.abs(r_fit).max(), np.abs(r_held).max()) return {"offset_ms": round(float(a * 1e3), 2), "skew_ppm": round(float(b * 1e6), 2), "n_fit": int(len(keep)), "rms_ms": round(float(np.sqrt((r_fit ** 2).mean())), 2), "max_fit_ms": round(float(np.abs(r_fit).max()), 2), "n_held": int(len(held)), "max_held_ms": round(float(np.abs(r_held).max()), 2), "budget_ms": budget_ms, "passed": bool(worst <= budget_ms)}
A good report also lists what the numbers cannot show: events dropped and why, packets lost and where, the software versions, and the file names. A reader who sees only “PASS” learns nothing. A reader who sees the budget, the held-out error and the dropped events can decide for themselves.
On real hardware. Record a 30 minute session on a Nucleo board with the coded pattern fired at 0, 15 and 30 minutes. Hold out the middle burst. Fit on the first and last, predict the middle, and compare. The prediction error is the number to quote. If it exceeds your budget, the wave of Chapter 5 is the first thing to look for.
Chapter 9
Keep the numbers, the checklist and the core code in one place, then follow the links to the lessons that come next
You can now take two recordings with separate clocks and show how well they line up. In one sentence: fire a distinct marker pattern that both recorders see, time each edge between the samples, fit offset and skew by least squares, read the residual plot, test on held-out events, and write the result beside a raw XDF file.
| What | Number | Why it matters |
|---|---|---|
| EEG sample period at 250 SPS | 4 ms (the ADS1299 runs 250 SPS to 16 kSPS) | Sets the grid your event times must beat |
| Audio sample period at 48 kHz | 20.8 µs, 192 samples per EEG sample | The EEG side limits the alignment |
| One ppm of skew | 1 µs per second = 3.6 ms per hour | Converts any skew to drift |
| 37 ppm over one hour | 133.2 ms, about 33 EEG samples | Why a start-only sync fails |
| Sound in air at 20 °C | about 343 m/s = 2.9 ms per metre | Why the click should be electrical |
| Edge timing, 4 ms grid (this lesson’s model) | first-sample rule 2.3 ms RMS; interpolation 0.2 ms | Interpolate, with the same rule everywhere |
| Parabolic peak shift | ½(c−1 − c+1) ÷ (c−1 − 2c0 + c+1) | A lag finer than one sample |
| Slope uncertainty | σb = σ ÷ √S; 5 events: 4.2 ppm bunched, 0.07 ppm spread | Fire markers at the start and the end |
| Expected residual RMS | σ √((n − 2) ÷ n) = 0.18 ms for n = 13, σ = 0.2 ms | What a clean fit looks like |
| pyxdf segment break | gap above max(1 s, 500 periods) = 2 s at 250 Hz | Smaller stalls hide inside one fit |
| pyxdf clock reset defaults | offset jump above 1 s and 10 standardized units | Where the offset line is split |
| XDF file | magic XDF:, tags 1 to 6, 16 byte Boundary code about every 10 s | Raw stamps and offsets stay in the file |
Rows marked “model” or with a 0.2 ms noise come from the toy models on this page. The rest come from the sources listed below.
pythonimport numpy as np def edge_times(x, fs, base, top): """Fractional 50% rising crossings of a trigger channel, in seconds on the recorder's clock.""" thr = 0.5 * (base + top) i = np.flatnonzero((x[:-1] < thr) & (x[1:] >= thr)) return (i + (thr - x[i]) / (x[i + 1] - x[i])) / fs # Chapter 2 # t_audio, t_eeg = paired edge times (Chapter 3 pairs them), then: # r, offset_s, skew_ppm = residuals(t_audio, t_eeg) # Chapter 5 # report = sign_off(t_audio, t_eeg, held=[10, 11, 12]) # Chapter 8
This lesson is the last step of the multi-sensor time sync track. fw-sync-01 explains crystals and drift, fw-sync-02 stamps events in hardware, and fw-sync-03 builds the live sync layer. For the EEG side see the analog front end, filtering neural signals and real-time closed loop, and streaming EEG reliably for counters and retransmits. The line fit has a recursive cousin in the Kalman filter. The same timing questions appear in robot sensor and actuator integration, and the sound-delay idea returns in microphone arrays. A lesson on sampling itself is discrete signals.
pyxdf.py): default parameters, the robust clock fit, the dejitter fit, the break rule.No course slides were used. The recorders, noise, edges and fault patterns on this page are our own models, with numbers labelled illustrative. Speed of sound is the standard 343 m/s at 20 °C. The board code is a sketch for an STM32 Nucleo board and was not run on hardware here.
Now press Present or Teach and explain from memory how a flash and a click let you align two files and prove it. Then go back to the clocks at the top, drag the offset to 2,413.7 ms and the skew to 37 ppm, and say why Auto-align lands the yellow dots inside the green band.