Debian Codegraph @

extern/adpcm/yma_codec.c

raw
1 /*
2 Encode and decode algorithms for
3 Yamaha ADPCM-A
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 const uint16_t yma_step_table[49] = {
17 16, 17, 19, 21, 23, 25, 28, 31,
18 34, 37, 41, 45, 50, 55, 60, 66,
19 73, 80, 88, 97, 107,118,130,143,
20 157,173,190,209,230,253,279,307,
21 337,371,408,449,494,544,598,658,
22 724,796,876,963,1060,1166,1282,1411,1552
23 };
24
25 // *** Yamaha ADPCM-A ***
26 static inline int16_t yma_step(uint8_t step, int16_t* history, uint8_t* step_hist)
27 {
28 static const int8_t delta_table[16] = {
29 1,3,5,7,9,11,13,15, -1,-3,-5,-7,-9,-11,-13,-15
30 };
31 static const int8_t adjust_table[8] = {
32 -1,-1,-1,-1,2,5,7,9
33 };
34 uint16_t step_size = yma_step_table[*step_hist];
35 int16_t delta = delta_table[step & 15] * step_size / 8;
36 int16_t out = (*history + delta) & 0xfff; // No saturation
37 out |= (out & 0x800) ? ~0xfff : 0;
38 *history = out;
39 int8_t adjusted_step = *step_hist + adjust_table[step & 7]; // Different adjust table
40 *step_hist = CLAMP(adjusted_step, 0, 48);
41
42 return out;
43 }
44
45 static inline uint8_t yma_encode_step(int16_t input, int16_t* history, uint8_t *step_hist)
46 {
47 int bit;
48 uint16_t step_size = yma_step_table[*step_hist];
49 int16_t delta = input - *history;
50 uint8_t adpcm_sample = (delta < 0) ? 8 : 0;
51 if(delta < 0)
52 adpcm_sample = 8;
53 delta = abs(delta);
54 for(bit=3; bit--; )
55 {
56 if(delta >= step_size)
57 {
58 adpcm_sample |= (1<<bit);
59 delta -= step_size;
60 }
61 step_size >>= 1;
62 }
63 yma_step(adpcm_sample,history,step_hist);
64 return adpcm_sample;
65 }
66
67 void yma_encode(int16_t *buffer,uint8_t *outbuffer,long len)
68 {
69 long i;
70
71 int16_t history = 0;
72 uint8_t step_hist = 0;
73 uint8_t buf_sample = 0, nibble = 0;
74
75 for(i=0;i<len;i++)
76 {
77 int16_t sample = *buffer++;
78 if(sample < 0x7ff8) // round up
79 sample += 8;
80 sample >>= 4;
81 int step = yma_encode_step(sample, &history, &step_hist);
82 if(nibble)
83 *outbuffer++ = buf_sample | (step&15);
84 else
85 buf_sample = (step&15)<<4;
86 nibble^=1;
87 }
88 }
89
90 void yma_decode(uint8_t *buffer,int16_t *outbuffer,long len)
91 {
92 long i;
93
94 int16_t history = 0;
95 uint8_t step_hist = 0;
96 uint8_t nibble = 0;
97
98 for(i=0;i<len;i++)
99 {
100 int8_t step = (*(int8_t*)buffer)<<nibble;
101 step >>= 4;
102 if(nibble)
103 buffer++;
104 nibble^=4;
105 *outbuffer++ = yma_step(step, &history, &step_hist) << 4;
106 }
107 }