]> Shamusworld >> Repos - virtualjaguar/blob - src/dac.cpp
Added appropriate audio thread pausing to the GUI layer.
[virtualjaguar] / src / dac.cpp
1 //
2 // DAC (really, Synchronous Serial Interface) Handler
3 //
4 // Originally by David Raingeard
5 // GCC/SDL port by Niels Wagenaar (Linux/WIN32) and Caz (BeOS)
6 // Rewritten by James Hammons
7 // (C) 2010 Underground Software
8 //
9 // JLH = James Hammons <jlhamm@acm.org>
10 //
11 // Who  When        What
12 // ---  ----------  -------------------------------------------------------------
13 // JLH  01/16/2010  Created this log ;-)
14 // JLH  04/30/2012  Changed SDL audio handler to run JERRY
15 //
16
17 // Need to set up defaults that the BIOS sets for the SSI here in DACInit()... !!! FIX !!!
18 // or something like that... Seems like it already does, but it doesn't seem to
19 // work correctly...! Perhaps just need to set up SSI stuff so BUTCH doesn't get
20 // confused...
21
22 // ALSO: Need to implement some form of proper locking to replace the clusterfuck
23 //       that is the current spinlock implementation. Since the DSP is a separate
24 //       entity, could we get away with running it in the sound IRQ?
25
26 // After testing on a real Jaguar, it seems clear that the I2S interrupt drives
27 // the audio subsystem. So while you can drive the audio at a *slower* rate than
28 // set by SCLK, you can't drive it any *faster*. Also note, that if the I2S
29 // interrupt is not enabled/running on the DSP, then there is no audio. Also,
30 // audio can be muted by clearing bit 8 of JOYSTICK (JOY1).
31 //
32 // Approach: We can run the DSP in the host system's audio IRQ, by running the
33 // DSP for the alloted time (depending on the host buffer size & sample rate)
34 // by simply reading the L/R_I2S (L/RTXD) registers at regular intervals. We
35 // would also have to time the I2S/TIMER0/TIMER1 interrupts in the DSP as well.
36 // This way, we can run the host audio IRQ at, say, 48 KHz and not have to care
37 // so much about SCLK and running a separate buffer and all the attendant
38 // garbage that comes with that awful approach.
39 //
40 // There would still be potential gotchas, as the SCLK can theoretically drive
41 // the I2S at 26590906 / 2 (for SCLK == 0) = 13.3 MHz which corresponds to an
42 // audio rate 416 KHz (dividing the I2S rate by 32, for 16-bit stereo). It
43 // seems doubtful that anything useful could come of such a high rate, and we
44 // can probably safely ignore any such ridiculously high audio rates. It won't
45 // sound the same as on a real Jaguar, but who cares? :-)
46
47 #include "dac.h"
48
49 #include "SDL.h"
50 #include "cdrom.h"
51 #include "dsp.h"
52 #include "event.h"
53 #include "jerry.h"
54 #include "jaguar.h"
55 #include "log.h"
56 #include "m68000/m68kinterface.h"
57 //#include "memory.h"
58 #include "settings.h"
59
60
61 //#define DEBUG_DAC
62
63 #define BUFFER_SIZE                     0x10000                         // Make the DAC buffers 64K x 16 bits
64 #define DAC_AUDIO_RATE          48000                           // Set the audio rate to 48 KHz
65
66 // Jaguar memory locations
67
68 #define LTXD                    0xF1A148
69 #define RTXD                    0xF1A14C
70 #define LRXD                    0xF1A148
71 #define RRXD                    0xF1A14C
72 #define SCLK                    0xF1A150
73 #define SMODE                   0xF1A154
74
75 // Global variables
76
77 // These are defined in memory.h/cpp
78 //uint16 lrxd, rrxd;                                                    // I2S ports (into Jaguar)
79
80 // Local variables
81
82 static SDL_AudioSpec desired;
83 static bool SDLSoundInitialized;
84 static uint8 SCLKFrequencyDivider = 19;                 // Default is roughly 22 KHz (20774 Hz in NTSC mode)
85 /*static*/ uint16 serialMode = 0;
86
87 // Private function prototypes
88
89 void SDLSoundCallback(void * userdata, Uint8 * buffer, int length);
90 void DSPSampleCallback(void);
91
92
93 //
94 // Initialize the SDL sound system
95 //
96 void DACInit(void)
97 {
98         SDLSoundInitialized = false;
99
100 //      if (!vjs.audioEnabled)
101         if (!vjs.DSPEnabled)
102         {
103                 WriteLog("DAC: DSP/host audio playback disabled.\n");
104                 return;
105         }
106
107         desired.freq = DAC_AUDIO_RATE;
108         desired.format = AUDIO_S16SYS;
109         desired.channels = 2;
110         desired.samples = 2048;                                         // 2K buffer = audio delay of 42.67 ms (@ 48 KHz)
111         desired.callback = SDLSoundCallback;
112
113         if (SDL_OpenAudio(&desired, NULL) < 0)          // NULL means SDL guarantees what we want
114                 WriteLog("DAC: Failed to initialize SDL sound...\n");
115         else
116         {
117                 SDLSoundInitialized = true;
118                 DACReset();
119                 SDL_PauseAudio(false);                                  // Start playback!
120                 WriteLog("DAC: Successfully initialized. Sample rate: %u\n", desired.freq);
121         }
122
123         ltxd = lrxd = desired.silence;
124
125         uint32_t riscClockRate = (vjs.hardwareTypeNTSC ? RISC_CLOCK_RATE_NTSC : RISC_CLOCK_RATE_PAL);
126         uint32_t cyclesPerSample = riscClockRate / DAC_AUDIO_RATE;
127         WriteLog("DAC: RISC clock = %u, cyclesPerSample = %u\n", riscClockRate, cyclesPerSample);
128 }
129
130
131 //
132 // Reset the sound buffer FIFOs
133 //
134 void DACReset(void)
135 {
136 //      LeftFIFOHeadPtr = LeftFIFOTailPtr = 0, RightFIFOHeadPtr = RightFIFOTailPtr = 1;
137         ltxd = lrxd = desired.silence;
138 }
139
140
141 //
142 // Pause/unpause the SDL audio thread
143 //
144 void DACPauseAudioThread(bool state/*= true*/)
145 {
146                 SDL_PauseAudio(state);
147 }
148
149
150 //
151 // Close down the SDL sound subsystem
152 //
153 void DACDone(void)
154 {
155         if (SDLSoundInitialized)
156         {
157                 SDL_PauseAudio(true);
158                 SDL_CloseAudio();
159         }
160
161         WriteLog("DAC: Done.\n");
162 }
163
164
165 // Approach: Run the DSP for however many cycles needed to correspond to whatever sample rate
166 // we've set the audio to run at. So, e.g., if we run it at 48 KHz, then we would run the DSP
167 // for however much time it takes to fill the buffer. So with a 2K buffer, this would correspond
168 // to running the DSP for 0.042666... seconds. At 26590906 Hz, this would correspond to
169 // running the DSP for 1134545 cycles. You would then sample the L/RTXD registers every
170 // 1134545 / 2048 = 554 cycles to fill the buffer. You would also have to manage interrupt
171 // timing as well (generating them at the proper times), but that shouldn't be too difficult...
172 // If the DSP isn't running, then fill the buffer with L/RTXD and exit.
173
174 //
175 // SDL callback routine to fill audio buffer
176 //
177 // Note: The samples are packed in the buffer in 16 bit left/16 bit right pairs.
178 //       Also, length is the length of the buffer in BYTES
179 //
180 static Uint8 * sampleBuffer;
181 static int bufferIndex = 0;
182 static int numberOfSamples = 0;
183 static bool bufferDone = false;
184 void SDLSoundCallback(void * userdata, Uint8 * buffer, int length)
185 {
186         // 1st, check to see if the DSP is running. If not, fill the buffer with L/RXTD and exit.
187
188         if (!DSPIsRunning())
189         {
190                 for(int i=0; i<(length/2); i+=2)
191                 {
192                         ((uint16_t *)buffer)[i + 0] = ltxd;
193                         ((uint16_t *)buffer)[i + 1] = rtxd;
194                 }
195
196                 return;
197         }
198
199         // The length of time we're dealing with here is 1/48000 s, so we multiply this
200         // by the number of cycles per second to get the number of cycles for one sample.
201         uint32_t riscClockRate = (vjs.hardwareTypeNTSC ? RISC_CLOCK_RATE_NTSC : RISC_CLOCK_RATE_PAL);
202         uint32_t cyclesPerSample = riscClockRate / DAC_AUDIO_RATE;
203         // This is the length of time
204 //      timePerSample = (1000000.0 / (double)riscClockRate) * ();
205
206         // Now, run the DSP for that length of time for each sample we need to make
207
208         bufferIndex = 0;
209         sampleBuffer = buffer;
210         numberOfSamples = length / 2;
211         bufferDone = false;
212
213         SetCallbackTime(DSPSampleCallback, 1000000.0 / (double)DAC_AUDIO_RATE, EVENT_JERRY);
214
215         // These timings are tied to NTSC, need to fix that in event.cpp/h!
216         do
217         {
218                 double timeToNextEvent = GetTimeToNextEvent(EVENT_JERRY);
219
220                 if (vjs.DSPEnabled)
221                 {
222                         if (vjs.usePipelinedDSP)
223                                 DSPExecP2(USEC_TO_RISC_CYCLES(timeToNextEvent));
224                         else
225                                 DSPExec(USEC_TO_RISC_CYCLES(timeToNextEvent));
226                 }
227
228                 HandleNextEvent(EVENT_JERRY);
229         }
230         while (!bufferDone);
231 }
232
233
234 void DSPSampleCallback(void)
235 {
236         ((uint16_t *)sampleBuffer)[bufferIndex + 0] = ltxd;
237         ((uint16_t *)sampleBuffer)[bufferIndex + 1] = rtxd;
238         bufferIndex += 2;
239
240         if (bufferIndex == numberOfSamples)
241         {
242                 bufferDone = true;
243                 return;
244         }
245
246         SetCallbackTime(DSPSampleCallback, 1000000.0 / (double)DAC_AUDIO_RATE, EVENT_JERRY);
247 }
248
249
250 #if 0
251 //
252 // Calculate the frequency of SCLK * 32 using the divider
253 //
254 int GetCalculatedFrequency(void)
255 {
256         int systemClockFrequency = (vjs.hardwareTypeNTSC ? RISC_CLOCK_RATE_NTSC : RISC_CLOCK_RATE_PAL);
257
258         // We divide by 32 here in order to find the frequency of 32 SCLKs in a row (transferring
259         // 16 bits of left data + 16 bits of right data = 32 bits, 1 SCLK = 1 bit transferred).
260         return systemClockFrequency / (32 * (2 * (SCLKFrequencyDivider + 1)));
261 }
262 #endif
263
264
265 //
266 // LTXD/RTXD/SCLK/SMODE ($F1A148/4C/50/54)
267 //
268 void DACWriteByte(uint32 offset, uint8 data, uint32 who/*= UNKNOWN*/)
269 {
270         WriteLog("DAC: %s writing BYTE %02X at %08X\n", whoName[who], data, offset);
271         if (offset == SCLK + 3)
272                 DACWriteWord(offset - 3, (uint16)data);
273 }
274
275
276 void DACWriteWord(uint32 offset, uint16 data, uint32 who/*= UNKNOWN*/)
277 {
278         if (offset == LTXD + 2)
279         {
280                 ltxd = data;
281         }
282         else if (offset == RTXD + 2)
283         {
284                 rtxd = data;
285         }
286         else if (offset == SCLK + 2)                                    // Sample rate
287         {
288                 WriteLog("DAC: Writing %u to SCLK...\n", data);
289
290                 if ((uint8)data != SCLKFrequencyDivider)
291                         SCLKFrequencyDivider = (uint8)data;
292         }
293         else if (offset == SMODE + 2)
294         {
295                 serialMode = data;
296                 WriteLog("DAC: %s writing to SMODE. Bits: %s%s%s%s%s%s [68K PC=%08X]\n", whoName[who],
297                         (data & 0x01 ? "INTERNAL " : ""), (data & 0x02 ? "MODE " : ""),
298                         (data & 0x04 ? "WSEN " : ""), (data & 0x08 ? "RISING " : ""),
299                         (data & 0x10 ? "FALLING " : ""), (data & 0x20 ? "EVERYWORD" : ""),
300                         m68k_get_reg(NULL, M68K_REG_PC));
301         }
302 }
303
304
305 //
306 // LRXD/RRXD/SSTAT ($F1A148/4C/50)
307 //
308 uint8 DACReadByte(uint32 offset, uint32 who/*= UNKNOWN*/)
309 {
310 //      WriteLog("DAC: %s reading byte from %08X\n", whoName[who], offset);
311         return 0xFF;
312 }
313
314
315 //static uint16 fakeWord = 0;
316 uint16 DACReadWord(uint32 offset, uint32 who/*= UNKNOWN*/)
317 {
318 //      WriteLog("DAC: %s reading word from %08X\n", whoName[who], offset);
319 //      return 0xFFFF;
320 //      WriteLog("DAC: %s reading WORD %04X from %08X\n", whoName[who], fakeWord, offset);
321 //      return fakeWord++;
322 //NOTE: This only works if a bunch of things are set in BUTCH which we currently don't
323 //      check for. !!! FIX !!!
324 // Partially fixed: We check for I2SCNTRL in the JERRY I2S routine...
325 //      return GetWordFromButchSSI(offset, who);
326         if (offset == LRXD || offset == RRXD)
327                 return 0x0000;
328         else if (offset == LRXD + 2)
329                 return lrxd;
330         else if (offset == RRXD + 2)
331                 return rrxd;
332
333         return 0xFFFF;  // May need SSTAT as well... (but may be a Jaguar II only feature)
334 }