spu: some misc refactoring/cleanup
[pcsx_rearmed.git] / plugins / dfsound / spu.c
... / ...
CommitLineData
1/***************************************************************************
2 spu.c - description
3 -------------------
4 begin : Wed May 15 2002
5 copyright : (C) 2002 by Pete Bernert
6 email : BlackDove@addcom.de
7
8 Portions (C) GraÅžvydas "notaz" Ignotas, 2010-2011
9
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"
26#include "registers.h"
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
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
51/*
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");
67*/
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;
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
111unsigned long dwChannelOn=0;
112unsigned long dwPendingChanOff=0;
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
119static const int f[8][2] = { { 0, 0 },
120 { 60, 0 },
121 { 115, -52 },
122 { 98, -55 },
123 { 122, -60 } };
124int ChanBuf[NSSIZE];
125int SSumLR[NSSIZE*2];
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
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;
269
270 s_chan[ch].SB[26]=0; // init mixing vars
271 s_chan[ch].SB[27]=0;
272 s_chan[ch].iSBPos=28;
273
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
298INLINE int FModChangeFrequency(int ch,int ns)
299{
300 int NP=s_chan[ch].iRawPitch;
301 int sinc;
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;
312 sinc=(((NP/10)<<16)/4410);
313 if(!sinc) sinc=1;
314 if(iUseInterpolation==1) // freq change in simple interpolation mode
315 s_chan[ch].SB[32]=1;
316 iFMod[ns]=0;
317
318 return sinc;
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 ssat32_to_16(fa);
359
360 if(iUseInterpolation>=2) // gauss/cubic interpolation
361 {
362 int gpos = s_chan[ch].SB[28];
363 gval0 = fa;
364 gpos = (gpos+1) & 3;
365 s_chan[ch].SB[28] = gpos;
366 }
367 else
368 if(iUseInterpolation==1) // simple interpolation
369 {
370 s_chan[ch].SB[28] = 0;
371 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'
372 s_chan[ch].SB[30] = s_chan[ch].SB[31];
373 s_chan[ch].SB[31] = fa;
374 s_chan[ch].SB[32] = 1; // -> flag: calc new interolation
375 }
376 else s_chan[ch].SB[29]=fa; // no interpolation
377 }
378}
379
380////////////////////////////////////////////////////////////////////////
381
382INLINE int iGetInterpolationVal(int ch)
383{
384 int fa;
385
386 if(s_chan[ch].bFMod==2) return s_chan[ch].SB[29];
387
388 switch(iUseInterpolation)
389 {
390 //--------------------------------------------------//
391 case 3: // cubic interpolation
392 {
393 long xd;int gpos;
394 xd = ((s_chan[ch].spos) >> 1)+1;
395 gpos = s_chan[ch].SB[28];
396
397 fa = gval(3) - 3*gval(2) + 3*gval(1) - gval0;
398 fa *= (xd - (2<<15)) / 6;
399 fa >>= 15;
400 fa += gval(2) - gval(1) - gval(1) + gval0;
401 fa *= (xd - (1<<15)) >> 1;
402 fa >>= 15;
403 fa += gval(1) - gval0;
404 fa *= xd;
405 fa >>= 15;
406 fa = fa + gval0;
407
408 } break;
409 //--------------------------------------------------//
410 case 2: // gauss interpolation
411 {
412 int vl, vr;int gpos;
413 vl = (s_chan[ch].spos >> 6) & ~3;
414 gpos = s_chan[ch].SB[28];
415 vr=(gauss[vl]*gval0)&~2047;
416 vr+=(gauss[vl+1]*gval(1))&~2047;
417 vr+=(gauss[vl+2]*gval(2))&~2047;
418 vr+=(gauss[vl+3]*gval(3))&~2047;
419 fa = vr>>11;
420 } break;
421 //--------------------------------------------------//
422 case 1: // simple interpolation
423 {
424 if(s_chan[ch].sinc<0x10000L) // -> upsampling?
425 InterpolateUp(ch); // --> interpolate up
426 else InterpolateDown(ch); // --> else down
427 fa=s_chan[ch].SB[29];
428 } break;
429 //--------------------------------------------------//
430 default: // no interpolation
431 {
432 fa=s_chan[ch].SB[29];
433 } break;
434 //--------------------------------------------------//
435 }
436
437 return fa;
438}
439
440static void do_irq(void)
441{
442 if(!(spuStat & STAT_IRQ))
443 {
444 spuStat |= STAT_IRQ;
445 if(irqCallback) irqCallback();
446 }
447}
448
449static void decode_block_data(int *dest, const unsigned char *src, int predict_nr, int shift_factor)
450{
451 int nSample;
452 int fa, s_1, s_2, d, s;
453
454 s_1 = dest[27];
455 s_2 = dest[26];
456
457 for (nSample = 0; nSample < 28; src++)
458 {
459 d = (int)*src;
460 s = (int)(signed short)((d & 0x0f) << 12);
461
462 fa = s >> shift_factor;
463 fa += ((s_1 * f[predict_nr][0])>>6) + ((s_2 * f[predict_nr][1])>>6);
464 s_2=s_1;s_1=fa;
465
466 dest[nSample++] = fa;
467
468 s = (int)(signed short)((d & 0xf0) << 8);
469 fa = s >> shift_factor;
470 fa += ((s_1 * f[predict_nr][0])>>6) + ((s_2 * f[predict_nr][1])>>6);
471 s_2=s_1;s_1=fa;
472
473 dest[nSample++] = fa;
474 }
475}
476
477static int decode_block(int ch)
478{
479 unsigned char *start;
480 int predict_nr,shift_factor,flags;
481 int ret = 0;
482
483 start=s_chan[ch].pCurr; // set up the current pos
484 if(start == (unsigned char*)-1 || // special "stop" sign
485 (dwPendingChanOff&(1<<ch)))
486 {
487 dwChannelOn&=~(1<<ch); // -> turn everything off
488 dwPendingChanOff&=~(1<<ch);
489 s_chan[ch].bStop=1;
490 s_chan[ch].ADSRX.EnvelopeVol=0;
491 return 0; // -> and done for this channel
492 }
493
494 //////////////////////////////////////////// irq check
495
496 if(spuCtrl&CTRL_IRQ)
497 {
498 if(pSpuIrq == start) // irq address reached?
499 {
500 do_irq(); // -> call main emu
501 ret = 1;
502 }
503 }
504
505 predict_nr=(int)start[0];
506 shift_factor=predict_nr&0xf;
507 predict_nr >>= 4;
508
509 decode_block_data(s_chan[ch].SB, start + 2, predict_nr, shift_factor);
510
511 //////////////////////////////////////////// flag handler
512
513 flags=(int)start[1];
514 if(flags&4)
515 s_chan[ch].pLoop=start; // loop adress
516
517 start+=16;
518 if(flags&1) // 1: stop/loop
519 {
520 if(!(flags&2))
521 dwPendingChanOff|=1<<ch;
522
523 start = s_chan[ch].pLoop;
524 }
525
526 if (start - spuMemC >= 0x80000)
527 start = (unsigned char*)-1;
528
529 s_chan[ch].pCurr = start; // store values for next cycle
530
531 return ret;
532}
533
534// do block, but ignore sample data
535static int skip_block(int ch)
536{
537 unsigned char *start = s_chan[ch].pCurr;
538 int flags = start[1];
539 int ret = 0;
540
541 // Tron Bonne hack, probably wrong (could be wrong memory contents..)
542 if(flags & ~7) flags = 0;
543
544 if(start == pSpuIrq)
545 {
546 do_irq();
547 ret = 1;
548 }
549
550 if(flags & 4)
551 s_chan[ch].pLoop=start;
552
553 s_chan[ch].pCurr += 16;
554
555 if(flags & 1)
556 s_chan[ch].pCurr = s_chan[ch].pLoop;
557
558 return ret;
559}
560
561#define make_do_samples(name, fmod_code, interp_start, interp1_code, interp2_code, interp_end) \
562static int do_samples_##name(int ch, int ns, int ns_to) \
563{ \
564 int sinc = s_chan[ch].sinc; \
565 int spos = s_chan[ch].spos; \
566 int sbpos = s_chan[ch].iSBPos; \
567 int *SB = s_chan[ch].SB; \
568 int ret = -1; \
569 int d, fa; \
570 interp_start; \
571 \
572 for (; ns < ns_to; ns++) \
573 { \
574 fmod_code; \
575 \
576 while (spos >= 0x10000) \
577 { \
578 if(sbpos == 28) \
579 { \
580 sbpos = 0; \
581 d = decode_block(ch); \
582 if(d && iSPUIRQWait) \
583 { \
584 ret = ns; \
585 goto out; \
586 } \
587 } \
588 \
589 fa = SB[sbpos++]; \
590 interp1_code; \
591 spos -= 0x10000; \
592 } \
593 \
594 interp2_code; \
595 spos += sinc; \
596 } \
597 \
598out: \
599 s_chan[ch].sinc = sinc; \
600 s_chan[ch].spos = spos; \
601 s_chan[ch].iSBPos = sbpos; \
602 interp_end; \
603 \
604 return ret; \
605}
606
607#define fmod_recv_check \
608 if(s_chan[ch].bFMod==1 && iFMod[ns]) \
609 sinc = FModChangeFrequency(ch,ns)
610
611make_do_samples(default, fmod_recv_check, ,
612 StoreInterpolationVal(ch, fa),
613 ChanBuf[ns] = iGetInterpolationVal(ch), )
614make_do_samples(noint, , fa = s_chan[ch].SB[29], , ChanBuf[ns] = fa, s_chan[ch].SB[29] = fa)
615
616#define simple_interp_store \
617 s_chan[ch].SB[28] = 0; \
618 s_chan[ch].SB[29] = s_chan[ch].SB[30]; \
619 s_chan[ch].SB[30] = s_chan[ch].SB[31]; \
620 s_chan[ch].SB[31] = fa; \
621 s_chan[ch].SB[32] = 1
622
623#define simple_interp_get \
624 if(sinc<0x10000) /* -> upsampling? */ \
625 InterpolateUp(ch); /* --> interpolate up */ \
626 else InterpolateDown(ch); /* --> else down */ \
627 ChanBuf[ns] = s_chan[ch].SB[29]
628
629make_do_samples(simple, , ,
630 simple_interp_store, simple_interp_get, )
631
632static int do_samples_noise(int ch, int ns, int ns_to)
633{
634 s_chan[ch].spos += s_chan[ch].sinc * (ns_to - ns);
635 while (s_chan[ch].spos >= 28*0x10000)
636 {
637 skip_block(ch);
638 s_chan[ch].spos -= 28*0x10000;
639 }
640
641 for (; ns < ns_to; ns++)
642 ChanBuf[ns] = iGetNoiseVal(ch);
643
644 return -1;
645}
646
647////////////////////////////////////////////////////////////////////////
648// MAIN SPU FUNCTION
649// here is the main job handler... thread, timer or direct func call
650// basically the whole sound processing is done in this fat func!
651////////////////////////////////////////////////////////////////////////
652
653// 5 ms waiting phase, if buffer is full and no new sound has to get started
654// .. can be made smaller (smallest val: 1 ms), but bigger waits give
655// better performance
656
657#define PAUSE_W 5
658#define PAUSE_L 5000
659
660////////////////////////////////////////////////////////////////////////
661
662static void *MAINThread(void *arg)
663{
664 int ns,ns_from,ns_to;
665#if !defined(_MACOSX) && !defined(__arm__)
666 int voldiv = iVolume;
667#else
668 const int voldiv = 2;
669#endif
670 int ch,d;
671 int bIRQReturn=0;
672
673 while(!bEndThread) // until we are shutting down
674 {
675 // ok, at the beginning we are looking if there is
676 // enuff free place in the dsound/oss buffer to
677 // fill in new data, or if there is a new channel to start.
678 // if not, we wait (thread) or return (timer/spuasync)
679 // until enuff free place is available/a new channel gets
680 // started
681
682 if(dwNewChannel) // new channel should start immedately?
683 { // (at least one bit 0 ... MAXCHANNEL is set?)
684 iSecureStart++; // -> set iSecure
685 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)
686 }
687 else iSecureStart=0; // 0: no new channel should start
688
689 while(!iSecureStart && !bEndThread && // no new start? no thread end?
690 (SoundGetBytesBuffered()>TESTSIZE)) // and still enuff data in sound buffer?
691 {
692 iSecureStart=0; // reset secure
693
694 if(iUseTimer) return 0; // linux no-thread mode? bye
695 usleep(PAUSE_L); // else sleep for x ms (linux)
696
697 if(dwNewChannel) iSecureStart=1; // if a new channel kicks in (or, of course, sound buffer runs low), we will leave the loop
698 }
699
700 //--------------------------------------------------// continue from irq handling in timer mode?
701
702 ns_from=0;
703 ns_to=NSSIZE;
704 ch=0;
705 if(lastch>=0) // will be -1 if no continue is pending
706 {
707 ch=lastch; ns_from=lastns; lastch=-1; // -> setup all kind of vars to continue
708 }
709
710 //--------------------------------------------------//
711 //- main channel loop -//
712 //--------------------------------------------------//
713 {
714 for(;ch<MAXCHAN;ch++) // loop em all... we will collect 1 ms of sound of each playing channel
715 {
716 if(dwNewChannel&(1<<ch)) StartSound(ch); // start new sound
717 if(!(dwChannelOn&(1<<ch))) continue; // channel not playing? next
718
719 if(s_chan[ch].iActFreq!=s_chan[ch].iUsedFreq) // new psx frequency?
720 VoiceChangeFrequency(ch);
721
722 if(s_chan[ch].bNoise)
723 d=do_samples_noise(ch, ns_from, ns_to);
724 else if(s_chan[ch].bFMod==2 || (s_chan[ch].bFMod==0 && iUseInterpolation==0))
725 d=do_samples_noint(ch, ns_from, ns_to);
726 else if(s_chan[ch].bFMod==0 && iUseInterpolation==1)
727 d=do_samples_simple(ch, ns_from, ns_to);
728 else
729 d=do_samples_default(ch, ns_from, ns_to);
730 if(d>=0)
731 {
732 bIRQReturn=1;
733 lastch=ch;
734 lastns=ns_to=d;
735 }
736
737 MixADSR(ch, ns_from, ns_to);
738
739 if(s_chan[ch].bFMod==2) // fmod freq channel
740 memcpy(iFMod, ChanBuf, sizeof(iFMod));
741 else
742 {
743 int lv=s_chan[ch].iLeftVolume;
744 int rv=s_chan[ch].iRightVolume;
745
746 for(ns=ns_from;ns<ns_to;ns++)
747 {
748 int sval = ChanBuf[ns];
749 int l, r;
750
751 //////////////////////////////////////////////
752 // ok, left/right sound volume (psx volume goes from 0 ... 0x3fff)
753
754 l=(sval*lv)>>14;
755 r=(sval*rv)>>14;
756 SSumLR[ns*2] +=l;
757 SSumLR[ns*2+1]+=r;
758
759 //////////////////////////////////////////////
760 // now let us store sound data for reverb
761
762 if(s_chan[ch].bRVBActive) StoreREVERB(ch,ns,l,r);
763 }
764 }
765 }
766 }
767
768 // advance "stopped" channels that can cause irqs
769 // (all chans are always playing on the real thing..)
770 if(!bIRQReturn && (spuCtrl&CTRL_IRQ))
771 for(ch=0;ch<MAXCHAN;ch++)
772 {
773 if(dwChannelOn&(1<<ch)) continue; // already handled
774 if(s_chan[ch].pCurr == (unsigned char *)-1)
775 continue;
776 if(s_chan[ch].pCurr > pSpuIrq && s_chan[ch].pLoop > pSpuIrq)
777 continue;
778
779 if(s_chan[ch].iActFreq!=s_chan[ch].iUsedFreq) // new psx frequency?
780 VoiceChangeFrequency(ch);
781
782 s_chan[ch].spos += s_chan[ch].sinc * NSSIZE;
783 while(s_chan[ch].spos >= 28 * 0x10000)
784 {
785 unsigned char *start=s_chan[ch].pCurr;
786
787 bIRQReturn |= skip_block(ch);
788 if(start == s_chan[ch].pCurr)
789 {
790 // looping on self
791 s_chan[ch].pCurr=(unsigned char *)-1;
792 break;
793 }
794
795 s_chan[ch].spos -= 28 * 0x10000;
796 }
797 }
798
799 if(bIRQReturn && iSPUIRQWait) // special return for "spu irq - wait for cpu action"
800 {
801 iSpuAsyncWait=1;
802 bIRQReturn=0;
803 if(iUseTimer!=2)
804 {
805 DWORD dwWatchTime=timeGetTime_spu()+2500;
806
807 while(iSpuAsyncWait && !bEndThread &&
808 timeGetTime_spu()<dwWatchTime)
809 usleep(1000L);
810 continue;
811 }
812 else
813 {
814 return 0;
815 }
816 }
817
818
819 //---------------------------------------------------//
820 //- here we have another 1 ms of sound data
821 //---------------------------------------------------//
822 // mix XA infos (if any)
823
824 MixXA();
825
826 ///////////////////////////////////////////////////////
827 // mix all channels (including reverb) into one buffer
828
829 if(iUseReverb)
830 REVERBDo();
831
832 if((spuCtrl&0x4000)==0) // muted? (rare, don't optimize for this)
833 {
834 memset(pS, 0, NSSIZE * 2 * sizeof(pS[0]));
835 pS += NSSIZE*2;
836 }
837 else
838 for (ns = 0; ns < NSSIZE*2; )
839 {
840 d = SSumLR[ns] / voldiv; SSumLR[ns] = 0;
841 ssat32_to_16(d);
842 *pS++ = d;
843 ns++;
844
845 d = SSumLR[ns] / voldiv; SSumLR[ns] = 0;
846 ssat32_to_16(d);
847 *pS++ = d;
848 ns++;
849 }
850
851 //////////////////////////////////////////////////////
852 // special irq handling in the decode buffers (0x0000-0x1000)
853 // we know:
854 // the decode buffers are located in spu memory in the following way:
855 // 0x0000-0x03ff CD audio left
856 // 0x0400-0x07ff CD audio right
857 // 0x0800-0x0bff Voice 1
858 // 0x0c00-0x0fff Voice 3
859 // and decoded data is 16 bit for one sample
860 // we assume:
861 // even if voices 1/3 are off or no cd audio is playing, the internal
862 // play positions will move on and wrap after 0x400 bytes.
863 // Therefore: we just need a pointer from spumem+0 to spumem+3ff, and
864 // increase this pointer on each sample by 2 bytes. If this pointer
865 // (or 0x400 offsets of this pointer) hits the spuirq address, we generate
866 // an IRQ. Only problem: the "wait for cpu" option is kinda hard to do here
867 // in some of Peops timer modes. So: we ignore this option here (for now).
868
869 if(pMixIrq)
870 {
871 for(ns=0;ns<NSSIZE;ns++)
872 {
873 if((spuCtrl&0x40) && pSpuIrq && pSpuIrq<spuMemC+0x1000)
874 {
875 for(ch=0;ch<4;ch++)
876 {
877 if(pSpuIrq>=pMixIrq+(ch*0x400) && pSpuIrq<pMixIrq+(ch*0x400)+2)
878 do_irq();
879 }
880 }
881 pMixIrq+=2;if(pMixIrq>spuMemC+0x3ff) pMixIrq=spuMemC;
882 }
883 }
884
885 InitREVERB();
886
887 // feed the sound
888 // wanna have around 1/60 sec (16.666 ms) updates
889 if (iCycle++ > 16/FRAG_MSECS)
890 {
891 SoundFeedStreamData((unsigned char *)pSpuBuffer,
892 ((unsigned char *)pS) - ((unsigned char *)pSpuBuffer));
893 pS = (short *)pSpuBuffer;
894 iCycle = 0;
895 }
896 }
897
898 // end of big main loop...
899
900 bThreadEnded = 1;
901
902 return 0;
903}
904
905// SPU ASYNC... even newer epsxe func
906// 1 time every 'cycle' cycles... harhar
907
908void CALLBACK SPUasync(unsigned long cycle)
909{
910 if(iSpuAsyncWait)
911 {
912 iSpuAsyncWait++;
913 if(iSpuAsyncWait<=16/FRAG_MSECS) return;
914 iSpuAsyncWait=0;
915 }
916
917 if(iUseTimer==2) // special mode, only used in Linux by this spu (or if you enable the experimental Windows mode)
918 {
919 if(!bSpuInit) return; // -> no init, no call
920
921 MAINThread(0); // -> linux high-compat mode
922
923 // abuse iSpuAsyncWait mechanism to reduce calls to above function
924 // to make it do larger chunks
925 // note: doing it less often than once per frame causes skips
926 iSpuAsyncWait=1;
927 }
928}
929
930// SPU UPDATE... new epsxe func
931// 1 time every 32 hsync lines
932// (312/32)x50 in pal
933// (262/32)x60 in ntsc
934
935// since epsxe 1.5.2 (linux) uses SPUupdate, not SPUasync, I will
936// leave that func in the linux port, until epsxe linux is using
937// the async function as well
938
939void CALLBACK SPUupdate(void)
940{
941 SPUasync(0);
942}
943
944// XA AUDIO
945
946void CALLBACK SPUplayADPCMchannel(xa_decode_t *xap)
947{
948 if(!xap) return;
949 if(!xap->freq) return; // no xa freq ? bye
950
951 FeedXA(xap); // call main XA feeder
952}
953
954// CDDA AUDIO
955void CALLBACK SPUplayCDDAchannel(short *pcm, int nbytes)
956{
957 if (!pcm) return;
958 if (nbytes<=0) return;
959
960 FeedCDDA((unsigned char *)pcm, nbytes);
961}
962
963// SETUPTIMER: init of certain buffers and threads/timers
964void SetupTimer(void)
965{
966 memset(SSumLR,0,sizeof(SSumLR)); // init some mixing buffers
967 memset(iFMod,0,NSSIZE*sizeof(int));
968 pS=(short *)pSpuBuffer; // setup soundbuffer pointer
969
970 bEndThread=0; // init thread vars
971 bThreadEnded=0;
972 bSpuInit=1; // flag: we are inited
973
974 if(!iUseTimer) // linux: use thread
975 {
976 pthread_create(&thread, NULL, MAINThread, NULL);
977 }
978}
979
980// REMOVETIMER: kill threads/timers
981void RemoveTimer(void)
982{
983 bEndThread=1; // raise flag to end thread
984
985 if(!iUseTimer) // linux tread?
986 {
987 int i=0;
988 while(!bThreadEnded && i<2000) {usleep(1000L);i++;} // -> wait until thread has ended
989 if(thread!=(pthread_t)-1) {pthread_cancel(thread);thread=(pthread_t)-1;} // -> cancel thread anyway
990 }
991
992 bThreadEnded=0; // no more spu is running
993 bSpuInit=0;
994}
995
996// SETUPSTREAMS: init most of the spu buffers
997void SetupStreams(void)
998{
999 int i;
1000
1001 pSpuBuffer=(unsigned char *)malloc(32768); // alloc mixing buffer
1002
1003 if(iUseReverb==1) i=88200*2;
1004 else i=NSSIZE*2;
1005
1006 sRVBStart = (int *)malloc(i*4); // alloc reverb buffer
1007 memset(sRVBStart,0,i*4);
1008 sRVBEnd = sRVBStart + i;
1009 sRVBPlay = sRVBStart;
1010
1011 XAStart = // alloc xa buffer
1012 (uint32_t *)malloc(44100 * sizeof(uint32_t));
1013 XAEnd = XAStart + 44100;
1014 XAPlay = XAStart;
1015 XAFeed = XAStart;
1016
1017 CDDAStart = // alloc cdda buffer
1018 (uint32_t *)malloc(16384 * sizeof(uint32_t));
1019 CDDAEnd = CDDAStart + 16384;
1020 CDDAPlay = CDDAStart;
1021 CDDAFeed = CDDAStart;
1022
1023 for(i=0;i<MAXCHAN;i++) // loop sound channels
1024 {
1025// we don't use mutex sync... not needed, would only
1026// slow us down:
1027// s_chan[i].hMutex=CreateMutex(NULL,FALSE,NULL);
1028 s_chan[i].ADSRX.SustainLevel = 0xf; // -> init sustain
1029 s_chan[i].pLoop=spuMemC;
1030 s_chan[i].pStart=spuMemC;
1031 s_chan[i].pCurr=spuMemC;
1032 }
1033
1034 pMixIrq=spuMemC; // enable decoded buffer irqs by setting the address
1035}
1036
1037// REMOVESTREAMS: free most buffer
1038void RemoveStreams(void)
1039{
1040 free(pSpuBuffer); // free mixing buffer
1041 pSpuBuffer = NULL;
1042 free(sRVBStart); // free reverb buffer
1043 sRVBStart = NULL;
1044 free(XAStart); // free XA buffer
1045 XAStart = NULL;
1046 free(CDDAStart); // free CDDA buffer
1047 CDDAStart = NULL;
1048}
1049
1050// INIT/EXIT STUFF
1051
1052// SPUINIT: this func will be called first by the main emu
1053long CALLBACK SPUinit(void)
1054{
1055 spuMemC = (unsigned char *)spuMem; // just small setup
1056 memset((void *)&rvb, 0, sizeof(REVERBInfo));
1057 InitADSR();
1058
1059 iVolume = 3;
1060 spuIrq = 0;
1061 spuAddr = 0xffffffff;
1062 bEndThread = 0;
1063 bThreadEnded = 0;
1064 spuMemC = (unsigned char *)spuMem;
1065 pMixIrq = 0;
1066 memset((void *)s_chan, 0, (MAXCHAN + 1) * sizeof(SPUCHAN));
1067 pSpuIrq = 0;
1068 //iSPUIRQWait = 0;
1069 lastch = -1;
1070
1071 //ReadConfigSPU(); // read user stuff
1072 SetupStreams(); // prepare streaming
1073
1074 return 0;
1075}
1076
1077// SPUOPEN: called by main emu after init
1078long CALLBACK SPUopen(void)
1079{
1080 if (bSPUIsOpen) return 0; // security for some stupid main emus
1081
1082 SetupSound(); // setup sound (before init!)
1083 SetupTimer(); // timer for feeding data
1084
1085 bSPUIsOpen = 1;
1086
1087 return PSE_SPU_ERR_SUCCESS;
1088}
1089
1090// SPUCLOSE: called before shutdown
1091long CALLBACK SPUclose(void)
1092{
1093 if (!bSPUIsOpen) return 0; // some security
1094
1095 bSPUIsOpen = 0; // no more open
1096
1097 RemoveTimer(); // no more feeding
1098 RemoveSound(); // no more sound handling
1099
1100 return 0;
1101}
1102
1103// SPUSHUTDOWN: called by main emu on final exit
1104long CALLBACK SPUshutdown(void)
1105{
1106 SPUclose();
1107 RemoveStreams(); // no more streaming
1108
1109 return 0;
1110}
1111
1112// SPUTEST: we don't test, we are always fine ;)
1113long CALLBACK SPUtest(void)
1114{
1115 return 0;
1116}
1117
1118// SPUCONFIGURE: call config dialog
1119long CALLBACK SPUconfigure(void)
1120{
1121#ifdef _MACOSX
1122 DoConfiguration();
1123#else
1124// StartCfgTool("CFG");
1125#endif
1126 return 0;
1127}
1128
1129// SPUABOUT: show about window
1130void CALLBACK SPUabout(void)
1131{
1132#ifdef _MACOSX
1133 DoAbout();
1134#else
1135// StartCfgTool("ABOUT");
1136#endif
1137}
1138
1139// SETUP CALLBACKS
1140// this functions will be called once,
1141// passes a callback that should be called on SPU-IRQ/cdda volume change
1142void CALLBACK SPUregisterCallback(void (CALLBACK *callback)(void))
1143{
1144 irqCallback = callback;
1145}
1146
1147void CALLBACK SPUregisterCDDAVolume(void (CALLBACK *CDDAVcallback)(unsigned short,unsigned short))
1148{
1149 cddavCallback = CDDAVcallback;
1150}
1151
1152// COMMON PLUGIN INFO FUNCS
1153/*
1154char * CALLBACK PSEgetLibName(void)
1155{
1156 return _(libraryName);
1157}
1158
1159unsigned long CALLBACK PSEgetLibType(void)
1160{
1161 return PSE_LT_SPU;
1162}
1163
1164unsigned long CALLBACK PSEgetLibVersion(void)
1165{
1166 return (1 << 16) | (6 << 8);
1167}
1168
1169char * SPUgetLibInfos(void)
1170{
1171 return _(libraryInfo);
1172}
1173*/
1174
1175// debug
1176void spu_get_debug_info(int *chans_out, int *fmod_chans_out, int *noise_chans_out)
1177{
1178 int ch = 0, fmod_chans = 0, noise_chans = 0;
1179
1180 for(;ch<MAXCHAN;ch++)
1181 {
1182 if (!(dwChannelOn & (1<<ch)))
1183 continue;
1184 if (s_chan[ch].bFMod == 2)
1185 fmod_chans |= 1 << ch;
1186 if (s_chan[ch].bNoise)
1187 noise_chans |= 1 << ch;
1188 }
1189
1190 *chans_out = dwChannelOn;
1191 *fmod_chans_out = fmod_chans;
1192 *noise_chans_out = noise_chans;
1193}
1194
1195// vim:shiftwidth=1:expandtab