Debian Codegraph @

extern/adpcm/ymb_codec.c

raw
1 /*
2 Encode and decode algorithms for
3 Y8950/YM2608/YM2610 ADPCM-B
4
5 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 static inline int16_t ymb_step(uint8_t step, int16_t* history, int16_t* step_size)
17 {
18 static const int step_table[8] = {
19 57, 57, 57, 57, 77, 102, 128, 153
20 };
21
22 int sign = step & 8;
23 int delta = step & 7;
24 int diff = ((1+(delta<<1)) * *step_size) >> 3;
25 int newval = *history;
26 int nstep = (step_table[delta] * *step_size) >> 6;
27 if (sign > 0)
28 newval -= diff;
29 else
30 newval += diff;
31 //*step_size = CLAMP(nstep, 511, 32767);
32 *step_size = CLAMP(nstep, 127, 24576);
33 *history = newval = CLAMP(newval, -32768, 32767);
34 return newval;
35 }
36
37 void ymb_encode(int16_t *buffer,uint8_t *outbuffer,long len)
38 {
39 long i;
40 int16_t step_size = 127;
41 int16_t history = 0;
42 uint8_t buf_sample = 0, nibble = 0;
43 unsigned int adpcm_sample;
44
45 for(i=0;i<len;i++)
46 {
47 // we remove a few bits of accuracy to reduce some noise.
48 int step = ((*buffer++) & -8) - history;
49 adpcm_sample = (abs(step)<<16) / (step_size<<14);
50 adpcm_sample = CLAMP(adpcm_sample, 0, 7);
51 if(step < 0)
52 adpcm_sample |= 8;
53 if(nibble)
54 *outbuffer++ = buf_sample | (adpcm_sample&15);
55 else
56 buf_sample = (adpcm_sample&15)<<4;
57 nibble^=1;
58 ymb_step(adpcm_sample, &history, &step_size);
59 }
60 }
61
62 void ymb_decode(uint8_t *buffer,int16_t *outbuffer,long len)
63 {
64 long i;
65
66 int16_t step_size = 127;
67 int16_t history = 0;
68 uint8_t nibble = 0;
69
70 for(i=0;i<len;i++)
71 {
72 int8_t step = (*(int8_t*)buffer)<<nibble;
73 step >>= 4;
74 if(nibble)
75 buffer++;
76 nibble^=4;
77 *outbuffer++ = ymb_step(step, &history, &step_size);
78 }
79 }