Debian Codegraph @

BambooTracker/chip/codec/ymb_codec.hpp

raw
1 /*
2 Encode and decode algorithms for
3 Y8950/YM2608/YM2610 ADPCM-B
4
5 2019 by superctr.
6 */
7
8 #pragma once
9
10 #include <stdio.h>
11 #include <stdlib.h>
12 #include <stdint.h>
13 #include <string.h>
14 #include <math.h>
15
16 #define CD_CLAMP(x, low, high) (((x) > (high)) ? (high) : (((x) < (low)) ? (low) : (x)))
17 #define CD_CLAMP_ZERO(x, high) (((x) > (high)) ? (high) : (x))
18
19 namespace codec
20 {
21 inline int16_t ymb_step(uint8_t step, int16_t* history, int16_t* step_size)
22 {
23 static const int step_table[8] = {
24 57, 57, 57, 57, 77, 102, 128, 153
25 };
26
27 int sign = step & 8;
28 int delta = step & 7;
29 int diff = ((1+(delta<<1)) * *step_size) >> 3;
30 int newval = *history;
31 int nstep = (step_table[delta] * *step_size) >> 6;
32 if (sign > 0)
33 newval -= diff;
34 else
35 newval += diff;
36 //*step_size = CLAMP(nstep, 511, 32767);
37 *step_size = CD_CLAMP(nstep, 127, 24576);
38 *history = newval = CD_CLAMP(newval, -32768, 32767);
39 return newval;
40 }
41
42 inline void ymb_encode(int16_t *buffer,uint8_t *outbuffer,long len)
43 {
44 long i;
45 int16_t step_size = 127;
46 int16_t history = 0;
47 uint8_t buf_sample = 0, nibble = 0;
48 unsigned int adpcm_sample;
49
50 for(i=0;i<len;i++)
51 {
52 // we remove a few bits of accuracy to reduce some noise.
53 int step = ((*buffer++) & -8) - history;
54 adpcm_sample = (abs(step)<<16) / (step_size<<14);
55 adpcm_sample = CD_CLAMP_ZERO(adpcm_sample, 7);
56 if(step < 0)
57 adpcm_sample |= 8;
58 if(nibble)
59 *outbuffer++ = buf_sample | (adpcm_sample&15);
60 else
61 buf_sample = (adpcm_sample&15)<<4;
62 nibble^=1;
63 ymb_step(adpcm_sample, &history, &step_size);
64 }
65 }
66
67 inline void ymb_decode(uint8_t *buffer,int16_t *outbuffer,long len)
68 {
69 long i;
70
71 int16_t step_size = 127;
72 int16_t history = 0;
73 uint8_t nibble = 0;
74
75 for(i=0;i<len;i++)
76 {
77 int8_t step = (*(int8_t*)buffer)<<nibble;
78 step >>= 4;
79 if(nibble)
80 buffer++;
81 nibble^=4;
82 *outbuffer++ = ymb_step(step, &history, &step_size);
83 }
84 }
85 }
86
87 #undef CD_CLAMP
88 #undef CD_CLAMP_ZERO