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"
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 s_chan->pCurr = spu.spuMemC+((regAreaGet(ch,6)&~1)<<3);
252 spu.dwNewChannel&=~(1<<ch); // clear new channel bit
253 spu.dwChannelOn|=1<<ch;
254 spu.dwChannelDead&=~(1<<ch);
257 static void StartSound(int ch)
260 StartSoundSB(spu.SB + ch * SB_SIZE);
263 ////////////////////////////////////////////////////////////////////////
264 // ALL KIND OF HELPERS
265 ////////////////////////////////////////////////////////////////////////
267 INLINE int FModChangeFrequency(int *SB, int pitch, int ns)
269 unsigned int NP=pitch;
272 NP=((32768L+iFMod[ns])*NP)>>15;
274 if(NP>0x3fff) NP=0x3fff;
277 sinc=NP<<4; // calc frequency
278 if(spu_config.iUseInterpolation==1) // freq change in simple interpolation mode
285 ////////////////////////////////////////////////////////////////////////
287 INLINE void StoreInterpolationVal(int *SB, int sinc, int fa, int fmod_freq)
289 if(fmod_freq) // fmod freq channel
295 if(spu_config.iUseInterpolation>=2) // gauss/cubic interpolation
303 if(spu_config.iUseInterpolation==1) // simple interpolation
306 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'
309 SB[32] = 1; // -> flag: calc new interolation
311 else SB[29]=fa; // no interpolation
315 ////////////////////////////////////////////////////////////////////////
317 INLINE int iGetInterpolationVal(int *SB, int sinc, int spos, int fmod_freq)
321 if(fmod_freq) return SB[29];
323 switch(spu_config.iUseInterpolation)
325 //--------------------------------------------------//
326 case 3: // cubic interpolation
332 fa = gval(3) - 3*gval(2) + 3*gval(1) - gval0;
333 fa *= (xd - (2<<15)) / 6;
335 fa += gval(2) - gval(1) - gval(1) + gval0;
336 fa *= (xd - (1<<15)) >> 1;
338 fa += gval(1) - gval0;
344 //--------------------------------------------------//
345 case 2: // gauss interpolation
348 vl = (spos >> 6) & ~3;
350 vr=(gauss[vl]*(int)gval0) >> 15;
351 vr+=(gauss[vl+1]*gval(1)) >> 15;
352 vr+=(gauss[vl+2]*gval(2)) >> 15;
353 vr+=(gauss[vl+3]*gval(3)) >> 15;
356 //--------------------------------------------------//
357 case 1: // simple interpolation
359 if(sinc<0x10000L) // -> upsampling?
360 InterpolateUp(SB, sinc); // --> interpolate up
361 else InterpolateDown(SB, sinc); // --> else down
364 //--------------------------------------------------//
365 default: // no interpolation
369 //--------------------------------------------------//
375 static void decode_block_data(int *dest, const unsigned char *src, int predict_nr, int shift_factor)
377 static const int f[16][2] = {
385 int fa, s_1, s_2, d, s;
390 for (nSample = 0; nSample < 28; src++)
393 s = (int)(signed short)((d & 0x0f) << 12);
395 fa = s >> shift_factor;
396 fa += ((s_1 * f[predict_nr][0])>>6) + ((s_2 * f[predict_nr][1])>>6);
399 dest[nSample++] = fa;
401 s = (int)(signed short)((d & 0xf0) << 8);
402 fa = s >> shift_factor;
403 fa += ((s_1 * f[predict_nr][0])>>6) + ((s_2 * f[predict_nr][1])>>6);
406 dest[nSample++] = fa;
410 static int decode_block(void *unused, int ch, int *SB)
412 SPUCHAN *s_chan = &spu.s_chan[ch];
413 unsigned char *start;
414 int predict_nr, shift_factor, flags;
417 start = s_chan->pCurr; // set up the current pos
418 if (start == spu.spuMemC) // ?
421 if (s_chan->prevflags & 1) // 1: stop/loop
423 if (!(s_chan->prevflags & 2))
426 start = s_chan->pLoop;
429 check_irq(ch, start); // hack, see check_irq below..
431 predict_nr = start[0];
432 shift_factor = predict_nr & 0xf;
435 decode_block_data(SB, start + 2, predict_nr, shift_factor);
438 if (flags & 4 && (!s_chan->bIgnoreLoop))
439 s_chan->pLoop = start; // loop adress
443 if (flags & 1) { // 1: stop/loop
444 start = s_chan->pLoop;
445 check_irq(ch, start); // hack.. :(
448 if (start - spu.spuMemC >= 0x80000)
451 s_chan->pCurr = start; // store values for next cycle
452 s_chan->prevflags = flags;
457 // do block, but ignore sample data
458 static int skip_block(int ch)
460 SPUCHAN *s_chan = &spu.s_chan[ch];
461 unsigned char *start = s_chan->pCurr;
465 if (s_chan->prevflags & 1) {
466 if (!(s_chan->prevflags & 2))
469 start = s_chan->pLoop;
472 check_irq(ch, start);
476 s_chan->pLoop = start;
481 start = s_chan->pLoop;
482 check_irq(ch, start);
485 s_chan->pCurr = start;
486 s_chan->prevflags = flags;
491 // if irq is going to trigger sooner than in upd_samples, set upd_samples
492 static void scan_for_irq(int ch, unsigned int *upd_samples)
494 SPUCHAN *s_chan = &spu.s_chan[ch];
495 int pos, sinc, sinc_inv, end;
496 unsigned char *block;
499 block = s_chan->pCurr;
502 end = pos + *upd_samples * sinc;
504 pos += (28 - s_chan->iSBPos) << 16;
507 if (block == spu.pSpuIrq)
511 if (flags & 1) { // 1: stop/loop
512 block = s_chan->pLoop;
513 if (block == spu.pSpuIrq) // hack.. (see decode_block)
521 sinc_inv = s_chan->sinc_inv;
523 sinc_inv = s_chan->sinc_inv = (0x80000000u / (uint32_t)sinc) << 1;
526 *upd_samples = (((uint64_t)pos * sinc_inv) >> 32) + 1;
527 //xprintf("ch%02d: irq sched: %3d %03d\n",
528 // ch, *upd_samples, *upd_samples * 60 * 263 / 44100);
532 #define make_do_samples(name, fmod_code, interp_start, interp1_code, interp2_code, interp_end) \
533 static noinline int do_samples_##name( \
534 int (*decode_f)(void *context, int ch, int *SB), void *ctx, \
535 int ch, int ns_to, int *SB, int sinc, int *spos, int *sbpos) \
541 for (ns = 0; ns < ns_to; ns++) \
546 while (*spos >= 0x10000) \
548 fa = SB[(*sbpos)++]; \
552 d = decode_f(ctx, ch, SB); \
569 #define fmod_recv_check \
570 if(spu.s_chan[ch].bFMod==1 && iFMod[ns]) \
571 sinc = FModChangeFrequency(SB, spu.s_chan[ch].iRawPitch, ns)
573 make_do_samples(default, fmod_recv_check, ,
574 StoreInterpolationVal(SB, sinc, fa, spu.s_chan[ch].bFMod==2),
575 ChanBuf[ns] = iGetInterpolationVal(SB, sinc, *spos, spu.s_chan[ch].bFMod==2), )
576 make_do_samples(noint, , fa = SB[29], , ChanBuf[ns] = fa, SB[29] = fa)
578 #define simple_interp_store \
585 #define simple_interp_get \
586 if(sinc<0x10000) /* -> upsampling? */ \
587 InterpolateUp(SB, sinc); /* --> interpolate up */ \
588 else InterpolateDown(SB, sinc); /* --> else down */ \
591 make_do_samples(simple, , ,
592 simple_interp_store, simple_interp_get, )
594 static int do_samples_skip(int ch, int ns_to)
596 SPUCHAN *s_chan = &spu.s_chan[ch];
597 int spos = s_chan->spos;
598 int sinc = s_chan->sinc;
599 int ret = ns_to, ns, d;
601 spos += s_chan->iSBPos << 16;
603 for (ns = 0; ns < ns_to; ns++)
606 while (spos >= 28*0x10000)
615 s_chan->iSBPos = spos >> 16;
616 s_chan->spos = spos & 0xffff;
621 static void do_lsfr_samples(int ns_to, int ctrl,
622 unsigned int *dwNoiseCount, unsigned int *dwNoiseVal)
624 unsigned int counter = *dwNoiseCount;
625 unsigned int val = *dwNoiseVal;
626 unsigned int level, shift, bit;
629 // modified from DrHell/shalma, no fraction
630 level = (ctrl >> 10) & 0x0f;
631 level = 0x8000 >> level;
633 for (ns = 0; ns < ns_to; ns++)
636 if (counter >= level)
639 shift = (val >> 10) & 0x1f;
640 bit = (0x69696969 >> shift) & 1;
641 bit ^= (val >> 15) & 1;
642 val = (val << 1) | bit;
645 ChanBuf[ns] = (signed short)val;
648 *dwNoiseCount = counter;
652 static int do_samples_noise(int ch, int ns_to)
656 ret = do_samples_skip(ch, ns_to);
658 do_lsfr_samples(ns_to, spu.spuCtrl, &spu.dwNoiseCount, &spu.dwNoiseVal);
664 // asm code; lv and rv must be 0-3fff
665 extern void mix_chan(int *SSumLR, int count, int lv, int rv);
666 extern void mix_chan_rvb(int *SSumLR, int count, int lv, int rv, int *rvb);
668 static void mix_chan(int *SSumLR, int count, int lv, int rv)
670 const int *src = ChanBuf;
677 l = (sval * lv) >> 14;
678 r = (sval * rv) >> 14;
684 static void mix_chan_rvb(int *SSumLR, int count, int lv, int rv, int *rvb)
686 const int *src = ChanBuf;
695 l = (sval * lv) >> 14;
696 r = (sval * rv) >> 14;
705 // 0x0800-0x0bff Voice 1
706 // 0x0c00-0x0fff Voice 3
707 static noinline void do_decode_bufs(unsigned short *mem, int which,
708 int count, int decode_pos)
710 unsigned short *dst = &mem[0x800/2 + which*0x400/2];
711 const int *src = ChanBuf;
712 int cursor = decode_pos;
717 dst[cursor] = *src++;
721 // decode_pos is updated and irqs are checked later, after voice loop
724 static void do_silent_chans(int ns_to, int silentch)
730 mask = silentch & 0xffffff;
731 for (ch = 0; mask != 0; ch++, mask >>= 1)
733 if (!(mask & 1)) continue;
734 if (spu.dwChannelDead & (1<<ch)) continue;
736 s_chan = &spu.s_chan[ch];
737 if (s_chan->pCurr > spu.pSpuIrq && s_chan->pLoop > spu.pSpuIrq)
740 s_chan->spos += s_chan->iSBPos << 16;
743 s_chan->spos += s_chan->sinc * ns_to;
744 while (s_chan->spos >= 28 * 0x10000)
746 unsigned char *start = s_chan->pCurr;
749 if (start == s_chan->pCurr || start - spu.spuMemC < 0x1000)
751 // looping on self or stopped(?)
752 spu.dwChannelDead |= 1<<ch;
757 s_chan->spos -= 28 * 0x10000;
762 static void do_channels(int ns_to)
769 do_rvb = spu.rvb->StartAddr && spu_config.iUseReverb;
771 memset(RVB, 0, ns_to * sizeof(RVB[0]) * 2);
773 mask = spu.dwNewChannel & 0xffffff;
774 for (ch = 0; mask != 0; ch++, mask >>= 1) {
779 mask = spu.dwChannelOn & 0xffffff;
780 for (ch = 0; mask != 0; ch++, mask >>= 1) // loop em all...
782 if (!(mask & 1)) continue; // channel not playing? next
784 s_chan = &spu.s_chan[ch];
785 SB = spu.SB + ch * SB_SIZE;
789 d = do_samples_noise(ch, ns_to);
790 else if (s_chan->bFMod == 2
791 || (s_chan->bFMod == 0 && spu_config.iUseInterpolation == 0))
792 d = do_samples_noint(decode_block, NULL, ch, ns_to,
793 SB, sinc, &s_chan->spos, &s_chan->iSBPos);
794 else if (s_chan->bFMod == 0 && spu_config.iUseInterpolation == 1)
795 d = do_samples_simple(decode_block, NULL, ch, ns_to,
796 SB, sinc, &s_chan->spos, &s_chan->iSBPos);
798 d = do_samples_default(decode_block, NULL, ch, ns_to,
799 SB, sinc, &s_chan->spos, &s_chan->iSBPos);
801 d = MixADSR(&s_chan->ADSRX, d);
803 spu.dwChannelOn &= ~(1 << ch);
804 s_chan->ADSRX.EnvelopeVol = 0;
805 memset(&ChanBuf[d], 0, (ns_to - d) * sizeof(ChanBuf[0]));
808 if (ch == 1 || ch == 3)
810 do_decode_bufs(spu.spuMem, ch/2, ns_to, spu.decode_pos);
811 spu.decode_dirty_ch |= 1 << ch;
814 if (s_chan->bFMod == 2) // fmod freq channel
815 memcpy(iFMod, &ChanBuf, ns_to * sizeof(iFMod[0]));
816 if (s_chan->bRVBActive && do_rvb)
817 mix_chan_rvb(spu.SSumLR, ns_to, s_chan->iLeftVolume, s_chan->iRightVolume, RVB);
819 mix_chan(spu.SSumLR, ns_to, s_chan->iLeftVolume, s_chan->iRightVolume);
822 if (spu.rvb->StartAddr) {
824 REVERBDo(spu.SSumLR, RVB, ns_to, spu.rvb->CurrAddr);
826 spu.rvb->CurrAddr += ns_to / 2;
827 while (spu.rvb->CurrAddr >= 0x40000)
828 spu.rvb->CurrAddr -= 0x40000 - spu.rvb->StartAddr;
832 static void do_samples_finish(int *SSumLR, int ns_to,
833 int silentch, int decode_pos);
835 // optional worker thread handling
837 #if defined(THREAD_ENABLED) || defined(WANT_THREAD_CODE)
839 // worker thread state
840 static struct spu_worker {
843 unsigned int exit_thread;
844 unsigned int i_ready;
845 unsigned int i_reaped;
846 unsigned int last_boot_cnt; // dsp
847 unsigned int ram_dirty;
849 // aligning for C64X_DSP
850 unsigned int _pad0[128/4];
855 unsigned int active; // dsp
856 unsigned int boot_cnt;
858 unsigned int _pad1[128/4];
865 unsigned int channels_new;
866 unsigned int channels_on;
867 unsigned int channels_silent;
878 // might also want to add fmod flags..
880 int SSumLR[NSSIZE * 2];
884 #define WORK_MAXCNT (sizeof(worker->i) / sizeof(worker->i[0]))
885 #define WORK_I_MASK (WORK_MAXCNT - 1)
887 static void thread_work_start(void);
888 static void thread_work_wait_sync(struct work_item *work, int force);
889 static void thread_sync_caches(void);
890 static int thread_get_i_done(void);
892 static int decode_block_work(void *context, int ch, int *SB)
894 const unsigned char *ram = spu.spuMemC;
895 int predict_nr, shift_factor, flags;
896 struct work_item *work = context;
897 int start = work->ch[ch].start;
898 int loop = work->ch[ch].loop;
900 predict_nr = ram[start];
901 shift_factor = predict_nr & 0xf;
904 decode_block_data(SB, ram + start + 2, predict_nr, shift_factor);
906 flags = ram[start + 1];
908 loop = start; // loop adress
912 if (flags & 1) // 1: stop/loop
915 work->ch[ch].start = start & 0x7ffff;
916 work->ch[ch].loop = loop;
921 static void queue_channel_work(int ns_to, unsigned int silentch)
923 struct work_item *work;
928 work = &worker->i[worker->i_ready & WORK_I_MASK];
930 work->ctrl = spu.spuCtrl;
931 work->decode_pos = spu.decode_pos;
932 work->channels_silent = silentch;
934 mask = work->channels_new = spu.dwNewChannel & 0xffffff;
935 for (ch = 0; mask != 0; ch++, mask >>= 1) {
940 mask = work->channels_on = spu.dwChannelOn & 0xffffff;
941 spu.decode_dirty_ch |= mask & 0x0a;
943 for (ch = 0; mask != 0; ch++, mask >>= 1)
945 if (!(mask & 1)) continue;
947 s_chan = &spu.s_chan[ch];
948 work->ch[ch].spos = s_chan->spos;
949 work->ch[ch].sbpos = s_chan->iSBPos;
950 work->ch[ch].sinc = s_chan->sinc;
951 work->ch[ch].adsr = s_chan->ADSRX;
952 work->ch[ch].vol_l = s_chan->iLeftVolume;
953 work->ch[ch].vol_r = s_chan->iRightVolume;
954 work->ch[ch].start = s_chan->pCurr - spu.spuMemC;
955 work->ch[ch].loop = s_chan->pLoop - spu.spuMemC;
956 if (s_chan->prevflags & 1)
957 work->ch[ch].start = work->ch[ch].loop;
959 d = do_samples_skip(ch, ns_to);
960 work->ch[ch].ns_to = d;
962 // note: d is not accurate on skip
963 d = SkipADSR(&s_chan->ADSRX, d);
965 spu.dwChannelOn &= ~(1 << ch);
966 s_chan->ADSRX.EnvelopeVol = 0;
971 if (spu.rvb->StartAddr) {
972 if (spu_config.iUseReverb)
973 work->rvb_addr = spu.rvb->CurrAddr;
975 spu.rvb->CurrAddr += ns_to / 2;
976 while (spu.rvb->CurrAddr >= 0x40000)
977 spu.rvb->CurrAddr -= 0x40000 - spu.rvb->StartAddr;
984 static void do_channel_work(struct work_item *work)
987 unsigned int decode_dirty_ch = 0;
988 const SPUCHAN *s_chan;
989 int *SB, sinc, spos, sbpos;
995 memset(RVB, 0, ns_to * sizeof(RVB[0]) * 2);
997 mask = work->channels_new;
998 for (ch = 0; mask != 0; ch++, mask >>= 1) {
1000 StartSoundSB(spu.SB + ch * SB_SIZE);
1003 mask = work->channels_on;
1004 for (ch = 0; mask != 0; ch++, mask >>= 1)
1006 if (!(mask & 1)) continue;
1008 d = work->ch[ch].ns_to;
1009 spos = work->ch[ch].spos;
1010 sbpos = work->ch[ch].sbpos;
1011 sinc = work->ch[ch].sinc;
1013 s_chan = &spu.s_chan[ch];
1014 SB = spu.SB + ch * SB_SIZE;
1017 do_lsfr_samples(d, work->ctrl, &spu.dwNoiseCount, &spu.dwNoiseVal);
1018 else if (s_chan->bFMod == 2
1019 || (s_chan->bFMod == 0 && spu_config.iUseInterpolation == 0))
1020 do_samples_noint(decode_block_work, work, ch, d, SB, sinc, &spos, &sbpos);
1021 else if (s_chan->bFMod == 0 && spu_config.iUseInterpolation == 1)
1022 do_samples_simple(decode_block_work, work, ch, d, SB, sinc, &spos, &sbpos);
1024 do_samples_default(decode_block_work, work, ch, d, SB, sinc, &spos, &sbpos);
1026 d = MixADSR(&work->ch[ch].adsr, d);
1028 work->ch[ch].adsr.EnvelopeVol = 0;
1029 memset(&ChanBuf[d], 0, (ns_to - d) * sizeof(ChanBuf[0]));
1032 if (ch == 1 || ch == 3)
1034 do_decode_bufs(spu.spuMem, ch/2, ns_to, work->decode_pos);
1035 decode_dirty_ch |= 1 << ch;
1038 if (s_chan->bFMod == 2) // fmod freq channel
1039 memcpy(iFMod, &ChanBuf, ns_to * sizeof(iFMod[0]));
1040 if (s_chan->bRVBActive && work->rvb_addr)
1041 mix_chan_rvb(work->SSumLR, ns_to,
1042 work->ch[ch].vol_l, work->ch[ch].vol_r, RVB);
1044 mix_chan(work->SSumLR, ns_to, work->ch[ch].vol_l, work->ch[ch].vol_r);
1048 REVERBDo(work->SSumLR, RVB, ns_to, work->rvb_addr);
1051 static void sync_worker_thread(int force)
1053 struct work_item *work;
1054 int done, used_space;
1056 // rvb offsets will change, thread may be using them
1057 force |= spu.rvb->dirty && spu.rvb->StartAddr;
1059 done = thread_get_i_done() - worker->i_reaped;
1060 used_space = worker->i_ready - worker->i_reaped;
1062 //printf("done: %d use: %d dsp: %u/%u\n", done, used_space,
1063 // worker->boot_cnt, worker->i_done);
1065 while ((force && used_space > 0) || used_space >= WORK_MAXCNT || done > 0) {
1066 work = &worker->i[worker->i_reaped & WORK_I_MASK];
1067 thread_work_wait_sync(work, force);
1069 do_samples_finish(work->SSumLR, work->ns_to,
1070 work->channels_silent, work->decode_pos);
1073 done = thread_get_i_done() - worker->i_reaped;
1074 used_space = worker->i_ready - worker->i_reaped;
1077 thread_sync_caches();
1082 static void queue_channel_work(int ns_to, int silentch) {}
1083 static void sync_worker_thread(int force) {}
1085 static const void * const worker = NULL;
1087 #endif // THREAD_ENABLED
1089 ////////////////////////////////////////////////////////////////////////
1090 // MAIN SPU FUNCTION
1091 // here is the main job handler...
1092 ////////////////////////////////////////////////////////////////////////
1094 void do_samples(unsigned int cycles_to, int do_direct)
1096 unsigned int silentch;
1100 cycle_diff = cycles_to - spu.cycles_played;
1101 if (cycle_diff < -2*1048576 || cycle_diff > 2*1048576)
1103 //xprintf("desync %u %d\n", cycles_to, cycle_diff);
1104 spu.cycles_played = cycles_to;
1108 silentch = ~(spu.dwChannelOn | spu.dwNewChannel) & 0xffffff;
1110 do_direct |= (silentch == 0xffffff);
1112 sync_worker_thread(do_direct);
1114 if (cycle_diff < 2 * 768)
1117 ns_to = (cycle_diff / 768 + 1) & ~1;
1118 if (ns_to > NSSIZE) {
1119 // should never happen
1120 //xprintf("ns_to oflow %d %d\n", ns_to, NSSIZE);
1124 //////////////////////////////////////////////////////
1125 // special irq handling in the decode buffers (0x0000-0x1000)
1127 // the decode buffers are located in spu memory in the following way:
1128 // 0x0000-0x03ff CD audio left
1129 // 0x0400-0x07ff CD audio right
1130 // 0x0800-0x0bff Voice 1
1131 // 0x0c00-0x0fff Voice 3
1132 // and decoded data is 16 bit for one sample
1134 // even if voices 1/3 are off or no cd audio is playing, the internal
1135 // play positions will move on and wrap after 0x400 bytes.
1136 // Therefore: we just need a pointer from spumem+0 to spumem+3ff, and
1137 // increase this pointer on each sample by 2 bytes. If this pointer
1138 // (or 0x400 offsets of this pointer) hits the spuirq address, we generate
1141 if (unlikely((spu.spuCtrl & CTRL_IRQ)
1142 && spu.pSpuIrq < spu.spuMemC+0x1000))
1144 int irq_pos = (spu.pSpuIrq - spu.spuMemC) / 2 & 0x1ff;
1145 int left = (irq_pos - spu.decode_pos) & 0x1ff;
1146 if (0 < left && left <= ns_to)
1148 //xprintf("decoder irq %x\n", spu.decode_pos);
1153 if (unlikely(spu.rvb->dirty))
1156 if (do_direct || worker == NULL || !spu_config.iUseThread) {
1158 do_samples_finish(spu.SSumLR, ns_to, silentch, spu.decode_pos);
1161 queue_channel_work(ns_to, silentch);
1164 // advance "stopped" channels that can cause irqs
1165 // (all chans are always playing on the real thing..)
1166 if (spu.spuCtrl & CTRL_IRQ)
1167 do_silent_chans(ns_to, silentch);
1169 spu.cycles_played += ns_to * 768;
1170 spu.decode_pos = (spu.decode_pos + ns_to) & 0x1ff;
1173 static void do_samples_finish(int *SSumLR, int ns_to,
1174 int silentch, int decode_pos)
1176 int volmult = spu_config.iVolume;
1180 // must clear silent channel decode buffers
1181 if(unlikely(silentch & spu.decode_dirty_ch & (1<<1)))
1183 memset(&spu.spuMem[0x800/2], 0, 0x400);
1184 spu.decode_dirty_ch &= ~(1<<1);
1186 if(unlikely(silentch & spu.decode_dirty_ch & (1<<3)))
1188 memset(&spu.spuMem[0xc00/2], 0, 0x400);
1189 spu.decode_dirty_ch &= ~(1<<3);
1192 MixXA(SSumLR, ns_to, decode_pos);
1194 if((spu.spuCtrl&0x4000)==0) // muted? (rare, don't optimize for this)
1196 memset(spu.pS, 0, ns_to * 2 * sizeof(spu.pS[0]));
1197 spu.pS += ns_to * 2;
1200 for (ns = 0; ns < ns_to * 2; )
1202 d = SSumLR[ns]; SSumLR[ns] = 0;
1203 d = d * volmult >> 10;
1208 d = SSumLR[ns]; SSumLR[ns] = 0;
1209 d = d * volmult >> 10;
1216 void schedule_next_irq(void)
1218 unsigned int upd_samples;
1221 if (spu.scheduleCallback == NULL)
1224 upd_samples = 44100 / 50;
1226 for (ch = 0; ch < MAXCHAN; ch++)
1228 if (spu.dwChannelDead & (1 << ch))
1230 if ((unsigned long)(spu.pSpuIrq - spu.s_chan[ch].pCurr) > IRQ_NEAR_BLOCKS * 16
1231 && (unsigned long)(spu.pSpuIrq - spu.s_chan[ch].pLoop) > IRQ_NEAR_BLOCKS * 16)
1234 scan_for_irq(ch, &upd_samples);
1237 if (unlikely(spu.pSpuIrq < spu.spuMemC + 0x1000))
1239 int irq_pos = (spu.pSpuIrq - spu.spuMemC) / 2 & 0x1ff;
1240 int left = (irq_pos - spu.decode_pos) & 0x1ff;
1241 if (0 < left && left < upd_samples) {
1242 //xprintf("decode: %3d (%3d/%3d)\n", left, spu.decode_pos, irq_pos);
1247 if (upd_samples < 44100 / 50)
1248 spu.scheduleCallback(upd_samples * 768);
1251 // SPU ASYNC... even newer epsxe func
1252 // 1 time every 'cycle' cycles... harhar
1254 // rearmed: called dynamically now
1256 void CALLBACK SPUasync(unsigned int cycle, unsigned int flags)
1258 do_samples(cycle, spu_config.iUseFixedUpdates);
1260 if (spu.spuCtrl & CTRL_IRQ)
1261 schedule_next_irq();
1264 out_current->feed(spu.pSpuBuffer, (unsigned char *)spu.pS - spu.pSpuBuffer);
1265 spu.pS = (short *)spu.pSpuBuffer;
1267 if (spu_config.iTempo) {
1268 if (!out_current->busy())
1269 // cause more samples to be generated
1270 // (and break some games because of bad sync)
1271 spu.cycles_played -= 44100 / 60 / 2 * 768;
1276 // SPU UPDATE... new epsxe func
1277 // 1 time every 32 hsync lines
1278 // (312/32)x50 in pal
1279 // (262/32)x60 in ntsc
1281 // since epsxe 1.5.2 (linux) uses SPUupdate, not SPUasync, I will
1282 // leave that func in the linux port, until epsxe linux is using
1283 // the async function as well
1285 void CALLBACK SPUupdate(void)
1291 void CALLBACK SPUplayADPCMchannel(xa_decode_t *xap)
1294 if(!xap->freq) return; // no xa freq ? bye
1296 FeedXA(xap); // call main XA feeder
1300 int CALLBACK SPUplayCDDAchannel(short *pcm, int nbytes)
1302 if (!pcm) return -1;
1303 if (nbytes<=0) return -1;
1305 return FeedCDDA((unsigned char *)pcm, nbytes);
1308 // to be called after state load
1309 void ClearWorkingState(void)
1311 memset(iFMod, 0, sizeof(iFMod));
1312 spu.pS=(short *)spu.pSpuBuffer; // setup soundbuffer pointer
1315 // SETUPSTREAMS: init most of the spu buffers
1316 static void SetupStreams(void)
1318 spu.pSpuBuffer = (unsigned char *)malloc(32768); // alloc mixing buffer
1319 spu.SSumLR = calloc(NSSIZE * 2, sizeof(spu.SSumLR[0]));
1321 spu.XAStart = malloc(44100 * sizeof(uint32_t)); // alloc xa buffer
1322 spu.XAEnd = spu.XAStart + 44100;
1323 spu.XAPlay = spu.XAStart;
1324 spu.XAFeed = spu.XAStart;
1326 spu.CDDAStart = malloc(CDDA_BUFFER_SIZE); // alloc cdda buffer
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;
1492 spu.s_chan[i].bIgnoreLoop = 0;
1495 spu.bSpuInit=1; // flag: we are inited
1500 // SPUOPEN: called by main emu after init
1501 long CALLBACK SPUopen(void)
1503 if (spu.bSPUIsOpen) return 0; // security for some stupid main emus
1505 SetupSound(); // setup sound (before init!)
1509 return PSE_SPU_ERR_SUCCESS;
1512 // SPUCLOSE: called before shutdown
1513 long CALLBACK SPUclose(void)
1515 if (!spu.bSPUIsOpen) return 0; // some security
1517 spu.bSPUIsOpen = 0; // no more open
1519 out_current->finish(); // no more sound handling
1524 // SPUSHUTDOWN: called by main emu on final exit
1525 long CALLBACK SPUshutdown(void)
1540 RemoveStreams(); // no more streaming
1546 // SPUTEST: we don't test, we are always fine ;)
1547 long CALLBACK SPUtest(void)
1552 // SPUCONFIGURE: call config dialog
1553 long CALLBACK SPUconfigure(void)
1558 // StartCfgTool("CFG");
1563 // SPUABOUT: show about window
1564 void CALLBACK SPUabout(void)
1569 // StartCfgTool("ABOUT");
1574 // this functions will be called once,
1575 // passes a callback that should be called on SPU-IRQ/cdda volume change
1576 void CALLBACK SPUregisterCallback(void (CALLBACK *callback)(void))
1578 spu.irqCallback = callback;
1581 void CALLBACK SPUregisterCDDAVolume(void (CALLBACK *CDDAVcallback)(short, short))
1583 spu.cddavCallback = CDDAVcallback;
1586 void CALLBACK SPUregisterScheduleCb(void (CALLBACK *callback)(unsigned int))
1588 spu.scheduleCallback = callback;
1591 // COMMON PLUGIN INFO FUNCS
1593 char * CALLBACK PSEgetLibName(void)
1595 return _(libraryName);
1598 unsigned long CALLBACK PSEgetLibType(void)
1603 unsigned long CALLBACK PSEgetLibVersion(void)
1605 return (1 << 16) | (6 << 8);
1608 char * SPUgetLibInfos(void)
1610 return _(libraryInfo);
1615 void spu_get_debug_info(int *chans_out, int *run_chans, int *fmod_chans_out, int *noise_chans_out)
1617 int ch = 0, fmod_chans = 0, noise_chans = 0, irq_chans = 0;
1619 if (spu.s_chan == NULL)
1622 for(;ch<MAXCHAN;ch++)
1624 if (!(spu.dwChannelOn & (1<<ch)))
1626 if (spu.s_chan[ch].bFMod == 2)
1627 fmod_chans |= 1 << ch;
1628 if (spu.s_chan[ch].bNoise)
1629 noise_chans |= 1 << ch;
1630 if((spu.spuCtrl&CTRL_IRQ) && spu.s_chan[ch].pCurr <= spu.pSpuIrq && spu.s_chan[ch].pLoop <= spu.pSpuIrq)
1631 irq_chans |= 1 << ch;
1634 *chans_out = spu.dwChannelOn;
1635 *run_chans = ~spu.dwChannelOn & ~spu.dwChannelDead & irq_chans;
1636 *fmod_chans_out = fmod_chans;
1637 *noise_chans_out = noise_chans;
1640 // vim:shiftwidth=1:expandtab