spu: some major reverb refactoring
[pcsx_rearmed.git] / plugins / dfsound / spu.c
CommitLineData
ef79bbde
P
1/***************************************************************************
2 spu.c - description
3 -------------------
4 begin : Wed May 15 2002
5 copyright : (C) 2002 by Pete Bernert
6 email : BlackDove@addcom.de
07a6dd2c 7
8 Portions (C) GraÅžvydas "notaz" Ignotas, 2010-2011
9
ef79bbde
P
10 ***************************************************************************/
11/***************************************************************************
12 * *
13 * This program is free software; you can redistribute it and/or modify *
14 * it under the terms of the GNU General Public License as published by *
15 * the Free Software Foundation; either version 2 of the License, or *
16 * (at your option) any later version. See also the license.txt file for *
17 * additional informations. *
18 * *
19 ***************************************************************************/
20
21#include "stdafx.h"
22
23#define _IN_SPU
24
25#include "externals.h"
3fc2a4c2 26#include "registers.h"
ef79bbde
P
27#include "cfg.h"
28#include "dsoundoss.h"
29#include "regs.h"
30
31#ifdef ENABLE_NLS
32#include <libintl.h>
33#include <locale.h>
34#define _(x) gettext(x)
35#define N_(x) (x)
36#else
37#define _(x) (x)
38#define N_(x) (x)
39#endif
40
1775933a 41#ifdef __arm__
42 #define ssat32_to_16(v) \
43 asm("ssat %0,#16,%1" : "=r" (v) : "r" (v))
44#else
45 #define ssat32_to_16(v) do { \
46 if (v < -32768) v = -32768; \
47 else if (v > 32767) v = 32767; \
48 } while (0)
49#endif
50
6d866bb7 51/*
ef79bbde
P
52#if defined (USEMACOSX)
53static char * libraryName = N_("Mac OS X Sound");
54#elif defined (USEALSA)
55static char * libraryName = N_("ALSA Sound");
56#elif defined (USEOSS)
57static char * libraryName = N_("OSS Sound");
58#elif defined (USESDL)
59static char * libraryName = N_("SDL Sound");
60#elif defined (USEPULSEAUDIO)
61static char * libraryName = N_("PulseAudio Sound");
62#else
63static char * libraryName = N_("NULL Sound");
64#endif
65
66static char * libraryInfo = N_("P.E.Op.S. Sound Driver V1.7\nCoded by Pete Bernert and the P.E.Op.S. team\n");
6d866bb7 67*/
ef79bbde
P
68
69// globals
70
71// psx buffer / addresses
72
73unsigned short regArea[10000];
74unsigned short spuMem[256*1024];
75unsigned char * spuMemC;
76unsigned char * pSpuIrq=0;
77unsigned char * pSpuBuffer;
78unsigned char * pMixIrq=0;
79
80// user settings
81
82int iVolume=3;
83int iXAPitch=1;
84int iUseTimer=2;
85int iSPUIRQWait=1;
86int iDebugMode=0;
87int iRecordMode=0;
88int iUseReverb=2;
89int iUseInterpolation=2;
ef79bbde
P
90
91// MAIN infos struct for each channel
92
93SPUCHAN s_chan[MAXCHAN+1]; // channel + 1 infos (1 is security for fmod handling)
94REVERBInfo rvb;
95
96unsigned long dwNoiseVal=1; // global noise generator
97int iSpuAsyncWait=0;
98
99unsigned short spuCtrl=0; // some vars to store psx reg infos
100unsigned short spuStat=0;
101unsigned short spuIrq=0;
102unsigned long spuAddr=0xffffffff; // address into spu mem
103int bEndThread=0; // thread handlers
104int bThreadEnded=0;
105int bSpuInit=0;
106int bSPUIsOpen=0;
107
108static pthread_t thread = (pthread_t)-1; // thread id (linux)
109
110unsigned long dwNewChannel=0; // flags for faster testing, if new channel starts
6d866bb7 111unsigned long dwChannelOn=0;
3fc2a4c2 112unsigned long dwPendingChanOff=0;
ef79bbde
P
113
114void (CALLBACK *irqCallback)(void)=0; // func of main emu, called on spu irq
115void (CALLBACK *cddavCallback)(unsigned short,unsigned short)=0;
116
117// certain globals (were local before, but with the new timeproc I need em global)
118
6d866bb7 119static const int f[8][2] = { { 0, 0 },
ef79bbde
P
120 { 60, 0 },
121 { 115, -52 },
122 { 98, -55 },
123 { 122, -60 } };
1ab7621a 124int ChanBuf[NSSIZE];
97ea4077 125int SSumLR[NSSIZE*2];
ef79bbde
P
126int iFMod[NSSIZE];
127int iCycle = 0;
128short * pS;
129
130int lastch=-1; // last channel processed on spu irq in timer mode
131static int lastns=0; // last ns pos
132static int iSecureStart=0; // secure start counter
133
134////////////////////////////////////////////////////////////////////////
135// CODE AREA
136////////////////////////////////////////////////////////////////////////
137
138// dirty inline func includes
139
140#include "reverb.c"
141#include "adsr.c"
142
143////////////////////////////////////////////////////////////////////////
144// helpers for simple interpolation
145
146//
147// easy interpolation on upsampling, no special filter, just "Pete's common sense" tm
148//
149// instead of having n equal sample values in a row like:
150// ____
151// |____
152//
153// we compare the current delta change with the next delta change.
154//
155// if curr_delta is positive,
156//
157// - and next delta is smaller (or changing direction):
158// \.
159// -__
160//
161// - and next delta significant (at least twice) bigger:
162// --_
163// \.
164//
165// - and next delta is nearly same:
166// \.
167// \.
168//
169//
170// if curr_delta is negative,
171//
172// - and next delta is smaller (or changing direction):
173// _--
174// /
175//
176// - and next delta significant (at least twice) bigger:
177// /
178// __-
179//
180// - and next delta is nearly same:
181// /
182// /
183//
184
185
186INLINE void InterpolateUp(int ch)
187{
188 if(s_chan[ch].SB[32]==1) // flag == 1? calc step and set flag... and don't change the value in this pass
189 {
190 const int id1=s_chan[ch].SB[30]-s_chan[ch].SB[29]; // curr delta to next val
191 const int id2=s_chan[ch].SB[31]-s_chan[ch].SB[30]; // and next delta to next-next val :)
192
193 s_chan[ch].SB[32]=0;
194
195 if(id1>0) // curr delta positive
196 {
197 if(id2<id1)
198 {s_chan[ch].SB[28]=id1;s_chan[ch].SB[32]=2;}
199 else
200 if(id2<(id1<<1))
201 s_chan[ch].SB[28]=(id1*s_chan[ch].sinc)/0x10000L;
202 else
203 s_chan[ch].SB[28]=(id1*s_chan[ch].sinc)/0x20000L;
204 }
205 else // curr delta negative
206 {
207 if(id2>id1)
208 {s_chan[ch].SB[28]=id1;s_chan[ch].SB[32]=2;}
209 else
210 if(id2>(id1<<1))
211 s_chan[ch].SB[28]=(id1*s_chan[ch].sinc)/0x10000L;
212 else
213 s_chan[ch].SB[28]=(id1*s_chan[ch].sinc)/0x20000L;
214 }
215 }
216 else
217 if(s_chan[ch].SB[32]==2) // flag 1: calc step and set flag... and don't change the value in this pass
218 {
219 s_chan[ch].SB[32]=0;
220
221 s_chan[ch].SB[28]=(s_chan[ch].SB[28]*s_chan[ch].sinc)/0x20000L;
222 if(s_chan[ch].sinc<=0x8000)
223 s_chan[ch].SB[29]=s_chan[ch].SB[30]-(s_chan[ch].SB[28]*((0x10000/s_chan[ch].sinc)-1));
224 else s_chan[ch].SB[29]+=s_chan[ch].SB[28];
225 }
226 else // no flags? add bigger val (if possible), calc smaller step, set flag1
227 s_chan[ch].SB[29]+=s_chan[ch].SB[28];
228}
229
230//
231// even easier interpolation on downsampling, also no special filter, again just "Pete's common sense" tm
232//
233
234INLINE void InterpolateDown(int ch)
235{
236 if(s_chan[ch].sinc>=0x20000L) // we would skip at least one val?
237 {
238 s_chan[ch].SB[29]+=(s_chan[ch].SB[30]-s_chan[ch].SB[29])/2; // add easy weight
239 if(s_chan[ch].sinc>=0x30000L) // we would skip even more vals?
240 s_chan[ch].SB[29]+=(s_chan[ch].SB[31]-s_chan[ch].SB[30])/2;// add additional next weight
241 }
242}
243
244////////////////////////////////////////////////////////////////////////
245// helpers for gauss interpolation
246
247#define gval0 (((short*)(&s_chan[ch].SB[29]))[gpos])
248#define gval(x) (((short*)(&s_chan[ch].SB[29]))[(gpos+x)&3])
249
250#include "gauss_i.h"
251
252////////////////////////////////////////////////////////////////////////
253
254#include "xa.c"
255
256////////////////////////////////////////////////////////////////////////
257// START SOUND... called by main thread to setup a new sound on a channel
258////////////////////////////////////////////////////////////////////////
259
260INLINE void StartSound(int ch)
261{
262 StartADSR(ch);
263 StartREVERB(ch);
264
b00afb77 265 // fussy timing issues - do in VoiceOn
266 //s_chan[ch].pCurr=s_chan[ch].pStart; // set sample start
267 //s_chan[ch].bStop=0;
268 //s_chan[ch].bOn=1;
ef79bbde
P
269
270 s_chan[ch].s_1=0; // init mixing vars
271 s_chan[ch].s_2=0;
272 s_chan[ch].iSBPos=28;
273
ef79bbde
P
274 s_chan[ch].SB[29]=0; // init our interpolation helpers
275 s_chan[ch].SB[30]=0;
276
277 if(iUseInterpolation>=2) // gauss interpolation?
278 {s_chan[ch].spos=0x30000L;s_chan[ch].SB[28]=0;} // -> start with more decoding
279 else {s_chan[ch].spos=0x10000L;s_chan[ch].SB[31]=0;} // -> no/simple interpolation starts with one 44100 decoding
280
281 dwNewChannel&=~(1<<ch); // clear new channel bit
282}
283
284////////////////////////////////////////////////////////////////////////
285// ALL KIND OF HELPERS
286////////////////////////////////////////////////////////////////////////
287
288INLINE void VoiceChangeFrequency(int ch)
289{
290 s_chan[ch].iUsedFreq=s_chan[ch].iActFreq; // -> take it and calc steps
291 s_chan[ch].sinc=s_chan[ch].iRawPitch<<4;
292 if(!s_chan[ch].sinc) s_chan[ch].sinc=1;
293 if(iUseInterpolation==1) s_chan[ch].SB[32]=1; // -> freq change in simle imterpolation mode: set flag
294}
295
296////////////////////////////////////////////////////////////////////////
297
07a6dd2c 298INLINE int FModChangeFrequency(int ch,int ns)
ef79bbde
P
299{
300 int NP=s_chan[ch].iRawPitch;
07a6dd2c 301 int sinc;
ef79bbde
P
302
303 NP=((32768L+iFMod[ns])*NP)/32768L;
304
305 if(NP>0x3fff) NP=0x3fff;
306 if(NP<0x1) NP=0x1;
307
308 NP=(44100L*NP)/(4096L); // calc frequency
309
310 s_chan[ch].iActFreq=NP;
311 s_chan[ch].iUsedFreq=NP;
07a6dd2c 312 sinc=(((NP/10)<<16)/4410);
313 if(!sinc) sinc=1;
ef79bbde 314 if(iUseInterpolation==1) // freq change in simple interpolation mode
07a6dd2c 315 s_chan[ch].SB[32]=1;
ef79bbde 316 iFMod[ns]=0;
07a6dd2c 317
318 return sinc;
ef79bbde
P
319}
320
321////////////////////////////////////////////////////////////////////////
322
323// noise handler... just produces some noise data
324// surely wrong... and no noise frequency (spuCtrl&0x3f00) will be used...
325// and sometimes the noise will be used as fmod modulation... pfff
326
327INLINE int iGetNoiseVal(int ch)
328{
329 int fa;
330
331 if((dwNoiseVal<<=1)&0x80000000L)
332 {
333 dwNoiseVal^=0x0040001L;
334 fa=((dwNoiseVal>>2)&0x7fff);
335 fa=-fa;
336 }
337 else fa=(dwNoiseVal>>2)&0x7fff;
338
339 // mmm... depending on the noise freq we allow bigger/smaller changes to the previous val
340 fa=s_chan[ch].iOldNoise+((fa-s_chan[ch].iOldNoise)/((0x001f-((spuCtrl&0x3f00)>>9))+1));
341 if(fa>32767L) fa=32767L;
342 if(fa<-32767L) fa=-32767L;
343 s_chan[ch].iOldNoise=fa;
344
345 if(iUseInterpolation<2) // no gauss/cubic interpolation?
346 s_chan[ch].SB[29] = fa; // -> store noise val in "current sample" slot
347 return fa;
348}
349
350////////////////////////////////////////////////////////////////////////
351
352INLINE void StoreInterpolationVal(int ch,int fa)
353{
354 if(s_chan[ch].bFMod==2) // fmod freq channel
355 s_chan[ch].SB[29]=fa;
356 else
357 {
358 if((spuCtrl&0x4000)==0) fa=0; // muted?
359 else // else adjust
360 {
361 if(fa>32767L) fa=32767L;
362 if(fa<-32767L) fa=-32767L;
363 }
364
365 if(iUseInterpolation>=2) // gauss/cubic interpolation
366 {
367 int gpos = s_chan[ch].SB[28];
368 gval0 = fa;
369 gpos = (gpos+1) & 3;
370 s_chan[ch].SB[28] = gpos;
371 }
372 else
373 if(iUseInterpolation==1) // simple interpolation
374 {
375 s_chan[ch].SB[28] = 0;
376 s_chan[ch].SB[29] = s_chan[ch].SB[30]; // -> helpers for simple linear interpolation: delay real val for two slots, and calc the two deltas, for a 'look at the future behaviour'
377 s_chan[ch].SB[30] = s_chan[ch].SB[31];
378 s_chan[ch].SB[31] = fa;
379 s_chan[ch].SB[32] = 1; // -> flag: calc new interolation
380 }
381 else s_chan[ch].SB[29]=fa; // no interpolation
382 }
383}
384
385////////////////////////////////////////////////////////////////////////
386
387INLINE int iGetInterpolationVal(int ch)
388{
389 int fa;
390
391 if(s_chan[ch].bFMod==2) return s_chan[ch].SB[29];
392
393 switch(iUseInterpolation)
394 {
395 //--------------------------------------------------//
396 case 3: // cubic interpolation
397 {
398 long xd;int gpos;
399 xd = ((s_chan[ch].spos) >> 1)+1;
400 gpos = s_chan[ch].SB[28];
401
402 fa = gval(3) - 3*gval(2) + 3*gval(1) - gval0;
403 fa *= (xd - (2<<15)) / 6;
404 fa >>= 15;
405 fa += gval(2) - gval(1) - gval(1) + gval0;
406 fa *= (xd - (1<<15)) >> 1;
407 fa >>= 15;
408 fa += gval(1) - gval0;
409 fa *= xd;
410 fa >>= 15;
411 fa = fa + gval0;
412
413 } break;
414 //--------------------------------------------------//
415 case 2: // gauss interpolation
416 {
417 int vl, vr;int gpos;
418 vl = (s_chan[ch].spos >> 6) & ~3;
419 gpos = s_chan[ch].SB[28];
420 vr=(gauss[vl]*gval0)&~2047;
421 vr+=(gauss[vl+1]*gval(1))&~2047;
422 vr+=(gauss[vl+2]*gval(2))&~2047;
423 vr+=(gauss[vl+3]*gval(3))&~2047;
424 fa = vr>>11;
425 } break;
426 //--------------------------------------------------//
427 case 1: // simple interpolation
428 {
429 if(s_chan[ch].sinc<0x10000L) // -> upsampling?
430 InterpolateUp(ch); // --> interpolate up
431 else InterpolateDown(ch); // --> else down
432 fa=s_chan[ch].SB[29];
433 } break;
434 //--------------------------------------------------//
435 default: // no interpolation
436 {
437 fa=s_chan[ch].SB[29];
438 } break;
439 //--------------------------------------------------//
440 }
441
442 return fa;
443}
444
3fc2a4c2 445static void do_irq(void)
446{
447 if(!(spuStat & STAT_IRQ))
448 {
449 spuStat |= STAT_IRQ;
450 if(irqCallback) irqCallback();
451 }
452}
453
e11ae5c5 454static int decode_block(int ch)
455{
456 unsigned char *start;
457 unsigned int nSample;
458 int predict_nr,shift_factor,flags,d,s;
459 int fa,s_1,s_2;
460 int ret = 0;
461
462 s_chan[ch].iSBPos=0;
463
464 start=s_chan[ch].pCurr; // set up the current pos
3fc2a4c2 465 if(start == (unsigned char*)-1 || // special "stop" sign
466 (dwPendingChanOff&(1<<ch)))
e11ae5c5 467 {
468 dwChannelOn&=~(1<<ch); // -> turn everything off
3fc2a4c2 469 dwPendingChanOff&=~(1<<ch);
e11ae5c5 470 s_chan[ch].bStop=1;
471 s_chan[ch].ADSRX.EnvelopeVol=0;
472 return 0; // -> and done for this channel
473 }
474
3fc2a4c2 475 //////////////////////////////////////////// irq check
476
477 if(spuCtrl&CTRL_IRQ)
478 {
479 if(pSpuIrq == start) // irq address reached?
480 {
481 do_irq(); // -> call main emu
482 ret = 1;
483 }
484 }
e11ae5c5 485
486 s_1=s_chan[ch].s_1;
487 s_2=s_chan[ch].s_2;
488
489 predict_nr=(int)*start;start++;
490 shift_factor=predict_nr&0xf;
491 predict_nr >>= 4;
492 flags=(int)*start;start++;
493
494 // -------------------------------------- //
495
496 for (nSample=0;nSample<28;start++)
497 {
498 d=(int)*start;
499 s=((d&0xf)<<12);
500 if(s&0x8000) s|=0xffff0000;
501
502 fa=(s >> shift_factor);
503 fa=fa + ((s_1 * f[predict_nr][0])>>6) + ((s_2 * f[predict_nr][1])>>6);
504 s_2=s_1;s_1=fa;
505 s=((d & 0xf0) << 8);
506
507 s_chan[ch].SB[nSample++]=fa;
508
509 if(s&0x8000) s|=0xffff0000;
510 fa=(s>>shift_factor);
511 fa=fa + ((s_1 * f[predict_nr][0])>>6) + ((s_2 * f[predict_nr][1])>>6);
512 s_2=s_1;s_1=fa;
513
514 s_chan[ch].SB[nSample++]=fa;
515 }
516
e11ae5c5 517 //////////////////////////////////////////// flag handler
518
519 if((flags&4) && (!s_chan[ch].bIgnoreLoop))
520 s_chan[ch].pLoop=start-16; // loop adress
521
522 if(flags&1) // 1: stop/loop
523 {
3fc2a4c2 524 if(!(flags&2))
525 dwPendingChanOff|=1<<ch;
526
527 start = s_chan[ch].pLoop;
e11ae5c5 528 }
529
530 if (start - spuMemC >= 0x80000)
531 start = (unsigned char*)-1;
532
533 s_chan[ch].pCurr=start; // store values for next cycle
534 s_chan[ch].s_1=s_1;
535 s_chan[ch].s_2=s_2;
536
537 return ret;
538}
539
07a6dd2c 540// do block, but ignore sample data
541static int skip_block(int ch)
542{
543 unsigned char *start = s_chan[ch].pCurr;
544 int flags = start[1];
545 int ret = 0;
546
547 // Tron Bonne hack, probably wrong (could be wrong memory contents..)
548 if(flags & ~7) flags = 0;
549
550 if(start == pSpuIrq)
551 {
552 do_irq();
553 ret = 1;
554 }
555
556 if((flags & 4) && !s_chan[ch].bIgnoreLoop)
557 s_chan[ch].pLoop=start;
558
559 s_chan[ch].pCurr += 16;
560
561 if(flags & 1)
562 s_chan[ch].pCurr = s_chan[ch].pLoop;
563
564 return ret;
565}
566
567#define make_do_samples(name, fmod_code, interp_start, interp1_code, interp2_code, interp_end) \
568static int do_samples_##name(int ch, int ns, int ns_to) \
569{ \
570 int sinc = s_chan[ch].sinc; \
571 int spos = s_chan[ch].spos; \
572 int ret = -1; \
573 int d, fa; \
574 interp_start; \
575 \
576 for (; ns < ns_to; ns++) \
577 { \
578 fmod_code; \
579 \
580 while (spos >= 0x10000) \
581 { \
582 if(s_chan[ch].iSBPos == 28) \
583 { \
584 d = decode_block(ch); \
585 if(d && iSPUIRQWait) \
586 { \
587 ret = ns; \
588 goto out; \
589 } \
590 } \
591 \
592 fa = s_chan[ch].SB[s_chan[ch].iSBPos++]; \
593 interp1_code; \
594 spos -= 0x10000; \
595 } \
596 \
597 interp2_code; \
598 spos += sinc; \
599 } \
600 \
601out: \
602 s_chan[ch].sinc = sinc; \
603 s_chan[ch].spos = spos; \
604 interp_end; \
605 \
606 return ret; \
607}
608
609#define fmod_recv_check \
610 if(s_chan[ch].bFMod==1 && iFMod[ns]) \
611 sinc = FModChangeFrequency(ch,ns)
612
613make_do_samples(default, fmod_recv_check, ,
614 StoreInterpolationVal(ch, fa),
615 ChanBuf[ns] = iGetInterpolationVal(ch), )
616make_do_samples(noint, , fa = s_chan[ch].SB[29], , ChanBuf[ns] = fa, s_chan[ch].SB[29] = fa)
617
618#define simple_interp_store \
619 s_chan[ch].SB[28] = 0; \
620 s_chan[ch].SB[29] = s_chan[ch].SB[30]; \
621 s_chan[ch].SB[30] = s_chan[ch].SB[31]; \
622 s_chan[ch].SB[31] = fa; \
623 s_chan[ch].SB[32] = 1
624
625#define simple_interp_get \
626 if(sinc<0x10000) /* -> upsampling? */ \
627 InterpolateUp(ch); /* --> interpolate up */ \
628 else InterpolateDown(ch); /* --> else down */ \
629 ChanBuf[ns] = s_chan[ch].SB[29]
630
631make_do_samples(simple, , ,
632 simple_interp_store, simple_interp_get, )
633
634static int do_samples_noise(int ch, int ns, int ns_to)
635{
636 s_chan[ch].spos += s_chan[ch].sinc * (ns_to - ns);
637 while (s_chan[ch].spos >= 28*0x10000)
638 {
639 skip_block(ch);
640 s_chan[ch].spos -= 28*0x10000;
641 }
642
643 for (; ns < ns_to; ns++)
644 ChanBuf[ns] = iGetNoiseVal(ch);
645
646 return -1;
647}
648
ef79bbde
P
649////////////////////////////////////////////////////////////////////////
650// MAIN SPU FUNCTION
651// here is the main job handler... thread, timer or direct func call
652// basically the whole sound processing is done in this fat func!
653////////////////////////////////////////////////////////////////////////
654
655// 5 ms waiting phase, if buffer is full and no new sound has to get started
656// .. can be made smaller (smallest val: 1 ms), but bigger waits give
657// better performance
658
659#define PAUSE_W 5
660#define PAUSE_L 5000
661
662////////////////////////////////////////////////////////////////////////
663
664static void *MAINThread(void *arg)
665{
07a6dd2c 666 int ns,ns_from,ns_to;
cfe71c00 667#if !defined(_MACOSX) && !defined(__arm__)
ef79bbde
P
668 int voldiv = iVolume;
669#else
670 const int voldiv = 2;
671#endif
e11ae5c5 672 int ch,d;
ef79bbde
P
673 int bIRQReturn=0;
674
675 while(!bEndThread) // until we are shutting down
676 {
677 // ok, at the beginning we are looking if there is
678 // enuff free place in the dsound/oss buffer to
679 // fill in new data, or if there is a new channel to start.
680 // if not, we wait (thread) or return (timer/spuasync)
681 // until enuff free place is available/a new channel gets
682 // started
683
684 if(dwNewChannel) // new channel should start immedately?
685 { // (at least one bit 0 ... MAXCHANNEL is set?)
686 iSecureStart++; // -> set iSecure
687 if(iSecureStart>5) iSecureStart=0; // (if it is set 5 times - that means on 5 tries a new samples has been started - in a row, we will reset it, to give the sound update a chance)
688 }
689 else iSecureStart=0; // 0: no new channel should start
690
691 while(!iSecureStart && !bEndThread && // no new start? no thread end?
692 (SoundGetBytesBuffered()>TESTSIZE)) // and still enuff data in sound buffer?
693 {
694 iSecureStart=0; // reset secure
695
696 if(iUseTimer) return 0; // linux no-thread mode? bye
697 usleep(PAUSE_L); // else sleep for x ms (linux)
698
699 if(dwNewChannel) iSecureStart=1; // if a new channel kicks in (or, of course, sound buffer runs low), we will leave the loop
700 }
701
702 //--------------------------------------------------// continue from irq handling in timer mode?
703
8680e822 704 ns_from=0;
705 ns_to=NSSIZE;
706 ch=0;
ef79bbde
P
707 if(lastch>=0) // will be -1 if no continue is pending
708 {
e11ae5c5 709 ch=lastch; ns_from=lastns; lastch=-1; // -> setup all kind of vars to continue
ef79bbde
P
710 }
711
712 //--------------------------------------------------//
713 //- main channel loop -//
714 //--------------------------------------------------//
715 {
8680e822 716 for(;ch<MAXCHAN;ch++) // loop em all... we will collect 1 ms of sound of each playing channel
ef79bbde 717 {
6d866bb7 718 if(dwNewChannel&(1<<ch)) StartSound(ch); // start new sound
719 if(!(dwChannelOn&(1<<ch))) continue; // channel not playing? next
ef79bbde
P
720
721 if(s_chan[ch].iActFreq!=s_chan[ch].iUsedFreq) // new psx frequency?
722 VoiceChangeFrequency(ch);
723
07a6dd2c 724 if(s_chan[ch].bNoise)
725 d=do_samples_noise(ch, ns_from, ns_to);
726 else if(s_chan[ch].bFMod==2 || (s_chan[ch].bFMod==0 && iUseInterpolation==0))
727 d=do_samples_noint(ch, ns_from, ns_to);
728 else if(s_chan[ch].bFMod==0 && iUseInterpolation==1)
729 d=do_samples_simple(ch, ns_from, ns_to);
730 else
731 d=do_samples_default(ch, ns_from, ns_to);
732 if(d>=0)
ef79bbde 733 {
07a6dd2c 734 bIRQReturn=1;
735 lastch=ch;
736 lastns=ns_to=d;
1ab7621a 737 }
ef79bbde 738
1ab7621a 739 MixADSR(ch, ns_from, ns_to);
740
741 if(s_chan[ch].bFMod==2) // fmod freq channel
742 memcpy(iFMod, ChanBuf, sizeof(iFMod));
1775933a 743 else
1ab7621a 744 {
1775933a 745 int lv=s_chan[ch].iLeftVolume;
746 int rv=s_chan[ch].iRightVolume;
ef79bbde 747
1775933a 748 for(ns=ns_from;ns<ns_to;ns++)
ef79bbde 749 {
1775933a 750 int sval = ChanBuf[ns];
751 int l, r;
752
ef79bbde
P
753 //////////////////////////////////////////////
754 // ok, left/right sound volume (psx volume goes from 0 ... 0x3fff)
755
1775933a 756 l=(sval*lv)>>14;
757 r=(sval*rv)>>14;
758 SSumLR[ns*2] +=l;
759 SSumLR[ns*2+1]+=r;
ef79bbde
P
760
761 //////////////////////////////////////////////
762 // now let us store sound data for reverb
763
1775933a 764 if(s_chan[ch].bRVBActive) StoreREVERB(ch,ns,l,r);
ef79bbde 765 }
ef79bbde 766 }
ef79bbde
P
767 }
768 }
769
78c60846 770 // advance "stopped" channels that can cause irqs
771 // (all chans are always playing on the real thing..)
772 if(!bIRQReturn && (spuCtrl&CTRL_IRQ))
773 for(ch=0;ch<MAXCHAN;ch++)
774 {
775 if(dwChannelOn&(1<<ch)) continue; // already handled
776 if(s_chan[ch].pCurr == (unsigned char *)-1)
777 continue;
778 if(s_chan[ch].pCurr > pSpuIrq && s_chan[ch].pLoop > pSpuIrq)
779 continue;
780
781 if(s_chan[ch].iActFreq!=s_chan[ch].iUsedFreq) // new psx frequency?
782 VoiceChangeFrequency(ch);
783
784 s_chan[ch].spos += s_chan[ch].sinc * NSSIZE;
785 while(s_chan[ch].spos >= 28 * 0x10000)
786 {
787 unsigned char *start=s_chan[ch].pCurr;
78c60846 788
07a6dd2c 789 bIRQReturn |= skip_block(ch);
790 if(start == s_chan[ch].pCurr)
78c60846 791 {
792 // looping on self
793 s_chan[ch].pCurr=(unsigned char *)-1;
794 break;
795 }
796
78c60846 797 s_chan[ch].spos -= 28 * 0x10000;
798 }
799 }
800
e11ae5c5 801 if(bIRQReturn && iSPUIRQWait) // special return for "spu irq - wait for cpu action"
8680e822 802 {
e11ae5c5 803 iSpuAsyncWait=1;
8680e822 804 bIRQReturn=0;
805 if(iUseTimer!=2)
806 {
807 DWORD dwWatchTime=timeGetTime_spu()+2500;
808
809 while(iSpuAsyncWait && !bEndThread &&
810 timeGetTime_spu()<dwWatchTime)
811 usleep(1000L);
812 continue;
813 }
814 else
815 {
816 return 0;
817 }
818 }
819
820
ef79bbde
P
821 //---------------------------------------------------//
822 //- here we have another 1 ms of sound data
823 //---------------------------------------------------//
824 // mix XA infos (if any)
825
826 MixXA();
827
828 ///////////////////////////////////////////////////////
829 // mix all channels (including reverb) into one buffer
830
1775933a 831 if(iUseReverb)
832 REVERBDo();
833
834 if((spuCtrl&0x4000)==0) // muted? (rare, don't optimize for this)
835 {
836 memset(pS, 0, NSSIZE * 2 * sizeof(pS[0]));
837 pS += NSSIZE*2;
838 }
839 else
97ea4077 840 for (ns = 0; ns < NSSIZE*2; )
ef79bbde 841 {
97ea4077 842 d = SSumLR[ns] / voldiv; SSumLR[ns] = 0;
1775933a 843 ssat32_to_16(d);
ef79bbde 844 *pS++ = d;
97ea4077 845 ns++;
ef79bbde 846
97ea4077 847 d = SSumLR[ns] / voldiv; SSumLR[ns] = 0;
1775933a 848 ssat32_to_16(d);
ef79bbde 849 *pS++ = d;
97ea4077 850 ns++;
ef79bbde
P
851 }
852
853 //////////////////////////////////////////////////////
854 // special irq handling in the decode buffers (0x0000-0x1000)
855 // we know:
856 // the decode buffers are located in spu memory in the following way:
857 // 0x0000-0x03ff CD audio left
858 // 0x0400-0x07ff CD audio right
859 // 0x0800-0x0bff Voice 1
860 // 0x0c00-0x0fff Voice 3
861 // and decoded data is 16 bit for one sample
862 // we assume:
863 // even if voices 1/3 are off or no cd audio is playing, the internal
864 // play positions will move on and wrap after 0x400 bytes.
865 // Therefore: we just need a pointer from spumem+0 to spumem+3ff, and
866 // increase this pointer on each sample by 2 bytes. If this pointer
867 // (or 0x400 offsets of this pointer) hits the spuirq address, we generate
868 // an IRQ. Only problem: the "wait for cpu" option is kinda hard to do here
869 // in some of Peops timer modes. So: we ignore this option here (for now).
870
3fc2a4c2 871 if(pMixIrq)
ef79bbde
P
872 {
873 for(ns=0;ns<NSSIZE;ns++)
874 {
875 if((spuCtrl&0x40) && pSpuIrq && pSpuIrq<spuMemC+0x1000)
876 {
877 for(ch=0;ch<4;ch++)
878 {
879 if(pSpuIrq>=pMixIrq+(ch*0x400) && pSpuIrq<pMixIrq+(ch*0x400)+2)
3fc2a4c2 880 do_irq();
ef79bbde
P
881 }
882 }
883 pMixIrq+=2;if(pMixIrq>spuMemC+0x3ff) pMixIrq=spuMemC;
884 }
885 }
886
887 InitREVERB();
888
889 // feed the sound
890 // wanna have around 1/60 sec (16.666 ms) updates
891 if (iCycle++ > 16)
892 {
893 SoundFeedStreamData((unsigned char *)pSpuBuffer,
894 ((unsigned char *)pS) - ((unsigned char *)pSpuBuffer));
895 pS = (short *)pSpuBuffer;
896 iCycle = 0;
897 }
898 }
899
900 // end of big main loop...
901
902 bThreadEnded = 1;
903
904 return 0;
905}
906
907// SPU ASYNC... even newer epsxe func
908// 1 time every 'cycle' cycles... harhar
909
910void CALLBACK SPUasync(unsigned long cycle)
911{
912 if(iSpuAsyncWait)
913 {
914 iSpuAsyncWait++;
17ed0d69 915 if(iSpuAsyncWait<=16) return;
ef79bbde
P
916 iSpuAsyncWait=0;
917 }
918
919 if(iUseTimer==2) // special mode, only used in Linux by this spu (or if you enable the experimental Windows mode)
920 {
921 if(!bSpuInit) return; // -> no init, no call
922
923 MAINThread(0); // -> linux high-compat mode
17ed0d69 924
925 // abuse iSpuAsyncWait mechanism to reduce calls to above function
926 // to make it do larger chunks
927 // note: doing it less often than once per frame causes skips
928 iSpuAsyncWait=1;
ef79bbde
P
929 }
930}
931
932// SPU UPDATE... new epsxe func
933// 1 time every 32 hsync lines
934// (312/32)x50 in pal
935// (262/32)x60 in ntsc
936
937// since epsxe 1.5.2 (linux) uses SPUupdate, not SPUasync, I will
938// leave that func in the linux port, until epsxe linux is using
939// the async function as well
940
941void CALLBACK SPUupdate(void)
942{
943 SPUasync(0);
944}
945
946// XA AUDIO
947
948void CALLBACK SPUplayADPCMchannel(xa_decode_t *xap)
949{
950 if(!xap) return;
951 if(!xap->freq) return; // no xa freq ? bye
952
953 FeedXA(xap); // call main XA feeder
954}
955
956// CDDA AUDIO
957void CALLBACK SPUplayCDDAchannel(short *pcm, int nbytes)
958{
959 if (!pcm) return;
960 if (nbytes<=0) return;
961
962 FeedCDDA((unsigned char *)pcm, nbytes);
963}
964
965// SETUPTIMER: init of certain buffers and threads/timers
966void SetupTimer(void)
967{
97ea4077 968 memset(SSumLR,0,sizeof(SSumLR)); // init some mixing buffers
ef79bbde
P
969 memset(iFMod,0,NSSIZE*sizeof(int));
970 pS=(short *)pSpuBuffer; // setup soundbuffer pointer
971
972 bEndThread=0; // init thread vars
973 bThreadEnded=0;
974 bSpuInit=1; // flag: we are inited
975
976 if(!iUseTimer) // linux: use thread
977 {
978 pthread_create(&thread, NULL, MAINThread, NULL);
979 }
980}
981
982// REMOVETIMER: kill threads/timers
983void RemoveTimer(void)
984{
985 bEndThread=1; // raise flag to end thread
986
987 if(!iUseTimer) // linux tread?
988 {
989 int i=0;
990 while(!bThreadEnded && i<2000) {usleep(1000L);i++;} // -> wait until thread has ended
991 if(thread!=(pthread_t)-1) {pthread_cancel(thread);thread=(pthread_t)-1;} // -> cancel thread anyway
992 }
993
994 bThreadEnded=0; // no more spu is running
995 bSpuInit=0;
996}
997
998// SETUPSTREAMS: init most of the spu buffers
999void SetupStreams(void)
1000{
1001 int i;
1002
1003 pSpuBuffer=(unsigned char *)malloc(32768); // alloc mixing buffer
1004
1005 if(iUseReverb==1) i=88200*2;
1006 else i=NSSIZE*2;
1007
1008 sRVBStart = (int *)malloc(i*4); // alloc reverb buffer
1009 memset(sRVBStart,0,i*4);
1010 sRVBEnd = sRVBStart + i;
1011 sRVBPlay = sRVBStart;
1012
1013 XAStart = // alloc xa buffer
1014 (uint32_t *)malloc(44100 * sizeof(uint32_t));
1015 XAEnd = XAStart + 44100;
1016 XAPlay = XAStart;
1017 XAFeed = XAStart;
1018
1019 CDDAStart = // alloc cdda buffer
1020 (uint32_t *)malloc(16384 * sizeof(uint32_t));
1021 CDDAEnd = CDDAStart + 16384;
1022 CDDAPlay = CDDAStart;
b8e744ce 1023 CDDAFeed = CDDAStart;
ef79bbde
P
1024
1025 for(i=0;i<MAXCHAN;i++) // loop sound channels
1026 {
1027// we don't use mutex sync... not needed, would only
1028// slow us down:
1029// s_chan[i].hMutex=CreateMutex(NULL,FALSE,NULL);
6d866bb7 1030 s_chan[i].ADSRX.SustainLevel = 0xf; // -> init sustain
ef79bbde
P
1031 s_chan[i].pLoop=spuMemC;
1032 s_chan[i].pStart=spuMemC;
1033 s_chan[i].pCurr=spuMemC;
1034 }
1035
1036 pMixIrq=spuMemC; // enable decoded buffer irqs by setting the address
1037}
1038
1039// REMOVESTREAMS: free most buffer
1040void RemoveStreams(void)
1041{
1042 free(pSpuBuffer); // free mixing buffer
1043 pSpuBuffer = NULL;
1044 free(sRVBStart); // free reverb buffer
1045 sRVBStart = NULL;
1046 free(XAStart); // free XA buffer
1047 XAStart = NULL;
1048 free(CDDAStart); // free CDDA buffer
1049 CDDAStart = NULL;
1050}
1051
1052// INIT/EXIT STUFF
1053
1054// SPUINIT: this func will be called first by the main emu
1055long CALLBACK SPUinit(void)
1056{
1057 spuMemC = (unsigned char *)spuMem; // just small setup
1058 memset((void *)&rvb, 0, sizeof(REVERBInfo));
1059 InitADSR();
1060
1061 iVolume = 3;
ef79bbde
P
1062 spuIrq = 0;
1063 spuAddr = 0xffffffff;
1064 bEndThread = 0;
1065 bThreadEnded = 0;
1066 spuMemC = (unsigned char *)spuMem;
1067 pMixIrq = 0;
1068 memset((void *)s_chan, 0, (MAXCHAN + 1) * sizeof(SPUCHAN));
1069 pSpuIrq = 0;
cdb31c95 1070 //iSPUIRQWait = 0;
ef79bbde
P
1071 lastch = -1;
1072
d7296e10 1073 //ReadConfigSPU(); // read user stuff
ef79bbde
P
1074 SetupStreams(); // prepare streaming
1075
1076 return 0;
1077}
1078
1079// SPUOPEN: called by main emu after init
1080long CALLBACK SPUopen(void)
1081{
1082 if (bSPUIsOpen) return 0; // security for some stupid main emus
1083
1084 SetupSound(); // setup sound (before init!)
1085 SetupTimer(); // timer for feeding data
1086
1087 bSPUIsOpen = 1;
1088
1089 return PSE_SPU_ERR_SUCCESS;
1090}
1091
1092// SPUCLOSE: called before shutdown
1093long CALLBACK SPUclose(void)
1094{
1095 if (!bSPUIsOpen) return 0; // some security
1096
1097 bSPUIsOpen = 0; // no more open
1098
1099 RemoveTimer(); // no more feeding
1100 RemoveSound(); // no more sound handling
1101
1102 return 0;
1103}
1104
1105// SPUSHUTDOWN: called by main emu on final exit
1106long CALLBACK SPUshutdown(void)
1107{
1108 SPUclose();
1109 RemoveStreams(); // no more streaming
1110
1111 return 0;
1112}
1113
1114// SPUTEST: we don't test, we are always fine ;)
1115long CALLBACK SPUtest(void)
1116{
1117 return 0;
1118}
1119
1120// SPUCONFIGURE: call config dialog
1121long CALLBACK SPUconfigure(void)
1122{
1123#ifdef _MACOSX
1124 DoConfiguration();
1125#else
ee849648 1126// StartCfgTool("CFG");
ef79bbde
P
1127#endif
1128 return 0;
1129}
1130
1131// SPUABOUT: show about window
1132void CALLBACK SPUabout(void)
1133{
1134#ifdef _MACOSX
1135 DoAbout();
1136#else
ee849648 1137// StartCfgTool("ABOUT");
ef79bbde
P
1138#endif
1139}
1140
1141// SETUP CALLBACKS
1142// this functions will be called once,
1143// passes a callback that should be called on SPU-IRQ/cdda volume change
1144void CALLBACK SPUregisterCallback(void (CALLBACK *callback)(void))
1145{
1146 irqCallback = callback;
1147}
1148
1149void CALLBACK SPUregisterCDDAVolume(void (CALLBACK *CDDAVcallback)(unsigned short,unsigned short))
1150{
1151 cddavCallback = CDDAVcallback;
1152}
1153
1154// COMMON PLUGIN INFO FUNCS
e906c010 1155/*
ef79bbde
P
1156char * CALLBACK PSEgetLibName(void)
1157{
1158 return _(libraryName);
1159}
1160
1161unsigned long CALLBACK PSEgetLibType(void)
1162{
1163 return PSE_LT_SPU;
1164}
1165
1166unsigned long CALLBACK PSEgetLibVersion(void)
1167{
1168 return (1 << 16) | (6 << 8);
1169}
1170
1171char * SPUgetLibInfos(void)
1172{
1173 return _(libraryInfo);
1174}
e906c010 1175*/
6d866bb7 1176
90f1d26c 1177// debug
1178void spu_get_debug_info(int *chans_out, int *fmod_chans_out, int *noise_chans_out)
1179{
1180 int ch = 0, fmod_chans = 0, noise_chans = 0;
1181
1182 for(;ch<MAXCHAN;ch++)
1183 {
1184 if (!(dwChannelOn & (1<<ch)))
1185 continue;
1186 if (s_chan[ch].bFMod == 2)
1187 fmod_chans |= 1 << ch;
1188 if (s_chan[ch].bNoise)
1189 noise_chans |= 1 << ch;
1190 }
1191
1192 *chans_out = dwChannelOn;
1193 *fmod_chans_out = fmod_chans;
1194 *noise_chans_out = noise_chans;
1195}
1196
6d866bb7 1197// vim:shiftwidth=1:expandtab