Debian Codegraph @

extern/adpcm/bs_codec.c

raw
1 /*
2 Encode and decode algorithms for
3 Brian Schmidt's ADPCM used in QSound DSP
4
5 2018-2019 by superctr.
6 */
7
8 #include <stdio.h>
9 #include <stdlib.h>
10 #include <stdint.h>
11 #include <string.h>
12 #include <math.h>
13
14 #define CLAMP(x, low, high) (((x) > (high)) ? (high) : (((x) < (low)) ? (low) : (x)))
15
16 // step ADPCM algorithm
17 static inline int16_t bs_step(int8_t step, int16_t* history, int16_t* step_size)
18 {
19 static const int16_t adpcm_table[16] = {
20 154, 154, 128, 102, 77, 58, 58, 58, // 2.4, 2.4, 2.0, 1.6, 1.2, 0.9, 0.9, 0.9
21 58, 58, 58, 58, 77, 102, 128, 154 // 0.9, 0.9, 0.9, 0.9, 1.2, 1.6, 2.0, 2.4
22 };
23
24 int32_t scale = *step_size;
25 int32_t delta = ((1+abs(step<<1)) * scale)>>1; // (0.5 + abs(step)) * scale
26 int32_t out = *history;
27 if(step <= 0)
28 delta = -delta;
29 out += delta;
30 out = CLAMP(out, -32768,32767);
31
32 scale = (scale * adpcm_table[8+step])>>6;
33 *step_size = CLAMP(scale, 1, 2000);
34 *history = out;
35
36 return out;
37 }
38
39 // step high pass filter
40 static inline int16_t bs_hpf_step(int16_t in, int16_t* history, int32_t *state)
41 {
42 int32_t out;
43 *state = (*state>>2) + in - *history;
44 *history = in;
45 out = (*state>>1) + in;
46 return CLAMP(out, -32768,32767);
47 }
48
49 // encode ADPCM with high pass filter. gets better results, i think
50 void bs_encode(int16_t *buffer,uint8_t *outbuffer,long len)
51 {
52 long i;
53
54 int16_t step_size = 10;
55 int16_t history = 0;
56 uint8_t buf_sample = 0, nibble = 0;
57 int16_t filter_history = 0;
58 int32_t filter_state = 0;
59
60 for(i=0;i<len;i++)
61 {
62 int step = bs_hpf_step(*buffer++,&filter_history,&filter_state) - history;
63 step = (step / step_size)>>1;
64 step = CLAMP(step, -8, 7);
65 if(nibble)
66 *outbuffer++ = buf_sample | (step&15);
67 else
68 buf_sample = (step&15)<<4;
69 nibble^=1;
70 bs_step(step, &history, &step_size);
71 }
72 }
73
74 void bs_decode(uint8_t *buffer,int16_t *outbuffer,long len)
75 {
76 long i;
77
78 int16_t step_size = 10;
79 int16_t history = 0;
80 uint8_t nibble = 0;
81
82 for(i=0;i<len;i++)
83 {
84 int8_t step = (*(int8_t*)buffer)<<nibble;
85 step >>= 4;
86 if(nibble)
87 buffer++;
88 nibble^=4;
89 *outbuffer++ = bs_step(step, &history, &step_size);
90 }
91 }