-
-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathMs.java
More file actions
447 lines (400 loc) · 15.8 KB
/
Ms.java
File metadata and controls
447 lines (400 loc) · 15.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
/*
* Copyright (C) 1999 Stanley J. Brooks <stabro@megsinet.net>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package vavi.sound.adpcm.ms;
import java.lang.System.Logger;
import java.lang.System.Logger.Level;
import static java.lang.System.getLogger;
/**
* Codec for MS_ADPCM data.
* <p>
* (hopefully) provides interoperability with
* Microsoft's ADPCM format, but, as usual,
* see LACK-OF-WARRANTY information below.
* </p>
* <p>
* November 22, 1999<br>
* specs I've seen are unclear about ADPCM supporting more than 2 channels,
* but these routines support more channels in a manner which looks (IMHO)
* like the most natural extension.
* </p>
* <p>
* Remark: code still turbulent, encoding very new.
* </p>
* @author <a href="mailto:stabro@megsinet.net">Stanley J. Brooks</a>
* @author <a href="mailto:umjammer@gmail.com">Naohide Sano</a> (nsano)
* @version 0.00 030715 nsano port to java <br>
* @see "https://chromium.googlesource.com/vcbox/third_party/libsox/+/refs/heads/master/src/src/adpcm.c"
*/
class Ms {
private static final Logger logger = getLogger(Ms.class.getName());
/** */
private static class State {
/** step size */
int step;
final int[] iCoef = new int[2];
}
/**
* Lookup tables for MS ADPCM format.
* <p>
* these are step-size adjust factors, where
* 1.0 is scaled to 0x100
* </p>
*/
private static final int[] stepAdjustTable = {
230, 230, 230, 230, 307, 409, 512, 614,
768, 614, 512, 409, 307, 230, 230, 230
};
/**
* TODO The first 7 iCoef sets are always hardcoded and must
* appear in the actual WAVE file. They should be read in
* in case a sound program added extras to the list.
*/
static final int[][] _iCoef = {
{ 256, 0 },
{ 512, -256 },
{ 0, 0 },
{ 192, 64 },
{ 240, 0 },
{ 460, -208 },
{ 392, -232 }
};
/**
* @param sp state pointer
*/
private static int decode(int code,
State[] state,
int sp,
int sample1,
int sample2) {
// Compute next step value
int step = state[sp].step;
int nstep = (stepAdjustTable[code] * step) >> 8;
state[sp].step = Math.max(nstep, 16);
// make linear prediction for next sample
int vlin = ((sample1 * state[sp].iCoef[0]) +
(sample2 * state[sp].iCoef[1])) >> 8;
//logger.log(Level.TRACE, vlin);
// then add the code * step adjustment
code -= (code & 0x08) << 1;
int sample = (code * step) + vlin;
if (sample > 0x7fff) {
sample = 0x7fff;
} else if (sample < -0x8000) {
sample = -0x8000;
}
return sample;
}
/**
* Outputs interleaved samples into one output buffer.
* @param channels total channels
* @param nCoef
* @param iCoef
* @param inBuffer input buffer[blockAlign]
* @param outBuffer output samples, length * channels
* @param length samples to decode per channel
*/
public void decodeBlock(int channels,
int nCoef,
int[][] iCoef,
byte[] inBuffer,
int[] outBuffer,
int length) {
// One decompressor state for each channel
State[] state = new State[channels];
// Read the four-byte header for each channel
int ip = 0;
for (int channel = 0; channel < channels; channel++) {
int bpred = inBuffer[ip++] & 0xff;
if (bpred >= nCoef) {
logger.log(Level.DEBUG, "MSADPCM bpred >= nCoef, arbitrarily using 0");
bpred = 0;
}
state[channel] = new State();
state[channel].iCoef[0] = iCoef[bpred][0];
state[channel].iCoef[1] = iCoef[bpred][1];
}
for (int channel = 0; channel < channels; channel++) {
int value = (inBuffer[ip] & 0xff) + ((inBuffer[ip + 1] & 0xff) << 8);
if ((value & 0x8000) != 0) {
value -= 0x10000;
}
//logger.log(Level.TRACE, "1: " + value);
state[channel].step = value;
ip += 2;
}
// sample1's directly into obuff
for (int channel = 0; channel < channels; channel++) {
int value = (inBuffer[ip] & 0xff) + ((inBuffer[ip + 1] & 0xff) << 8);
if ((value & 0x8000) != 0) {
value -= 0x10000;
}
//logger.log(Level.TRACE, "2: " + value);
outBuffer[channels + channel] = value;
ip += 2;
}
// sample2's directly into obuff
for (int channel = 0; channel < channels; channel++) {
int value = (inBuffer[ip] & 0xff) + ((inBuffer[ip + 1] & 0xff) << 8);
if ((value & 0x8000) != 0) {
value -= 0x10000;
}
//logger.log(Level.TRACE, "3: " + value);
outBuffer[channel] = value;
ip += 2;
}
// already have 1st 2 samples from block-header
int op = 2 * channels;
int top = length * channels;
int channel = 0;
while (op < top) {
int b = inBuffer[ip++] & 0xff;
int tmp = op;
outBuffer[op++] = decode((b & 0xf0) >> 4, state, channel, outBuffer[tmp - channels], outBuffer[tmp - 2 * channels]);
if (++channel == channels) {
channel = 0;
}
tmp = op;
outBuffer[op++] = decode(b & 0x0f, state, channel, outBuffer[tmp - channels], outBuffer[tmp - 2 * channels]);
if (++channel == channels) {
channel = 0;
}
}
}
/**
* Encode.
* @param channel channel number to encode, REQUIRE 0 <= ch < chans
* @param channels total channels
* @param v values to use as starting 2
* @param iCoef lin predictor coeffs
* @param inBuffer interleaved input samples
* @param length samples to encode PER channel
* @param steps input/output step, REQUIRE 16 <= *st <= 0x7fff
* @param sp steps pointer
* @param outBuffer output buffer[blockAlign], or NULL for no output
* @return ???
*/
private static int encode(int channel,
int channels,
int[] v,
int[] iCoef,
int[] inBuffer,
int length,
int[] steps,
int sp,
byte[] outBuffer) {
int ox = 0; //
int ip = channel; // point ip to 1st input sample for this channel
int itop = length * channels;
int v0 = v[0];
int v1 = v[1];
int d = inBuffer[ip] - v1;
ip += channels; // 1st input sample for this channel
// long long is okay also, speed abt the same
// d2 will be sum of squares of errors, given input v0 and *st
double d2 = d * d;
d = inBuffer[ip] - v0;
ip += channels; // 2nd input sample for this channel
d2 += d * d;
int step = steps[sp];
int op = 0; // output pointer (or null)
// null means don't output, just compute the rms error
if (outBuffer != null) {
op += channels; // skip bpred indices
op += 2 * channel; // channel's stepsize
outBuffer[op] = (byte) step;
outBuffer[op + 1] = (byte) (step >> 8);
op += 2 * channels; // skip to v0
outBuffer[op] = (byte) v0;
outBuffer[op + 1] = (byte) (v0 >> 8);
op += 2 * channels; // skip to v1
outBuffer[op] = (byte) v1;
outBuffer[op + 1] = (byte) (v1 >> 8);
op = 7 * channels; // point to base of output nibbles
ox = 4 * channel;
}
for (; ip < itop; ip += channels) {
// make linear prediction for next sample
int vlin = (v0 * iCoef[0] + v1 * iCoef[1]) >> 8;
// difference between linear prediction and current sample
d = inBuffer[ip] - vlin;
int dp = d + (step << 3) + (step >> 1);
//logger.log(Level.TRACE, "vlin: " + vlin + ", d: " + d + ", dp: " + dp + ", in: " + inBuffer[ip] + ", coef: " + iCoef[0] + ", " + iCoef[1]);
int c = 0;
if (dp > 0) {
c = dp / step;
if (c > 15) {
c = 15;
}
}
c -= 8;
dp = c * step; // quantized estimate of samp - vlin
c &= 0x0f; // mask to 4 bits
v1 = v0; // shift history
v0 = vlin + dp;
if (v0 < -0x8000) {
v0 = -0x8000;
} else if (v0 > 0x7fff) {
v0 = 0x7fff;
}
d = inBuffer[ip] - v0;
d2 += d * d; // update square-error
if (outBuffer != null) { // if we want output, put it in proper place
// FIXME does c << 0 work properly ?
outBuffer[op + (ox >> 3)] |= (byte) ((ox & 4) != 0 ? c : (c << 4));
ox += 4 * channels;
//logger.log(Level.TRACE, "%1x".formatted(c));
}
// Update the step for the next sample
step = (stepAdjustTable[c] * step) >> 8;
if (step < 16) {
step = 16;
}
}
//if (outBuffer != null)
// logger.log(Level.DEBUG, "");
d2 /= length; // be sure it's non-negative
//logger.log(Level.TRACE, "ch%d: st %d->%d, d %.1f".formatted(channel, steps[sp], step, Math.sqrt(d2)));
steps[sp] = step;
return (int) Math.sqrt(d2);
}
/**
* Encodes a channel.
*
* @param channel channel number to encode, REQUIRE 0 <= ch < chans
* @param channels total channels
* @param inBuffer interleaved input samples
* @param length samples to encode per channel, REQUIRE
* @param steps input/output steps, 16<=st[i]
* @param sp steps pointer
* @param outBuffer output buffer[blockAlign]
*/
private static void encodeChannel(int channel,
int channels,
int[] inBuffer,
int length,
int[] steps,
int sp,
byte[] outBuffer) {
int[] v = new int[2];
int[] ss = new int[1];
int[] s1 = new int[1];
int n0 = length / 2;
if (n0 > 32) {
n0 = 32;
}
if (steps[sp] < 16) {
steps[sp] = 16;
}
v[1] = inBuffer[channel];
v[0] = inBuffer[channel + channels];
int dmin = 0;
int kmin = 0;
int smin = 0;
// for each of 7 standard coeff sets, we try compression
// beginning with last step-value, and with slightly
// forward-adjusted step-value, taking best of the 14
for (int k = 0; k < 7; k++) {
ss[0] = steps[sp];
int s0 = ss[0];
// with step s0
int d0 = encode(channel, channels, v, _iCoef[k], inBuffer, length, ss, 0, null);
s1[0] = s0;
encode(channel, channels, v, _iCoef[k], inBuffer, n0, s1, 0, null);
//logger.log(Level.TRACE, " s32 %d".formatted(s1[0]));
ss[0] = (3 * s0 + s1[0]) / 4;
s1[0] = ss[0];
// with step s1
int d1 = encode(channel, channels, v, _iCoef[k], inBuffer, length, ss, 0, null);
if (k == 0 || d0 < dmin || d1 < dmin) {
kmin = k;
if (d0 <= d1) {
dmin = d0;
smin = s0;
} else {
dmin = d1;
smin = s1[0];
}
}
}
steps[sp] = smin;
//logger.log(Level.TRACE, "kmin %d, smin %5d, ".formatted(kmin, smin));
encode(channel, channels, v, _iCoef[kmin], inBuffer, length, steps, sp, outBuffer);
outBuffer[channel] = (byte) kmin;
}
/**
* Encode.
* @param channels total channels
* @param inBuffer interleaved input samples
* @param length samples to encode PER channel
* @param steps input/output steps, 16 <= steps[i]
* @param outBuffer output buffer[blockAlign]
* @param blockAlign >= 7 * channels + channels * (n - 2) / 2.0
*/
public void encodeBlock(int channels,
int[] inBuffer,
int length,
int[] steps,
byte[] outBuffer,
int blockAlign) {
for (int p = 7 * channels; p < blockAlign; p++) {
outBuffer[p] = 0;
}
for (int channel = 0; channel < channels; channel++) {
encodeChannel(channel, channels, inBuffer, length, steps, channel, outBuffer);
}
}
/**
* Returns the number of samples/channel which would be
* in the dataLength, given the other parameters ...
* if input samplesPerBlock is 0, then returns the max
* samplesPerBlock which would go into a block of size blockAlign
* Yes, it is confusing usage.
*/
public static int getSamplesIn(int dataLength,
int channels,
int blockAlign,
int samplesPerBlock) {
int m, n;
if (samplesPerBlock > 0) {
n = (dataLength / blockAlign) * samplesPerBlock;
m = dataLength % blockAlign;
} else {
n = 0;
m = blockAlign;
}
//logger.log(Level.TRACE, "n: " + n);
//logger.log(Level.TRACE, "m: " + m);
if (m >= 7 * channels) {
m -= 7 * channels; // bytes beyond block-header
m = (2 * m) / channels + 2; // nibbles / channels + 2 in header
if (samplesPerBlock > 0 && m > samplesPerBlock) {
m = samplesPerBlock;
}
n += m;
}
return n;
}
/** Returns bytes per block. */
public static int getBytesPerBlock(int channels, int samplesPerBlock) {
int n = 7 * channels; // header
if (samplesPerBlock > 2) {
n += ((samplesPerBlock - 2) * channels + 1) / 2;
}
return n;
}
}