Pico PCM, only one hardcoded mode for now
[picodrive.git] / Pico / Pico / xpcm.c
1 /*
2  * The following ADPCM algorithm was stolen from MAME aica driver.
3  * I'm quite sure it's not the right one, but it's the
4  * best sounding of the ones that I tried.
5  */
6
7 #include "../PicoInt.h"
8
9 #define ADPCMSHIFT      8
10 #define ADFIX(f)        (int) ((double)f * (double)(1<<ADPCMSHIFT))
11
12 /* limitter */
13 #define Limit(val, max, min) { \
14         if ( val > max )      val = max; \
15         else if ( val < min ) val = min; \
16 }
17
18 const int TableQuant[8] =
19 {
20   ADFIX(0.8984375),
21   ADFIX(0.8984375),
22   ADFIX(0.8984375),
23   ADFIX(0.8984375),
24   ADFIX(1.19921875),
25   ADFIX(1.59765625),
26   ADFIX(2.0),
27   ADFIX(2.3984375)
28 };
29
30 // changed using trial and error..
31 //const int quant_mul[16] = { 1, 3, 5, 7, 9, 11, 13, 15, -1, -3, -5, -7, -9, -11, -13, -15 };
32 const int quant_mul[16]   = { 1, 3, 5, 7, 9, 11, 13, -1, -1, -3, -5, -7, -9, -11, -13, -15 };
33
34 static int sample = 0, quant = 0;
35
36 PICO_INTERNAL void PicoPicoPCMReset(void)
37 {
38   sample = 0;
39   quant = 0x7f;
40   memset(PicoPicohw.xpcm_buffer, 0, sizeof(PicoPicohw.xpcm_buffer));
41 }
42
43 #define XSHIFT 7
44
45 #define do_sample() \
46 { \
47   sample += quant * quant_mul[srcval] >> XSHIFT; \
48   quant = (quant * TableQuant[srcval&7]) >> ADPCMSHIFT; \
49   Limit(quant, 0x6000, 0x7f); \
50   Limit(sample, 32767, -32768); \
51 }
52
53 PICO_INTERNAL void PicoPicoPCMUpdate(short *buffer, int length, int stereo)
54 {
55   unsigned char *src = PicoPicohw.xpcm_buffer;
56   unsigned char *lim = PicoPicohw.xpcm_ptr;
57   int srcval, stepsamples = (44100<<10)/16000, needsamples = 0; // TODO: stepsamples
58
59   if (src == lim)
60   {
61     if (stereo)
62       // still must expand SN76496 to stereo
63       for (; length > 0; buffer+=2, length--)
64         buffer[1] = buffer[0];
65     sample = quant = 0;
66     return;
67   }
68
69   for (; length > 0 && src < lim; src++)
70   {
71     srcval = *src >> 4;
72     do_sample();
73
74     for (needsamples += stepsamples; needsamples > (1<<10) && length > 0; needsamples -= (1<<10), length--) {
75       *buffer++ = sample;
76       if (stereo) { buffer[0] = buffer[-1]; buffer++; }
77     }
78
79     srcval = *src & 0xf;
80     do_sample();
81
82     for (needsamples += stepsamples; needsamples > (1<<10) && length > 0; needsamples -= (1<<10), length--) {
83       *buffer++ = sample;
84       if (stereo) { buffer[0] = buffer[-1]; buffer++; }
85     }
86   }
87
88   if (src < lim) {
89     int di = lim - src;
90     memmove(PicoPicohw.xpcm_buffer, src, di);
91     PicoPicohw.xpcm_ptr = PicoPicohw.xpcm_buffer + di;
92     elprintf(EL_STATUS, "xpcm update: over %i", di);
93   }
94   else
95   {
96     elprintf(EL_STATUS, "xpcm update: under %i", length);
97     PicoPicohw.xpcm_ptr = PicoPicohw.xpcm_buffer;
98   }
99 }
100