]> Shamusworld >> Repos - virtualjaguar/blob - src/dac.cpp
Fixed memory leak
[virtualjaguar] / src / dac.cpp
1 //
2 // DAC (really, Synchronous Serial Interface) Handler
3 //
4 // Original by Cal2
5 // GCC/SDL port by Niels Wagenaar (Linux/WIN32) and Caz (BeOS)
6 // Rewritten by James L. Hammons
7 //
8
9 //#include <SDL.h>
10 #include "SDL.h"
11 #include "jaguar.h"
12 #include "settings.h"
13 #include "dac.h"
14
15 //#define DEBUG_DAC
16
17 #define BUFFER_SIZE             0x10000                                         // Make the DAC buffers 64K x 16 bits
18
19 // Jaguar memory locations
20
21 #define LTXD                    0xF1A148
22 #define RTXD                    0xF1A14C
23 #define SCLK                    0xF1A150
24 #define SMODE                   0xF1A154
25
26 // Local variables
27
28 uint32 LeftFIFOHeadPtr, LeftFIFOTailPtr, RightFIFOHeadPtr, RightFIFOTailPtr;
29 SDL_AudioSpec desired;
30
31 // We can get away with using native endian here because we can tell SDL to use the native
32 // endian when looking at the sample buffer, i.e., no need to worry about it.
33
34 uint16 * DACBuffer;
35 uint8 SCLKFrequencyDivider = 19;                                                // Default is roughly 22 KHz (20774 Hz in NTSC mode)
36 uint16 serialMode = 0;
37
38 // Private function prototypes
39
40 void SDLSoundCallback(void * userdata, Uint8 * buffer, int length);
41 int GetCalculatedFrequency(void);
42
43 //
44 // Initialize the SDL sound system
45 //
46 void DACInit(void)
47 {
48         memory_malloc_secure((void **)&DACBuffer, BUFFER_SIZE * sizeof(uint16), "DAC buffer");
49
50         desired.freq = GetCalculatedFrequency();                // SDL will do conversion on the fly, if it can't get the exact rate. Nice!
51         desired.format = AUDIO_S16SYS;                                  // This uses the native endian (for portability)...
52         desired.channels = 2;
53 //      desired.samples = 4096;                                                 // Let's try a 4K buffer (can always go lower)
54         desired.samples = 2048;                                                 // Let's try a 2K buffer (can always go lower)
55         desired.callback = SDLSoundCallback;
56
57         if (SDL_OpenAudio(&desired, NULL) < 0)                  // NULL means SDL guarantees what we want
58         {
59                 WriteLog("DAC: Failed to initialize SDL sound. Shutting down!\n");
60                 log_done();
61                 exit(1);
62         }
63
64         DACReset();
65         SDL_PauseAudio(false);                                                  // Start playback!
66         WriteLog("DAC: Successfully initialized.\n");
67 }
68
69 //
70 // Reset the sound buffer FIFOs
71 //
72 void DACReset(void)
73 {
74         LeftFIFOHeadPtr = LeftFIFOTailPtr = 0, RightFIFOHeadPtr = RightFIFOTailPtr = 1;
75 }
76
77 //
78 // Close down the SDL sound subsystem
79 //
80 void DACDone(void)
81 {
82         SDL_PauseAudio(true);
83         SDL_CloseAudio();
84         memory_free(DACBuffer);
85         WriteLog("DAC: Done.\n");
86 }
87
88 //
89 // SDL callback routine to fill audio buffer
90 //
91 // Note: The samples are packed in the buffer in 16 bit left/16 bit right pairs.
92 //
93 void SDLSoundCallback(void * userdata, Uint8 * buffer, int length)
94 {
95         // Clear the buffer to silence, in case the DAC buffer is empty (or short)
96         memset(buffer, desired.silence, length);
97 //WriteLog("DAC: Inside callback...\n");
98         if (LeftFIFOHeadPtr != LeftFIFOTailPtr)
99         {
100 //WriteLog("DAC: About to write some data!\n");
101                 int numLeftSamplesReady
102                         = (LeftFIFOTailPtr + (LeftFIFOTailPtr < LeftFIFOHeadPtr ? BUFFER_SIZE : 0))
103                                 - LeftFIFOHeadPtr;
104                 int numRightSamplesReady
105                         = (RightFIFOTailPtr + (RightFIFOTailPtr < RightFIFOHeadPtr ? BUFFER_SIZE : 0))
106                                 - RightFIFOHeadPtr;
107                 int numSamplesReady
108                         = (numLeftSamplesReady < numRightSamplesReady
109                                 ? numLeftSamplesReady : numRightSamplesReady);//Hmm. * 2;
110
111 //The numbers look good--it's just that the DSP can't get enough samples in the DAC buffer!
112 //WriteLog("DAC: Left/RightFIFOHeadPtr: %u/%u, Left/RightFIFOTailPtr: %u/%u\n", LeftFIFOHeadPtr, RightFIFOHeadPtr, LeftFIFOTailPtr, RightFIFOTailPtr);
113 //WriteLog("     numLeft/RightSamplesReady: %i/%i, numSamplesReady: %i, length of buffer: %i\n", numLeftSamplesReady, numRightSamplesReady, numSamplesReady, length);
114
115 /*              if (numSamplesReady > length)
116                         numSamplesReady = length;//*/
117                 if (numSamplesReady > length / 2)       // length / 2 because we're comparing 16-bit lengths
118                         numSamplesReady = length / 2;
119 //else
120 //      WriteLog("     Not enough samples to fill the buffer (short by %u L/R samples)...\n", (length / 2) - numSamplesReady);
121 //WriteLog("DAC: %u samples ready.\n", numSamplesReady);
122
123                 // Actually, it's a bit more involved than this, but this is the general idea:
124 //              memcpy(buffer, DACBuffer, length);
125                 for(int i=0; i<numSamplesReady; i++)
126                         ((uint16 *)buffer)[i] = DACBuffer[(LeftFIFOHeadPtr + i) % BUFFER_SIZE];
127                         // Could also use (as long as BUFFER_SIZE is a multiple of 2):
128 //                      buffer[i] = DACBuffer[(LeftFIFOHeadPtr + i) & (BUFFER_SIZE - 1)];
129
130                 LeftFIFOHeadPtr = (LeftFIFOHeadPtr + numSamplesReady) % BUFFER_SIZE;
131                 RightFIFOHeadPtr = (RightFIFOHeadPtr + numSamplesReady) % BUFFER_SIZE;
132                 // Could also use (as long as BUFFER_SIZE is a multiple of 2):
133 //              LeftFIFOHeadPtr = (LeftFIFOHeadPtr + numSamplesReady) & (BUFFER_SIZE - 1);
134 //              RightFIFOHeadPtr = (RightFIFOHeadPtr + numSamplesReady) & (BUFFER_SIZE - 1);
135 //WriteLog("  -> Left/RightFIFOHeadPtr: %u/%u, Left/RightFIFOTailPtr: %u/%u\n", LeftFIFOHeadPtr, RightFIFOHeadPtr, LeftFIFOTailPtr, RightFIFOTailPtr);
136         }
137 //Hmm. Seems that the SDL buffer isn't being starved by the DAC buffer...
138 //      else
139 //              WriteLog("DAC: Silence...!\n");
140 }
141
142 //
143 // Calculate the frequency of SCLK * 32 using the divider
144 //
145 int GetCalculatedFrequency(void)
146 {
147         int systemClockFrequency = (vjs.hardwareTypeNTSC ? RISC_CLOCK_RATE_NTSC : RISC_CLOCK_RATE_PAL);
148
149         // We divide by 32 here in order to find the frequency of 32 SCLKs in a row (transferring
150         // 16 bits of left data + 16 bits of right data = 32 bits, 1 SCLK = 1 bit transferred).
151         return systemClockFrequency / (32 * (2 * (SCLKFrequencyDivider + 1)));
152 }
153
154 //
155 // LTXD/RTXD/SCLK/SMODE ($F1A148/4C/50/54)
156 //
157 void DACWriteByte(uint32 offset, uint8 data)
158 {
159         WriteLog("DAC: Writing %02X at %08X\n", data, offset);
160         if (offset == SCLK + 3)
161                 DACWriteWord(offset - 3, (uint16)data);
162 }
163
164 void DACWriteWord(uint32 offset, uint16 data)
165 {
166         if (offset == LTXD + 2)
167         {
168                 // Spin until buffer has been drained (for too fast processors!)...
169 //Small problem--if Head == 0 and Tail == buffer end, then this will fail... !!! FIX !!!
170 //[DONE]
171                 // Also, we're taking advantage of the fact that the buffer is a multiple of two
172                 // in this check...
173                 while ((LeftFIFOTailPtr + 2) & (BUFFER_SIZE - 1) == LeftFIFOHeadPtr);
174
175                 SDL_LockAudio();                                                        // Is it necessary to do this? Mebbe.
176                 // We use a circular buffer 'cause it's easy. Note that the callback function
177                 // takes care of dumping audio to the soundcard...! Also note that we're writing
178                 // the samples in the buffer in an interleaved L/R format.
179                 LeftFIFOTailPtr = (LeftFIFOTailPtr + 2) % BUFFER_SIZE;
180                 DACBuffer[LeftFIFOTailPtr] = data;
181                 SDL_UnlockAudio();
182         }
183         else if (offset == RTXD + 2)
184         {
185                 // Spin until buffer has been drained (for too fast processors!)...
186 //uint32 spin = 0;
187                 while ((RightFIFOTailPtr + 2) & (BUFFER_SIZE - 1) == RightFIFOHeadPtr);
188 /*              {
189 spin++;
190 if (spin == 0x10000000)
191 {
192         WriteLog("\nStuck in right DAC spinlock! Tail=%u, Head=%u\nAborting!\n", RightFIFOTailPtr, RightFIFOHeadPtr);
193         log_done();
194         exit(0);
195 }
196                 }*/
197
198 //This is wrong         if (RightFIFOTailPtr + 2 != RightFIFOHeadPtr)
199 //              {
200                 SDL_LockAudio();
201                 RightFIFOTailPtr = (RightFIFOTailPtr + 2) % BUFFER_SIZE;
202                 DACBuffer[RightFIFOTailPtr] = data;
203                 SDL_UnlockAudio();
204 //              }
205 /*#ifdef DEBUG_DAC
206                 else
207                         WriteLog("DAC: Ran into FIFO's right tail pointer!\n");
208 #endif*/
209         }
210         else if (offset == SCLK + 2)                                    // Sample rate
211         {
212                 WriteLog("DAC: Writing %u to SCLK...\n", data);
213                 if ((uint8)data != SCLKFrequencyDivider)
214                 {
215                         SCLKFrequencyDivider = (uint8)data;
216 //Of course a better way would be to query the hardware to find the upper limit...
217                         if (data > 7)   // Anything less than 8 is too high!
218                         {
219                                 SDL_CloseAudio();
220                                 desired.freq = GetCalculatedFrequency();// SDL will do conversion on the fly, if it can't get the exact rate. Nice!
221                                 WriteLog("DAC: Changing sample rate to %u Hz!\n", desired.freq);
222
223                                 if (SDL_OpenAudio(&desired, NULL) < 0)  // NULL means SDL guarantees what we want
224                                 {
225                                         WriteLog("DAC: Failed to initialize SDL sound: %s.\nDesired freq: %u\nShutting down!\n", SDL_GetError(), desired.freq);
226                                         log_done();
227                                         exit(1);
228                                 }
229
230                                 DACReset();
231                                 SDL_PauseAudio(false);                          // Start playback!
232                         }
233                 }
234         }
235         else if (offset == SMODE + 2)
236         {
237                 serialMode = data;
238                 WriteLog("DAC: Writing to SMODE. Bits: %s%s%s%s%s%s\n",
239                         (data & 0x01 ? "INTERNAL " : ""), (data & 0x02 ? "MODE " : ""),
240                         (data & 0x04 ? "WSEN " : ""), (data & 0x08 ? "RISING " : ""),
241                         (data & 0x10 ? "FALLING " : ""), (data & 0x20 ? "EVERYWORD" : ""));
242         }
243 }
244
245 //
246 // LRXD/RRXD/SSTAT ($F1A148/4C/50)
247 //
248 uint8 DACReadByte(uint32 offset)
249 {
250 //      WriteLog("DAC: Reading byte from %08X\n", offset);
251         return 0xFF;
252 }
253
254 uint16 DACReadWord(uint32 offset)
255 {
256 //      WriteLog("DAC: Reading word from %08X\n", offset);
257         return 0xFFFF;
258 }