mic_ wrote:
Unless I'm missing something, that doc describes how to decode BRR samples to raw PCM. I want want to do the opposite; encode raw PCM to BRR.
To understand my explanation, first look up IMA ADPCM and how it's encoded and decoded. Encoding BRR or VAG is rawther similar.
In BRR, each sample y is the sum of a prediction p and a residue r. The prediction is a linear function of the two previous samples.
y[t] = p[t] + r[t]
filter 0: p[t] = y[n - 1] * 0/64 - y[n - 2] * 0/16
filter 1: p[t] = y[n - 1] * 60/64 - y[n - 2] * 0/16
filter 2: p[t] = y[n - 1] * 122/64 - y[n - 2] * 15/16
filter 3: p[t] = y[n - 1] * 115/64 - y[n - 2] * 13/16
I added multiplications by 0 to make parallels among the filters more obvious.
For each block of 16 samples, you need to first find the appropriate filter and range and then encode the block. To find the best filter and range:
- Compute r[t] = y[t] - p[t] for all four filters.
- Compute the peak residue for each filter, as max(abs(r[t])).
- Find the filter with the smallest peak residue.
- Set the range to the smallest value that doesn't cause slope overload when encoding the peak residue with this filter.
Then for each sample in the block:
- Compute p[t] based on the filter, y[n - 1], and y[n - 2].
- Compute the residue r[t] = y[t] - p[t].
- Quantize the residue based on the range, and output this scaled residue: rscaled[t] = r[t] >> range.
- Recompute y[t] based on the scaled residue: y[t] = p[t] + (rscaled[t] << range).