How the LHDC V5 decoder works
A 5 ms LHDC V5 frame carries two independently coded channels. Here is every stage that turns those bytes back into PCM, in the order the decoder runs them, with the real code beside each one.
Code shown from LHDC-V5-Decoder@cf857ce. Every excerpt links to its exact lines.
1 · Descramble the channel header
Each channel opens with an 8-byte header that is scrambled on the wire. The decoder undoes it in place with a fixed XOR mask and byte permutation, separately for each channel, before it can read any field. The two selector variants exist because the permutation depends on a header bit.
decoder/lhdc_dec.c:245–262 ↗static void lhdc_descramble_inplace_sel(uint8_t *buf, size_t avail, int sel)
{
if (avail < 9) return;
uint8_t tmp[8];
sel &= 1;
const uint8_t *perm = LHDC_PERM[sel];
for (int i = 0; i < 8; i++) tmp[perm[i]] = buf[i];
for (int k = 0; k < 8; k++) buf[k] = tmp[k] ^ LHDC_XOR_MASK[k];
}
static void lhdc_descramble_inplace(uint8_t *buf, size_t avail)
{
if (avail < 9) return;
lhdc_descramble_inplace_sel(buf, avail, buf[8] & 1);
}
__attribute__((unused))
static void lhdc_descramble(const uint8_t *in, uint8_t *out, size_t len)2 · Read the SNS side information
SNS (spectral noise shaping) describes the rough loudness of each frequency band. A 4-bit mode plus one direction bit per band rebuild per-band scale factors by DPCM: each band is coded as a step up or down from the previous one, which costs very few bits.
decoder/lhdc_sns_synth.c:286–315 ↗lhdc_dec_ret_t lhdc_sns_decode_params(lhdc_dec_bit_reader_t *br,
lhdc_dec_sns_params_t *params,
int num_sfb)
{
if (num_sfb < 1 || num_sfb > LHDC_DEC_MAX_SFB) {
return LHDC_DEC_BITSTREAM_ERROR;
}
int sns_mode = (int)lhdc_bit_reader_read(br, 4) + 8;
uint8_t side_bits[LHDC_DEC_MAX_SFB];
for (int i = 0; i < num_sfb - 1; i++) {
side_bits[i] = (uint8_t)lhdc_bit_reader_read(br, 1);
}
/*
* sns_mode == 23 (the 4-bit field = 15) is the encoder's FLAT-SNS escape
* (sns_encode @0xd5ad8): when a channel's energy is low/flat it zeroes the
* side bits, sets mode 23 and SKIPS adsq, so the transmitted envelope is
* flat. The decoder must use sf = 0 (gain 1, no whitening) — running adsq
* here would synthesize a bogus envelope (audible crackle / wrong band).
*/
if (sns_mode == 23) {
memset(params->scale_factors, 0, sizeof(params->scale_factors));
memset(params->noise_level, 0, sizeof(params->noise_level));
params->num_sfb = (uint8_t)num_sfb;
params->sns_mode = (int32_t)sns_mode;
return LHDC_DEC_OK;
}
3 · FAC range decoding
The spectrum itself is two ternary symbol streams (an LSB/marker plane and Rice quotient codes) packed into one range-coded byte stream. Each symbol is decoded against a sliding-window adaptive model, so probabilities follow the music. The inner loop avoids integer division so it stays fast on the ESP32.
decoder/lhdc_tables.c:777–806 ↗int lhdc_fac_dec_read(lhdc_fac_dec_t *fac, lhdc_dec_bit_reader_t *br)
{
uint32_t range = fac->range;
uint32_t low = fac->low;
uint32_t total = fac->total_count;
if (total == 0) return -1;
if (range < 0x1000000) {
low = (low << 8) | lhdc_bit_reader_read(br, 8);
range <<= 8;
}
uint32_t target = (low >> 24) & 0xFF;
uint32_t cum = 0;
int symbol = 0;
for (int i = 0; i < fac->num_symbols; i++) {
cum += fac->sym_count[i];
if (target < (cum * 256) / total) { symbol = i; break; }
}
uint32_t sym_low = 0;
for (int i = 0; i < symbol; i++) sym_low += fac->sym_count[i];
low = low + range * sym_low / total;
range = range * fac->sym_count[symbol] / total;
fac->range = range;
fac->low = low;
fac->sym_count[symbol]++;
fac->total_count++;
4 · Rebuild magnitudes from the mantissa plane
Rice quotients only give the coarse size of each coefficient. A causal bit-plane pass predicts a shift per coefficient from its neighbours and reads the remaining mantissa bits, plus a sign bit for every non-zero value.
decoder/lhdc_dec.c:617–646 ↗static LHDC_HOT int64_t lhdc_dec_mant_plane(const int32_t *coeff, int32_t *out, int cnt,
const uint8_t *pl, int total_bits,
int start_bit, int pred_mode, int init_shift)
{
int p = start_bit;
/* The mantissa shift predictor is seeded by the transmitted initial shift
* (the 4-bit "resid" field), NOT 0. shift[0] = (pred+0x40)>>7, and the
* first iteration leaves pred unchanged ((a+b)*pred>>3 == pred), so seeding
* pred = init_shift<<7 yields shift[0] = init_shift = calc_bits(|M[0]|).
* Without this, dense frames whose first coeff has a large magnitude (and a
* zero Rice quotient) lose all mantissa bits -> spectrum desync/garble. */
int pred = init_shift << 7;
int64_t peak = 0;
for (int k = 0; k < cnt; k++) {
int s = (pred + 0x40) >> 7;
/* Read s mantissa bits MSB-first. The ARM-style per-bit loop did s byte
* loads + shifts; on Xtensa we batch them into ONE shifted 4-byte load
* when the 4 bytes are in-bounds (the common mid-buffer case): the field
* is w bits (31-off)..(32-off-s), so (w<<off)>>(32-s) right-aligns it.
* Guard (byte+4)*8<=total_bits ensures all 32 bits are valid (no
* zero-fill) and s<=24 keeps off+s<=31. Bit-identical to the loop
* (verified 2,000,000 random cases). Boundary/large-s -> per-bit fallback. */
int mant;
{
int byte = p >> 3, off = p & 7;
if (s == 0) {
mant = 0;
} else if (s <= 24 && ((byte + 4) << 3) <= total_bits) {
uint32_t w = ((uint32_t)pl[byte] << 24) | ((uint32_t)pl[byte + 1] << 16) |
((uint32_t)pl[byte + 2] << 8) | (uint32_t)pl[byte + 3];5 · Inverse quantization
Integer coefficients become real spectrum values: coeff × 2^gain_exponent, using the frame’s global gain step. The exponent is fractional, which is why the code calls exp2f rather than ldexpf: truncating it would shift the level.
/*
* Inverse quantization (PROJECT_CONTEXT §11): linear dequant by the global gain
* step. spectrum[k] = q[k] * 2^e(gain_idx). The SNS per-band shaping is undone
* separately in lhdc_sns_synth_apply.
*/
static LHDC_HOT void lhdc_dec_inverse_quantize(int32_t *quant, float *spectrum,
int num_coeffs,
const lhdc_dec_sns_params_t *sns,
int enc_frame_len, int bit_depth,
uint32_t sample_rate)
{
/* step = 2^e with FRACTIONAL e -> exp2f (single precision), NOT ldexpf
* (which would truncate the fractional exponent and shift the level). */
float step = exp2f(lhdc_dec_gain_exponent(
sns->global_gain, enc_frame_len, bit_depth, sample_rate));
for (int k = 0; k < num_coeffs; k++) {
spectrum[k] = (float)quant[k] * step;
}
}
6 · SNS synthesis
Now the per-band scale factors from step 2 are applied, undoing the spectral shaping the encoder did so that quantization noise sits where the ear is least sensitive.
decoder/lhdc_sns_synth.c:246–275 ↗LHDC_HOT void lhdc_sns_synth_apply(float *spectrum,
const lhdc_dec_sns_params_t *params,
int mdct_size,
const uint16_t *band_off,
const uint16_t *band_scale,
int num_sfb)
{
(void)band_scale;
#if defined(LHDC_SNS_BYPASS)
(void)params; (void)band_off; (void)num_sfb; (void)mdct_size; (void)spectrum;
return; /* calibration: leave spectrum untouched to isolate dequant/IMDCT scale */
#else
int sns_dir = g_lhdc_diag_sns_mode; /* 0=divide, 1=multiply, 2=bypass */
#if defined(LHDC_HOST_BUILD)
{ const char *e = getenv("LHDC_SNS"); if (e) sns_dir = atoi(e); }
#endif
if (sns_dir == 2) return;
for (int sfb = 0; sfb < num_sfb; sfb++) {
int start = band_off[sfb];
int end = (sfb + 1 < num_sfb) ? band_off[sfb + 1] : mdct_size;
if (end > mdct_size) end = mdct_size;
int32_t sf = params->scale_factors[sfb];
float g;
#if defined(LHDC_GAIN_NEG)
g = powf(2.0f, -(float)sf / 16.0f);
#elif defined(LHDC_GAIN_POS)
g = powf(2.0f, (float)sf / 16.0f);
#else
if (sns_dir == 1) { g = sns_band_gain(sf); } /* multiply */
else { g = sns_band_gain_recip(sf); } /* divide-POW2, no __divsf3 */7 · Fast low-delay IMDCT
The spectrum goes back to the time domain. Rather than an O(N²) transform, the IMDCT runs as an N/4-point complex FFT with pre/post twiddles: a radix-2 stage followed by a 15-point DFT built as 3×5 Cooley–Tukey. At init a self-test checks the fast path against a direct cosine reference and falls back if it fails.
decoder/lhdc_imdct.c:371–406 ↗static LHDC_HOT void lhdc_imdct_fast_480(const float *in, float *out)
{
float zr[IMDCT_P], zi[IMDCT_P];
float Xr[IMDCT_P], Xi[IMDCT_P];
float reZ[IMDCT_P], imZ[IMDCT_P];
const float invM = 1.0f / (float)IMDCT_M;
/* Pre-twiddle: z[k] = (in[2k] + i*in[239-2k]) * ROT[k]. */
for (int k = 0; k < IMDCT_P; k++) {
float r0 = in[2 * k];
float i0 = in[IMDCT_M - 1 - 2 * k];
float rr = s_rot_r[k], ri = s_rot_i[k];
zr[k] = r0 * rr - i0 * ri;
zi[k] = r0 * ri + i0 * rr;
}
lhdc_fft120(zr, zi, Xr, Xi);
/* Post-twiddle + scale by 1/M. */
for (int k = 0; k < IMDCT_P; k++) {
float rr = s_rot_r[k], ri = s_rot_i[k];
reZ[k] = (Xr[k] * rr - Xi[k] * ri) * invM;
imZ[k] = (Xr[k] * ri + Xi[k] * rr) * invM;
}
/* Symmetric unfold, P=120, M=240 (validated convention). Split into three branch-free
* segments: the old single loop re-evaluated two 3-way range tests on every
* one of the 240 iterations, and the ranges are compile-time constants. */
for (int p = 0; p < 60; p++) {
out[2 * p] = reZ[60 + p];
out[2 * p + 1] = -imZ[59 - p];
}
for (int p = 60; p < 180; p++) {
out[2 * p] = imZ[p - 60];
out[2 * p + 1] = -reZ[179 - p];
}8 · Windowed overlap-add
Each IMDCT output is windowed and added to the tail of the previous frame (50% TDAC overlap), which cancels the time-domain aliasing and gives continuous audio. The two channels are then interleaved into stereo PCM.
decoder/lhdc_dec.c:498–531 ↗static LHDC_HOT void lhdc_dec_overlap_add(lhdc_decoder_t *dec, float *pcm_out,
int channel, int mdct_size)
{
int overlap = mdct_size / 2;
/* Only the generic path needs the full window; fetching it here would run
* lhdc_dec_get_window()'s lookup every frame for nothing on the fast path. */
const float *window = (s_win.ramp && s_win.n == mdct_size)
? NULL : lhdc_dec_get_window(mdct_size);
float *overlap_buf = dec->overlap_buf[channel]; /* per-channel: no slot needed */
float *mdct_out = dec->slot[LHDC_DEC_SLOT()].mdct_out;
/* Windowing is fused into the two halves instead of being a separate pass
* over all `mdct_size` samples. The old shape read+scaled+stored the whole
* IMDCT output (1920 loads + 1920 stores at 192k) and then read it back
* again; folding window[] into each consumer removes that entire round trip
* and lets the first half become a single fused multiply-add. Identical
* arithmetic: each output is still mdct_out[n]*window[n] (+ overlap_buf[n]).
*
* Note mdct_out[] is no longer left windowed in place -- nothing downstream
* reads it (the caller consumes pcm_out, and the next frame overwrites
* mdct_out from the IMDCT). */
/* Structured fast path: skip the 63% of the window that is exactly 0 or 1
* (see lhdc_dec_window_prepare). Same arithmetic, but multiplies happen
* only across the ramp, and the ramp is in DRAM so this touches no flash.
* s_win.ramp == NULL (unrecognized window / out of memory) -> generic loop
* below, which is what always ran before. */
if (s_win.ramp && s_win.n == mdct_size) {
const float *const ramp = s_win.ramp;
const int z = s_win.z, t = s_win.t;
/* --- first half: pcm_out[n] = mdct_out[n]*w[n] + overlap_buf[n] --- */
/* w = 0 on [0,z): the IMDCT contributes nothing, emit the tail as-is. */
memcpy(pcm_out, overlap_buf, sizeof(float) * (size_t)z);