Debian Codegraph @

src/engine/platform/sound/vera_pcm.c

raw
1 // Commander X16 Emulator
2 // Copyright (c) 2020 Frank van den Hoef
3 // All rights reserved. License: 2-clause BSD
4
5 #include "vera_pcm.h"
6 #include <stdio.h>
7 #include <string.h>
8
9 static uint8_t volume_lut[16] = {0, 1, 2, 3, 4, 5, 6, 8, 11, 14, 18, 23, 30, 38, 49, 64};
10
11 static void
12 fifo_reset(struct VERA_PCM* pcm)
13 {
14 pcm->fifo_wridx = 0;
15 pcm->fifo_rdidx = 0;
16 pcm->fifo_cnt = 0;
17 memset(pcm->fifo,0,sizeof(pcm->fifo));
18 }
19
20 void
21 pcm_reset(struct VERA_PCM* pcm)
22 {
23 fifo_reset(pcm);
24 pcm->ctrl = 0;
25 pcm->rate = 0;
26 pcm->cur_l = 0;
27 pcm->cur_r = 0;
28 pcm->phase = 0;
29 }
30
31 void
32 pcm_write_ctrl(struct VERA_PCM* pcm, uint8_t val)
33 {
34 if (val & 0x80) {
35 fifo_reset(pcm);
36 }
37
38 pcm->ctrl = val & 0x3F;
39 }
40
41 uint8_t
42 pcm_read_ctrl(struct VERA_PCM* pcm)
43 {
44 uint8_t result = pcm->ctrl;
45 if (pcm->fifo_cnt == sizeof(pcm->fifo)) {
46 result |= 0x80;
47 }
48 return result;
49 }
50
51 void
52 pcm_write_rate(struct VERA_PCM* pcm, uint8_t val)
53 {
54 pcm->rate = val;
55 }
56
57 uint8_t
58 pcm_read_rate(struct VERA_PCM* pcm)
59 {
60 return pcm->rate;
61 }
62
63 void
64 pcm_write_fifo(struct VERA_PCM* pcm, uint8_t val)
65 {
66 if (pcm->fifo_cnt < sizeof(pcm->fifo)) {
67 pcm->fifo[pcm->fifo_wridx++] = val;
68 if (pcm->fifo_wridx == sizeof(pcm->fifo)) {
69 pcm->fifo_wridx = 0;
70 }
71 pcm->fifo_cnt++;
72 }
73 }
74
75 static uint8_t
76 read_fifo(struct VERA_PCM* pcm)
77 {
78 if (pcm->fifo_cnt == 0) {
79 return 0;
80 }
81 uint8_t result = pcm->fifo[pcm->fifo_rdidx++];
82 if (pcm->fifo_rdidx == sizeof(pcm->fifo)) {
83 pcm->fifo_rdidx = 0;
84 }
85 pcm->fifo_cnt--;
86 return result;
87 }
88
89 bool
90 pcm_is_fifo_almost_empty(struct VERA_PCM* pcm)
91 {
92 return pcm->fifo_cnt < 1024;
93 }
94
95 void
96 pcm_render(struct VERA_PCM* pcm, int16_t* buf_l, int16_t* buf_r, unsigned num_samples)
97 {
98 while (num_samples--) {
99 uint8_t old_phase = pcm->phase;
100 pcm->phase += pcm->rate;
101 if ((old_phase & 0x80) != (pcm->phase & 0x80)) {
102 switch ((pcm->ctrl >> 4) & 3) {
103 case 0: { // mono 8-bit
104 pcm->cur_l = (int16_t)read_fifo(pcm) << 8;
105 pcm->cur_r = pcm->cur_l;
106 break;
107 }
108 case 1: { // stereo 8-bit
109 pcm->cur_l = read_fifo(pcm) << 8;
110 pcm->cur_r = read_fifo(pcm) << 8;
111 break;
112 }
113 case 2: { // mono 16-bit
114 pcm->cur_l = read_fifo(pcm);
115 pcm->cur_l |= read_fifo(pcm) << 8;
116 pcm->cur_r = pcm->cur_l;
117 break;
118 }
119 case 3: { // stereo 16-bit
120 pcm->cur_l = read_fifo(pcm);
121 pcm->cur_l |= read_fifo(pcm) << 8;
122 pcm->cur_r = read_fifo(pcm);
123 pcm->cur_r |= read_fifo(pcm) << 8;
124 break;
125 }
126 }
127 }
128
129 *(buf_l) += ((int)pcm->cur_l * (int)volume_lut[pcm->ctrl & 0xF]) >> 6;
130 *(buf_r) += ((int)pcm->cur_r * (int)volume_lut[pcm->ctrl & 0xF]) >> 6;
131
132 buf_l++;
133 buf_r++;
134 }
135 }