1 /***************************************************************************
4 begin : Wed May 15 2002
5 copyright : (C) 2002 by Pete Bernert
6 email : BlackDove@addcom.de
8 Portions (C) GraÅžvydas "notaz" Ignotas, 2010-2012,2014,2015
10 ***************************************************************************/
11 /***************************************************************************
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. *
19 ***************************************************************************/
21 #if !defined(_WIN32) && !defined(NO_OS)
22 #include <sys/time.h> // gettimeofday in xa.c
23 #define THREAD_ENABLED 1
29 #include "externals.h"
30 #include "registers.h"
32 #include "spu_config.h"
35 #include "arm_features.h"
38 #ifdef __ARM_ARCH_7A__
39 #define ssat32_to_16(v) \
40 asm("ssat %0,#16,%1" : "=r" (v) : "r" (v))
42 #define ssat32_to_16(v) do { \
43 if (v < -32768) v = -32768; \
44 else if (v > 32767) v = 32767; \
48 #define PSXCLK 33868800 /* 33.8688 MHz */
50 // intended to be ~1 frame
51 #define IRQ_NEAR_BLOCKS 32
54 #if defined (USEMACOSX)
55 static char * libraryName = N_("Mac OS X Sound");
56 #elif defined (USEALSA)
57 static char * libraryName = N_("ALSA Sound");
58 #elif defined (USEOSS)
59 static char * libraryName = N_("OSS Sound");
60 #elif defined (USESDL)
61 static char * libraryName = N_("SDL Sound");
62 #elif defined (USEPULSEAUDIO)
63 static char * libraryName = N_("PulseAudio Sound");
65 static char * libraryName = N_("NULL Sound");
68 static char * libraryInfo = N_("P.E.Op.S. Sound Driver V1.7\nCoded by Pete Bernert and the P.E.Op.S. team\n");
76 static int iFMod[NSSIZE];
77 static int RVB[NSSIZE * 2];
80 #define CDDA_BUFFER_SIZE (16384 * sizeof(uint32_t)) // must be power of 2
82 ////////////////////////////////////////////////////////////////////////
84 ////////////////////////////////////////////////////////////////////////
86 // dirty inline func includes
91 ////////////////////////////////////////////////////////////////////////
92 // helpers for simple interpolation
95 // easy interpolation on upsampling, no special filter, just "Pete's common sense" tm
97 // instead of having n equal sample values in a row like:
101 // we compare the current delta change with the next delta change.
103 // if curr_delta is positive,
105 // - and next delta is smaller (or changing direction):
109 // - and next delta significant (at least twice) bigger:
113 // - and next delta is nearly same:
118 // if curr_delta is negative,
120 // - and next delta is smaller (or changing direction):
124 // - and next delta significant (at least twice) bigger:
128 // - and next delta is nearly same:
133 static void InterpolateUp(int *SB, int sinc)
135 if(SB[32]==1) // flag == 1? calc step and set flag... and don't change the value in this pass
137 const int id1=SB[30]-SB[29]; // curr delta to next val
138 const int id2=SB[31]-SB[30]; // and next delta to next-next val :)
142 if(id1>0) // curr delta positive
145 {SB[28]=id1;SB[32]=2;}
148 SB[28]=(id1*sinc)>>16;
150 SB[28]=(id1*sinc)>>17;
152 else // curr delta negative
155 {SB[28]=id1;SB[32]=2;}
158 SB[28]=(id1*sinc)>>16;
160 SB[28]=(id1*sinc)>>17;
164 if(SB[32]==2) // flag 1: calc step and set flag... and don't change the value in this pass
168 SB[28]=(SB[28]*sinc)>>17;
170 // SB[29]=SB[30]-(SB[28]*((0x10000/sinc)-1));
174 else // no flags? add bigger val (if possible), calc smaller step, set flag1
179 // even easier interpolation on downsampling, also no special filter, again just "Pete's common sense" tm
182 static void InterpolateDown(int *SB, int sinc)
184 if(sinc>=0x20000L) // we would skip at least one val?
186 SB[29]+=(SB[30]-SB[29])/2; // add easy weight
187 if(sinc>=0x30000L) // we would skip even more vals?
188 SB[29]+=(SB[31]-SB[30])/2; // add additional next weight
192 ////////////////////////////////////////////////////////////////////////
193 // helpers for gauss interpolation
195 #define gval0 (((short*)(&SB[29]))[gpos&3])
196 #define gval(x) ((int)((short*)(&SB[29]))[(gpos+x)&3])
200 ////////////////////////////////////////////////////////////////////////
204 static void do_irq(void)
206 //if(!(spu.spuStat & STAT_IRQ))
208 spu.spuStat |= STAT_IRQ; // asserted status?
209 if(spu.irqCallback) spu.irqCallback();
213 static int check_irq(int ch, unsigned char *pos)
215 if((spu.spuCtrl & CTRL_IRQ) && pos == spu.pSpuIrq)
217 //printf("ch%d irq %04x\n", ch, pos - spu.spuMemC);
224 ////////////////////////////////////////////////////////////////////////
225 // START SOUND... called by main thread to setup a new sound on a channel
226 ////////////////////////////////////////////////////////////////////////
228 static void StartSoundSB(int *SB)
230 SB[26]=0; // init mixing vars
234 SB[29]=0; // init our interpolation helpers
239 static void StartSoundMain(int ch)
241 SPUCHAN *s_chan = &spu.s_chan[ch];
250 spu.dwNewChannel&=~(1<<ch); // clear new channel bit
251 spu.dwChannelOn|=1<<ch;
252 spu.dwChannelDead&=~(1<<ch);
255 static void StartSound(int ch)
258 StartSoundSB(spu.SB + ch * SB_SIZE);
261 ////////////////////////////////////////////////////////////////////////
262 // ALL KIND OF HELPERS
263 ////////////////////////////////////////////////////////////////////////
265 INLINE int FModChangeFrequency(int *SB, int pitch, int ns)
267 unsigned int NP=pitch;
270 NP=((32768L+iFMod[ns])*NP)>>15;
272 if(NP>0x3fff) NP=0x3fff;
275 sinc=NP<<4; // calc frequency
276 if(spu_config.iUseInterpolation==1) // freq change in simple interpolation mode
283 ////////////////////////////////////////////////////////////////////////
285 INLINE void StoreInterpolationVal(int *SB, int sinc, int fa, int fmod_freq)
287 if(fmod_freq) // fmod freq channel
293 if(spu_config.iUseInterpolation>=2) // gauss/cubic interpolation
301 if(spu_config.iUseInterpolation==1) // simple interpolation
304 SB[29] = 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'
307 SB[32] = 1; // -> flag: calc new interolation
309 else SB[29]=fa; // no interpolation
313 ////////////////////////////////////////////////////////////////////////
315 INLINE int iGetInterpolationVal(int *SB, int sinc, int spos, int fmod_freq)
319 if(fmod_freq) return SB[29];
321 switch(spu_config.iUseInterpolation)
323 //--------------------------------------------------//
324 case 3: // cubic interpolation
330 fa = gval(3) - 3*gval(2) + 3*gval(1) - gval0;
331 fa *= (xd - (2<<15)) / 6;
333 fa += gval(2) - gval(1) - gval(1) + gval0;
334 fa *= (xd - (1<<15)) >> 1;
336 fa += gval(1) - gval0;
342 //--------------------------------------------------//
343 case 2: // gauss interpolation
346 vl = (spos >> 6) & ~3;
348 vr=(gauss[vl]*(int)gval0)&~2047;
349 vr+=(gauss[vl+1]*gval(1))&~2047;
350 vr+=(gauss[vl+2]*gval(2))&~2047;
351 vr+=(gauss[vl+3]*gval(3))&~2047;
354 //--------------------------------------------------//
355 case 1: // simple interpolation
357 if(sinc<0x10000L) // -> upsampling?
358 InterpolateUp(SB, sinc); // --> interpolate up
359 else InterpolateDown(SB, sinc); // --> else down
362 //--------------------------------------------------//
363 default: // no interpolation
367 //--------------------------------------------------//
373 static void decode_block_data(int *dest, const unsigned char *src, int predict_nr, int shift_factor)
375 static const int f[16][2] = {
383 int fa, s_1, s_2, d, s;
388 for (nSample = 0; nSample < 28; src++)
391 s = (int)(signed short)((d & 0x0f) << 12);
393 fa = s >> shift_factor;
394 fa += ((s_1 * f[predict_nr][0])>>6) + ((s_2 * f[predict_nr][1])>>6);
397 dest[nSample++] = fa;
399 s = (int)(signed short)((d & 0xf0) << 8);
400 fa = s >> shift_factor;
401 fa += ((s_1 * f[predict_nr][0])>>6) + ((s_2 * f[predict_nr][1])>>6);
404 dest[nSample++] = fa;
408 static int decode_block(void *unused, int ch, int *SB)
410 SPUCHAN *s_chan = &spu.s_chan[ch];
411 unsigned char *start;
412 int predict_nr, shift_factor, flags;
415 start = s_chan->pCurr; // set up the current pos
416 if (start == spu.spuMemC) // ?
419 if (s_chan->prevflags & 1) // 1: stop/loop
421 if (!(s_chan->prevflags & 2))
424 start = s_chan->pLoop;
427 check_irq(ch, start); // hack, see check_irq below..
429 predict_nr = start[0];
430 shift_factor = predict_nr & 0xf;
433 decode_block_data(SB, start + 2, predict_nr, shift_factor);
437 s_chan->pLoop = start; // loop adress
441 if (flags & 1) { // 1: stop/loop
442 start = s_chan->pLoop;
443 check_irq(ch, start); // hack.. :(
446 if (start - spu.spuMemC >= 0x80000)
449 s_chan->pCurr = start; // store values for next cycle
450 s_chan->prevflags = flags;
455 // do block, but ignore sample data
456 static int skip_block(int ch)
458 SPUCHAN *s_chan = &spu.s_chan[ch];
459 unsigned char *start = s_chan->pCurr;
463 if (s_chan->prevflags & 1) {
464 if (!(s_chan->prevflags & 2))
467 start = s_chan->pLoop;
470 check_irq(ch, start);
474 s_chan->pLoop = start;
479 start = s_chan->pLoop;
480 check_irq(ch, start);
483 s_chan->pCurr = start;
484 s_chan->prevflags = flags;
489 // if irq is going to trigger sooner than in upd_samples, set upd_samples
490 static void scan_for_irq(int ch, unsigned int *upd_samples)
492 SPUCHAN *s_chan = &spu.s_chan[ch];
493 int pos, sinc, sinc_inv, end;
494 unsigned char *block;
497 block = s_chan->pCurr;
500 end = pos + *upd_samples * sinc;
502 pos += (28 - s_chan->iSBPos) << 16;
505 if (block == spu.pSpuIrq)
509 if (flags & 1) { // 1: stop/loop
510 block = s_chan->pLoop;
511 if (block == spu.pSpuIrq) // hack.. (see decode_block)
519 sinc_inv = s_chan->sinc_inv;
521 sinc_inv = s_chan->sinc_inv = (0x80000000u / (uint32_t)sinc) << 1;
524 *upd_samples = (((uint64_t)pos * sinc_inv) >> 32) + 1;
525 //xprintf("ch%02d: irq sched: %3d %03d\n",
526 // ch, *upd_samples, *upd_samples * 60 * 263 / 44100);
530 #define make_do_samples(name, fmod_code, interp_start, interp1_code, interp2_code, interp_end) \
531 static noinline int do_samples_##name( \
532 int (*decode_f)(void *context, int ch, int *SB), void *ctx, \
533 int ch, int ns_to, int *SB, int sinc, int *spos, int *sbpos) \
539 for (ns = 0; ns < ns_to; ns++) \
544 while (*spos >= 0x10000) \
546 fa = SB[(*sbpos)++]; \
550 d = decode_f(ctx, ch, SB); \
567 #define fmod_recv_check \
568 if(spu.s_chan[ch].bFMod==1 && iFMod[ns]) \
569 sinc = FModChangeFrequency(SB, spu.s_chan[ch].iRawPitch, ns)
571 make_do_samples(default, fmod_recv_check, ,
572 StoreInterpolationVal(SB, sinc, fa, spu.s_chan[ch].bFMod==2),
573 ChanBuf[ns] = iGetInterpolationVal(SB, sinc, *spos, spu.s_chan[ch].bFMod==2), )
574 make_do_samples(noint, , fa = SB[29], , ChanBuf[ns] = fa, SB[29] = fa)
576 #define simple_interp_store \
583 #define simple_interp_get \
584 if(sinc<0x10000) /* -> upsampling? */ \
585 InterpolateUp(SB, sinc); /* --> interpolate up */ \
586 else InterpolateDown(SB, sinc); /* --> else down */ \
589 make_do_samples(simple, , ,
590 simple_interp_store, simple_interp_get, )
592 static int do_samples_skip(int ch, int ns_to)
594 SPUCHAN *s_chan = &spu.s_chan[ch];
595 int spos = s_chan->spos;
596 int sinc = s_chan->sinc;
597 int ret = ns_to, ns, d;
599 spos += s_chan->iSBPos << 16;
601 for (ns = 0; ns < ns_to; ns++)
604 while (spos >= 28*0x10000)
613 s_chan->iSBPos = spos >> 16;
614 s_chan->spos = spos & 0xffff;
619 static void do_lsfr_samples(int ns_to, int ctrl,
620 unsigned int *dwNoiseCount, unsigned int *dwNoiseVal)
622 unsigned int counter = *dwNoiseCount;
623 unsigned int val = *dwNoiseVal;
624 unsigned int level, shift, bit;
627 // modified from DrHell/shalma, no fraction
628 level = (ctrl >> 10) & 0x0f;
629 level = 0x8000 >> level;
631 for (ns = 0; ns < ns_to; ns++)
634 if (counter >= level)
637 shift = (val >> 10) & 0x1f;
638 bit = (0x69696969 >> shift) & 1;
639 bit ^= (val >> 15) & 1;
640 val = (val << 1) | bit;
643 ChanBuf[ns] = (signed short)val;
646 *dwNoiseCount = counter;
650 static int do_samples_noise(int ch, int ns_to)
654 ret = do_samples_skip(ch, ns_to);
656 do_lsfr_samples(ns_to, spu.spuCtrl, &spu.dwNoiseCount, &spu.dwNoiseVal);
662 // asm code; lv and rv must be 0-3fff
663 extern void mix_chan(int *SSumLR, int count, int lv, int rv);
664 extern void mix_chan_rvb(int *SSumLR, int count, int lv, int rv, int *rvb);
666 static void mix_chan(int *SSumLR, int count, int lv, int rv)
668 const int *src = ChanBuf;
675 l = (sval * lv) >> 14;
676 r = (sval * rv) >> 14;
682 static void mix_chan_rvb(int *SSumLR, int count, int lv, int rv, int *rvb)
684 const int *src = ChanBuf;
693 l = (sval * lv) >> 14;
694 r = (sval * rv) >> 14;
703 // 0x0800-0x0bff Voice 1
704 // 0x0c00-0x0fff Voice 3
705 static noinline void do_decode_bufs(unsigned short *mem, int which,
706 int count, int decode_pos)
708 unsigned short *dst = &mem[0x800/2 + which*0x400/2];
709 const int *src = ChanBuf;
710 int cursor = decode_pos;
715 dst[cursor] = *src++;
719 // decode_pos is updated and irqs are checked later, after voice loop
722 static void do_silent_chans(int ns_to, int silentch)
728 mask = silentch & 0xffffff;
729 for (ch = 0; mask != 0; ch++, mask >>= 1)
731 if (!(mask & 1)) continue;
732 if (spu.dwChannelDead & (1<<ch)) continue;
734 s_chan = &spu.s_chan[ch];
735 if (s_chan->pCurr > spu.pSpuIrq && s_chan->pLoop > spu.pSpuIrq)
738 s_chan->spos += s_chan->iSBPos << 16;
741 s_chan->spos += s_chan->sinc * ns_to;
742 while (s_chan->spos >= 28 * 0x10000)
744 unsigned char *start = s_chan->pCurr;
747 if (start == s_chan->pCurr || start - spu.spuMemC < 0x1000)
749 // looping on self or stopped(?)
750 spu.dwChannelDead |= 1<<ch;
755 s_chan->spos -= 28 * 0x10000;
760 static void do_channels(int ns_to)
767 do_rvb = spu.rvb->StartAddr && spu_config.iUseReverb;
769 memset(RVB, 0, ns_to * sizeof(RVB[0]) * 2);
771 mask = spu.dwNewChannel & 0xffffff;
772 for (ch = 0; mask != 0; ch++, mask >>= 1) {
777 mask = spu.dwChannelOn & 0xffffff;
778 for (ch = 0; mask != 0; ch++, mask >>= 1) // loop em all...
780 if (!(mask & 1)) continue; // channel not playing? next
782 s_chan = &spu.s_chan[ch];
783 SB = spu.SB + ch * SB_SIZE;
787 d = do_samples_noise(ch, ns_to);
788 else if (s_chan->bFMod == 2
789 || (s_chan->bFMod == 0 && spu_config.iUseInterpolation == 0))
790 d = do_samples_noint(decode_block, NULL, ch, ns_to,
791 SB, sinc, &s_chan->spos, &s_chan->iSBPos);
792 else if (s_chan->bFMod == 0 && spu_config.iUseInterpolation == 1)
793 d = do_samples_simple(decode_block, NULL, ch, ns_to,
794 SB, sinc, &s_chan->spos, &s_chan->iSBPos);
796 d = do_samples_default(decode_block, NULL, ch, ns_to,
797 SB, sinc, &s_chan->spos, &s_chan->iSBPos);
799 d = MixADSR(&s_chan->ADSRX, d);
801 spu.dwChannelOn &= ~(1 << ch);
802 s_chan->ADSRX.EnvelopeVol = 0;
803 memset(&ChanBuf[d], 0, (ns_to - d) * sizeof(ChanBuf[0]));
806 if (ch == 1 || ch == 3)
808 do_decode_bufs(spu.spuMem, ch/2, ns_to, spu.decode_pos);
809 spu.decode_dirty_ch |= 1 << ch;
812 if (s_chan->bFMod == 2) // fmod freq channel
813 memcpy(iFMod, &ChanBuf, ns_to * sizeof(iFMod[0]));
814 if (s_chan->bRVBActive && do_rvb)
815 mix_chan_rvb(spu.SSumLR, ns_to, s_chan->iLeftVolume, s_chan->iRightVolume, RVB);
817 mix_chan(spu.SSumLR, ns_to, s_chan->iLeftVolume, s_chan->iRightVolume);
820 if (spu.rvb->StartAddr) {
822 REVERBDo(spu.SSumLR, RVB, ns_to, spu.rvb->CurrAddr);
824 spu.rvb->CurrAddr += ns_to / 2;
825 while (spu.rvb->CurrAddr >= 0x40000)
826 spu.rvb->CurrAddr -= 0x40000 - spu.rvb->StartAddr;
830 static void do_samples_finish(int *SSumLR, int ns_to,
831 int silentch, int decode_pos);
833 // optional worker thread handling
835 #if defined(THREAD_ENABLED) || defined(WANT_THREAD_CODE)
837 // worker thread state
838 static struct spu_worker {
841 unsigned int exit_thread;
842 unsigned int i_ready;
843 unsigned int i_reaped;
844 unsigned int last_boot_cnt; // dsp
845 unsigned int ram_dirty;
847 // aligning for C64X_DSP
848 unsigned int _pad0[128/4];
853 unsigned int active; // dsp
854 unsigned int boot_cnt;
856 unsigned int _pad1[128/4];
863 unsigned int channels_new;
864 unsigned int channels_on;
865 unsigned int channels_silent;
876 // might also want to add fmod flags..
878 int SSumLR[NSSIZE * 2];
882 #define WORK_MAXCNT (sizeof(worker->i) / sizeof(worker->i[0]))
883 #define WORK_I_MASK (WORK_MAXCNT - 1)
885 static void thread_work_start(void);
886 static void thread_work_wait_sync(struct work_item *work, int force);
887 static void thread_sync_caches(void);
888 static int thread_get_i_done(void);
890 static int decode_block_work(void *context, int ch, int *SB)
892 const unsigned char *ram = spu.spuMemC;
893 int predict_nr, shift_factor, flags;
894 struct work_item *work = context;
895 int start = work->ch[ch].start;
896 int loop = work->ch[ch].loop;
898 predict_nr = ram[start];
899 shift_factor = predict_nr & 0xf;
902 decode_block_data(SB, ram + start + 2, predict_nr, shift_factor);
904 flags = ram[start + 1];
906 loop = start; // loop adress
910 if (flags & 1) // 1: stop/loop
913 work->ch[ch].start = start & 0x7ffff;
914 work->ch[ch].loop = loop;
919 static void queue_channel_work(int ns_to, unsigned int silentch)
921 struct work_item *work;
926 work = &worker->i[worker->i_ready & WORK_I_MASK];
928 work->ctrl = spu.spuCtrl;
929 work->decode_pos = spu.decode_pos;
930 work->channels_silent = silentch;
932 mask = work->channels_new = spu.dwNewChannel & 0xffffff;
933 for (ch = 0; mask != 0; ch++, mask >>= 1) {
938 mask = work->channels_on = spu.dwChannelOn & 0xffffff;
939 spu.decode_dirty_ch |= mask & 0x0a;
941 for (ch = 0; mask != 0; ch++, mask >>= 1)
943 if (!(mask & 1)) continue;
945 s_chan = &spu.s_chan[ch];
946 work->ch[ch].spos = s_chan->spos;
947 work->ch[ch].sbpos = s_chan->iSBPos;
948 work->ch[ch].sinc = s_chan->sinc;
949 work->ch[ch].adsr = s_chan->ADSRX;
950 work->ch[ch].vol_l = s_chan->iLeftVolume;
951 work->ch[ch].vol_r = s_chan->iRightVolume;
952 work->ch[ch].start = s_chan->pCurr - spu.spuMemC;
953 work->ch[ch].loop = s_chan->pLoop - spu.spuMemC;
954 if (s_chan->prevflags & 1)
955 work->ch[ch].start = work->ch[ch].loop;
957 d = do_samples_skip(ch, ns_to);
958 work->ch[ch].ns_to = d;
960 // note: d is not accurate on skip
961 d = SkipADSR(&s_chan->ADSRX, d);
963 spu.dwChannelOn &= ~(1 << ch);
964 s_chan->ADSRX.EnvelopeVol = 0;
969 if (spu.rvb->StartAddr) {
970 if (spu_config.iUseReverb)
971 work->rvb_addr = spu.rvb->CurrAddr;
973 spu.rvb->CurrAddr += ns_to / 2;
974 while (spu.rvb->CurrAddr >= 0x40000)
975 spu.rvb->CurrAddr -= 0x40000 - spu.rvb->StartAddr;
982 static void do_channel_work(struct work_item *work)
985 unsigned int decode_dirty_ch = 0;
986 const SPUCHAN *s_chan;
987 int *SB, sinc, spos, sbpos;
993 memset(RVB, 0, ns_to * sizeof(RVB[0]) * 2);
995 mask = work->channels_new;
996 for (ch = 0; mask != 0; ch++, mask >>= 1) {
998 StartSoundSB(spu.SB + ch * SB_SIZE);
1001 mask = work->channels_on;
1002 for (ch = 0; mask != 0; ch++, mask >>= 1)
1004 if (!(mask & 1)) continue;
1006 d = work->ch[ch].ns_to;
1007 spos = work->ch[ch].spos;
1008 sbpos = work->ch[ch].sbpos;
1009 sinc = work->ch[ch].sinc;
1011 s_chan = &spu.s_chan[ch];
1012 SB = spu.SB + ch * SB_SIZE;
1015 do_lsfr_samples(d, work->ctrl, &spu.dwNoiseCount, &spu.dwNoiseVal);
1016 else if (s_chan->bFMod == 2
1017 || (s_chan->bFMod == 0 && spu_config.iUseInterpolation == 0))
1018 do_samples_noint(decode_block_work, work, ch, d, SB, sinc, &spos, &sbpos);
1019 else if (s_chan->bFMod == 0 && spu_config.iUseInterpolation == 1)
1020 do_samples_simple(decode_block_work, work, ch, d, SB, sinc, &spos, &sbpos);
1022 do_samples_default(decode_block_work, work, ch, d, SB, sinc, &spos, &sbpos);
1024 d = MixADSR(&work->ch[ch].adsr, d);
1026 work->ch[ch].adsr.EnvelopeVol = 0;
1027 memset(&ChanBuf[d], 0, (ns_to - d) * sizeof(ChanBuf[0]));
1030 if (ch == 1 || ch == 3)
1032 do_decode_bufs(spu.spuMem, ch/2, ns_to, work->decode_pos);
1033 decode_dirty_ch |= 1 << ch;
1036 if (s_chan->bFMod == 2) // fmod freq channel
1037 memcpy(iFMod, &ChanBuf, ns_to * sizeof(iFMod[0]));
1038 if (s_chan->bRVBActive && work->rvb_addr)
1039 mix_chan_rvb(work->SSumLR, ns_to,
1040 work->ch[ch].vol_l, work->ch[ch].vol_r, RVB);
1042 mix_chan(work->SSumLR, ns_to, work->ch[ch].vol_l, work->ch[ch].vol_r);
1046 REVERBDo(work->SSumLR, RVB, ns_to, work->rvb_addr);
1049 static void sync_worker_thread(int force)
1051 struct work_item *work;
1052 int done, used_space;
1054 // rvb offsets will change, thread may be using them
1055 force |= spu.rvb->dirty && spu.rvb->StartAddr;
1057 done = thread_get_i_done() - worker->i_reaped;
1058 used_space = worker->i_ready - worker->i_reaped;
1060 //printf("done: %d use: %d dsp: %u/%u\n", done, used_space,
1061 // worker->boot_cnt, worker->i_done);
1063 while ((force && used_space > 0) || used_space >= WORK_MAXCNT || done > 0) {
1064 work = &worker->i[worker->i_reaped & WORK_I_MASK];
1065 thread_work_wait_sync(work, force);
1067 do_samples_finish(work->SSumLR, work->ns_to,
1068 work->channels_silent, work->decode_pos);
1071 done = thread_get_i_done() - worker->i_reaped;
1072 used_space = worker->i_ready - worker->i_reaped;
1075 thread_sync_caches();
1080 static void queue_channel_work(int ns_to, int silentch) {}
1081 static void sync_worker_thread(int force) {}
1083 static const void * const worker = NULL;
1085 #endif // THREAD_ENABLED
1087 ////////////////////////////////////////////////////////////////////////
1088 // MAIN SPU FUNCTION
1089 // here is the main job handler...
1090 ////////////////////////////////////////////////////////////////////////
1092 void do_samples(unsigned int cycles_to, int do_direct)
1094 unsigned int silentch;
1098 cycle_diff = cycles_to - spu.cycles_played;
1099 if (cycle_diff < -2*1048576 || cycle_diff > 2*1048576)
1101 //xprintf("desync %u %d\n", cycles_to, cycle_diff);
1102 spu.cycles_played = cycles_to;
1106 silentch = ~(spu.dwChannelOn | spu.dwNewChannel) & 0xffffff;
1108 do_direct |= (silentch == 0xffffff);
1110 sync_worker_thread(do_direct);
1112 if (cycle_diff < 2 * 768)
1115 ns_to = (cycle_diff / 768 + 1) & ~1;
1116 if (ns_to > NSSIZE) {
1117 // should never happen
1118 //xprintf("ns_to oflow %d %d\n", ns_to, NSSIZE);
1122 //////////////////////////////////////////////////////
1123 // special irq handling in the decode buffers (0x0000-0x1000)
1125 // the decode buffers are located in spu memory in the following way:
1126 // 0x0000-0x03ff CD audio left
1127 // 0x0400-0x07ff CD audio right
1128 // 0x0800-0x0bff Voice 1
1129 // 0x0c00-0x0fff Voice 3
1130 // and decoded data is 16 bit for one sample
1132 // even if voices 1/3 are off or no cd audio is playing, the internal
1133 // play positions will move on and wrap after 0x400 bytes.
1134 // Therefore: we just need a pointer from spumem+0 to spumem+3ff, and
1135 // increase this pointer on each sample by 2 bytes. If this pointer
1136 // (or 0x400 offsets of this pointer) hits the spuirq address, we generate
1139 if (unlikely((spu.spuCtrl & CTRL_IRQ)
1140 && spu.pSpuIrq < spu.spuMemC+0x1000))
1142 int irq_pos = (spu.pSpuIrq - spu.spuMemC) / 2 & 0x1ff;
1143 int left = (irq_pos - spu.decode_pos) & 0x1ff;
1144 if (0 < left && left <= ns_to)
1146 //xprintf("decoder irq %x\n", spu.decode_pos);
1151 if (unlikely(spu.rvb->dirty))
1154 if (do_direct || worker == NULL || !spu_config.iUseThread) {
1156 do_samples_finish(spu.SSumLR, ns_to, silentch, spu.decode_pos);
1159 queue_channel_work(ns_to, silentch);
1162 // advance "stopped" channels that can cause irqs
1163 // (all chans are always playing on the real thing..)
1164 if (spu.spuCtrl & CTRL_IRQ)
1165 do_silent_chans(ns_to, silentch);
1167 spu.cycles_played += ns_to * 768;
1168 spu.decode_pos = (spu.decode_pos + ns_to) & 0x1ff;
1171 static void do_samples_finish(int *SSumLR, int ns_to,
1172 int silentch, int decode_pos)
1174 int volmult = spu_config.iVolume;
1178 // must clear silent channel decode buffers
1179 if(unlikely(silentch & spu.decode_dirty_ch & (1<<1)))
1181 memset(&spu.spuMem[0x800/2], 0, 0x400);
1182 spu.decode_dirty_ch &= ~(1<<1);
1184 if(unlikely(silentch & spu.decode_dirty_ch & (1<<3)))
1186 memset(&spu.spuMem[0xc00/2], 0, 0x400);
1187 spu.decode_dirty_ch &= ~(1<<3);
1190 MixXA(SSumLR, ns_to, decode_pos);
1192 if((spu.spuCtrl&0x4000)==0) // muted? (rare, don't optimize for this)
1194 memset(spu.pS, 0, ns_to * 2 * sizeof(spu.pS[0]));
1195 spu.pS += ns_to * 2;
1198 for (ns = 0; ns < ns_to * 2; )
1200 d = SSumLR[ns]; SSumLR[ns] = 0;
1201 d = d * volmult >> 10;
1206 d = SSumLR[ns]; SSumLR[ns] = 0;
1207 d = d * volmult >> 10;
1214 void schedule_next_irq(void)
1216 unsigned int upd_samples;
1219 if (spu.scheduleCallback == NULL)
1222 upd_samples = 44100 / 50;
1224 for (ch = 0; ch < MAXCHAN; ch++)
1226 if (spu.dwChannelDead & (1 << ch))
1228 if ((unsigned long)(spu.pSpuIrq - spu.s_chan[ch].pCurr) > IRQ_NEAR_BLOCKS * 16
1229 && (unsigned long)(spu.pSpuIrq - spu.s_chan[ch].pLoop) > IRQ_NEAR_BLOCKS * 16)
1232 scan_for_irq(ch, &upd_samples);
1235 if (unlikely(spu.pSpuIrq < spu.spuMemC + 0x1000))
1237 int irq_pos = (spu.pSpuIrq - spu.spuMemC) / 2 & 0x1ff;
1238 int left = (irq_pos - spu.decode_pos) & 0x1ff;
1239 if (0 < left && left < upd_samples) {
1240 //xprintf("decode: %3d (%3d/%3d)\n", left, spu.decode_pos, irq_pos);
1245 if (upd_samples < 44100 / 50)
1246 spu.scheduleCallback(upd_samples * 768);
1249 // SPU ASYNC... even newer epsxe func
1250 // 1 time every 'cycle' cycles... harhar
1252 // rearmed: called dynamically now
1254 void CALLBACK SPUasync(unsigned int cycle, unsigned int flags)
1256 do_samples(cycle, spu_config.iUseFixedUpdates);
1258 if (spu.spuCtrl & CTRL_IRQ)
1259 schedule_next_irq();
1262 out_current->feed(spu.pSpuBuffer, (unsigned char *)spu.pS - spu.pSpuBuffer);
1263 spu.pS = (short *)spu.pSpuBuffer;
1265 if (spu_config.iTempo) {
1266 if (!out_current->busy())
1267 // cause more samples to be generated
1268 // (and break some games because of bad sync)
1269 spu.cycles_played -= 44100 / 60 / 2 * 768;
1274 // SPU UPDATE... new epsxe func
1275 // 1 time every 32 hsync lines
1276 // (312/32)x50 in pal
1277 // (262/32)x60 in ntsc
1279 // since epsxe 1.5.2 (linux) uses SPUupdate, not SPUasync, I will
1280 // leave that func in the linux port, until epsxe linux is using
1281 // the async function as well
1283 void CALLBACK SPUupdate(void)
1289 void CALLBACK SPUplayADPCMchannel(xa_decode_t *xap)
1292 if(!xap->freq) return; // no xa freq ? bye
1294 FeedXA(xap); // call main XA feeder
1298 int CALLBACK SPUplayCDDAchannel(short *pcm, int nbytes)
1300 if (!pcm) return -1;
1301 if (nbytes<=0) return -1;
1303 return FeedCDDA((unsigned char *)pcm, nbytes);
1306 // to be called after state load
1307 void ClearWorkingState(void)
1309 memset(iFMod, 0, sizeof(iFMod));
1310 spu.pS=(short *)spu.pSpuBuffer; // setup soundbuffer pointer
1313 // SETUPSTREAMS: init most of the spu buffers
1314 static void SetupStreams(void)
1316 spu.pSpuBuffer = (unsigned char *)malloc(32768); // alloc mixing buffer
1317 spu.SSumLR = calloc(NSSIZE * 2, sizeof(spu.SSumLR[0]));
1319 spu.XAStart = // alloc xa buffer
1320 (uint32_t *)malloc(44100 * sizeof(uint32_t));
1321 spu.XAEnd = spu.XAStart + 44100;
1322 spu.XAPlay = spu.XAStart;
1323 spu.XAFeed = spu.XAStart;
1325 spu.CDDAStart = // alloc cdda buffer
1326 (uint32_t *)malloc(CDDA_BUFFER_SIZE);
1327 spu.CDDAEnd = spu.CDDAStart + 16384;
1328 spu.CDDAPlay = spu.CDDAStart;
1329 spu.CDDAFeed = spu.CDDAStart;
1331 ClearWorkingState();
1334 // REMOVESTREAMS: free most buffer
1335 static void RemoveStreams(void)
1337 free(spu.pSpuBuffer); // free mixing buffer
1338 spu.pSpuBuffer = NULL;
1341 free(spu.XAStart); // free XA buffer
1343 free(spu.CDDAStart); // free CDDA buffer
1344 spu.CDDAStart = NULL;
1347 #if defined(C64X_DSP)
1349 /* special code for TI C64x DSP */
1350 #include "spu_c64x.c"
1352 #elif defined(THREAD_ENABLED)
1354 #include <pthread.h>
1355 #include <semaphore.h>
1364 /* generic pthread implementation */
1366 static void thread_work_start(void)
1368 sem_post(&t.sem_avail);
1371 static void thread_work_wait_sync(struct work_item *work, int force)
1373 sem_wait(&t.sem_done);
1376 static int thread_get_i_done(void)
1378 return worker->i_done;
1381 static void thread_sync_caches(void)
1385 static void *spu_worker_thread(void *unused)
1387 struct work_item *work;
1390 sem_wait(&t.sem_avail);
1391 if (worker->exit_thread)
1394 work = &worker->i[worker->i_done & WORK_I_MASK];
1395 do_channel_work(work);
1398 sem_post(&t.sem_done);
1404 static void init_spu_thread(void)
1408 if (sysconf(_SC_NPROCESSORS_ONLN) <= 1)
1411 worker = calloc(1, sizeof(*worker));
1414 ret = sem_init(&t.sem_avail, 0, 0);
1416 goto fail_sem_avail;
1417 ret = sem_init(&t.sem_done, 0, 0);
1421 ret = pthread_create(&t.thread, NULL, spu_worker_thread, NULL);
1425 spu_config.iThreadAvail = 1;
1429 sem_destroy(&t.sem_done);
1431 sem_destroy(&t.sem_avail);
1435 spu_config.iThreadAvail = 0;
1438 static void exit_spu_thread(void)
1442 worker->exit_thread = 1;
1443 sem_post(&t.sem_avail);
1444 pthread_join(t.thread, NULL);
1445 sem_destroy(&t.sem_done);
1446 sem_destroy(&t.sem_avail);
1451 #else // if !THREAD_ENABLED
1453 static void init_spu_thread(void)
1457 static void exit_spu_thread(void)
1463 // SPUINIT: this func will be called first by the main emu
1464 long CALLBACK SPUinit(void)
1468 spu.spuMemC = calloc(1, 512 * 1024);
1471 spu.s_chan = calloc(MAXCHAN+1, sizeof(spu.s_chan[0])); // channel + 1 infos (1 is security for fmod handling)
1472 spu.rvb = calloc(1, sizeof(REVERBInfo));
1473 spu.SB = calloc(MAXCHAN, sizeof(spu.SB[0]) * SB_SIZE);
1477 spu.pSpuIrq = spu.spuMemC;
1479 SetupStreams(); // prepare streaming
1481 if (spu_config.iVolume == 0)
1482 spu_config.iVolume = 768; // 1024 is 1.0
1486 for (i = 0; i < MAXCHAN; i++) // loop sound channels
1488 spu.s_chan[i].ADSRX.SustainLevel = 0xf; // -> init sustain
1489 spu.s_chan[i].ADSRX.SustainIncrease = 1;
1490 spu.s_chan[i].pLoop = spu.spuMemC;
1491 spu.s_chan[i].pCurr = spu.spuMemC;
1494 spu.bSpuInit=1; // flag: we are inited
1499 // SPUOPEN: called by main emu after init
1500 long CALLBACK SPUopen(void)
1502 if (spu.bSPUIsOpen) return 0; // security for some stupid main emus
1504 SetupSound(); // setup sound (before init!)
1508 return PSE_SPU_ERR_SUCCESS;
1511 // SPUCLOSE: called before shutdown
1512 long CALLBACK SPUclose(void)
1514 if (!spu.bSPUIsOpen) return 0; // some security
1516 spu.bSPUIsOpen = 0; // no more open
1518 out_current->finish(); // no more sound handling
1523 // SPUSHUTDOWN: called by main emu on final exit
1524 long CALLBACK SPUshutdown(void)
1539 RemoveStreams(); // no more streaming
1545 // SPUTEST: we don't test, we are always fine ;)
1546 long CALLBACK SPUtest(void)
1551 // SPUCONFIGURE: call config dialog
1552 long CALLBACK SPUconfigure(void)
1557 // StartCfgTool("CFG");
1562 // SPUABOUT: show about window
1563 void CALLBACK SPUabout(void)
1568 // StartCfgTool("ABOUT");
1573 // this functions will be called once,
1574 // passes a callback that should be called on SPU-IRQ/cdda volume change
1575 void CALLBACK SPUregisterCallback(void (CALLBACK *callback)(void))
1577 spu.irqCallback = callback;
1580 void CALLBACK SPUregisterCDDAVolume(void (CALLBACK *CDDAVcallback)(unsigned short,unsigned short))
1582 spu.cddavCallback = CDDAVcallback;
1585 void CALLBACK SPUregisterScheduleCb(void (CALLBACK *callback)(unsigned int))
1587 spu.scheduleCallback = callback;
1590 // COMMON PLUGIN INFO FUNCS
1592 char * CALLBACK PSEgetLibName(void)
1594 return _(libraryName);
1597 unsigned long CALLBACK PSEgetLibType(void)
1602 unsigned long CALLBACK PSEgetLibVersion(void)
1604 return (1 << 16) | (6 << 8);
1607 char * SPUgetLibInfos(void)
1609 return _(libraryInfo);
1614 void spu_get_debug_info(int *chans_out, int *run_chans, int *fmod_chans_out, int *noise_chans_out)
1616 int ch = 0, fmod_chans = 0, noise_chans = 0, irq_chans = 0;
1618 if (spu.s_chan == NULL)
1621 for(;ch<MAXCHAN;ch++)
1623 if (!(spu.dwChannelOn & (1<<ch)))
1625 if (spu.s_chan[ch].bFMod == 2)
1626 fmod_chans |= 1 << ch;
1627 if (spu.s_chan[ch].bNoise)
1628 noise_chans |= 1 << ch;
1629 if((spu.spuCtrl&CTRL_IRQ) && spu.s_chan[ch].pCurr <= spu.pSpuIrq && spu.s_chan[ch].pLoop <= spu.pSpuIrq)
1630 irq_chans |= 1 << ch;
1633 *chans_out = spu.dwChannelOn;
1634 *run_chans = ~spu.dwChannelOn & ~spu.dwChannelDead & irq_chans;
1635 *fmod_chans_out = fmod_chans;
1636 *noise_chans_out = noise_chans;
1639 // vim:shiftwidth=1:expandtab