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(THREAD_ENABLED) && !defined(_WIN32) && !defined(NO_OS)
22 #define THREAD_ENABLED 1
28 #include "externals.h"
29 #include "registers.h"
31 #include "spu_config.h"
34 #include "arm_features.h"
38 #define ssat32_to_16(v) \
39 asm("ssat %0,#16,%1" : "=r" (v) : "r" (v))
41 #define ssat32_to_16(v) do { \
42 if (v < -32768) v = -32768; \
43 else if (v > 32767) v = 32767; \
47 #define PSXCLK 33868800 /* 33.8688 MHz */
49 // intended to be ~1 frame
50 #define IRQ_NEAR_BLOCKS 32
53 #if defined (USEMACOSX)
54 static char * libraryName = N_("Mac OS X Sound");
55 #elif defined (USEALSA)
56 static char * libraryName = N_("ALSA Sound");
57 #elif defined (USEOSS)
58 static char * libraryName = N_("OSS Sound");
59 #elif defined (USESDL)
60 static char * libraryName = N_("SDL Sound");
61 #elif defined (USEPULSEAUDIO)
62 static char * libraryName = N_("PulseAudio Sound");
64 static char * libraryName = N_("NULL Sound");
67 static char * libraryInfo = N_("P.E.Op.S. Sound Driver V1.7\nCoded by Pete Bernert and the P.E.Op.S. team\n");
75 static int iFMod[NSSIZE];
76 static int RVB[NSSIZE * 2];
79 #define CDDA_BUFFER_SIZE (16384 * sizeof(uint32_t)) // must be power of 2
81 ////////////////////////////////////////////////////////////////////////
83 ////////////////////////////////////////////////////////////////////////
85 // dirty inline func includes
90 ////////////////////////////////////////////////////////////////////////
91 // helpers for simple interpolation
94 // easy interpolation on upsampling, no special filter, just "Pete's common sense" tm
96 // instead of having n equal sample values in a row like:
100 // we compare the current delta change with the next delta change.
102 // if curr_delta is positive,
104 // - and next delta is smaller (or changing direction):
108 // - and next delta significant (at least twice) bigger:
112 // - and next delta is nearly same:
117 // if curr_delta is negative,
119 // - and next delta is smaller (or changing direction):
123 // - and next delta significant (at least twice) bigger:
127 // - and next delta is nearly same:
132 static void InterpolateUp(int *SB, int sinc)
134 if(SB[32]==1) // flag == 1? calc step and set flag... and don't change the value in this pass
136 const int id1=SB[30]-SB[29]; // curr delta to next val
137 const int id2=SB[31]-SB[30]; // and next delta to next-next val :)
141 if(id1>0) // curr delta positive
144 {SB[28]=id1;SB[32]=2;}
147 SB[28]=(id1*sinc)>>16;
149 SB[28]=(id1*sinc)>>17;
151 else // curr delta negative
154 {SB[28]=id1;SB[32]=2;}
157 SB[28]=(id1*sinc)>>16;
159 SB[28]=(id1*sinc)>>17;
163 if(SB[32]==2) // flag 1: calc step and set flag... and don't change the value in this pass
167 SB[28]=(SB[28]*sinc)>>17;
169 // SB[29]=SB[30]-(SB[28]*((0x10000/sinc)-1));
173 else // no flags? add bigger val (if possible), calc smaller step, set flag1
178 // even easier interpolation on downsampling, also no special filter, again just "Pete's common sense" tm
181 static void InterpolateDown(int *SB, int sinc)
183 if(sinc>=0x20000L) // we would skip at least one val?
185 SB[29]+=(SB[30]-SB[29])/2; // add easy weight
186 if(sinc>=0x30000L) // we would skip even more vals?
187 SB[29]+=(SB[31]-SB[30])/2; // add additional next weight
191 ////////////////////////////////////////////////////////////////////////
192 // helpers for gauss interpolation
194 #define gval0 (((short*)(&SB[29]))[gpos&3])
195 #define gval(x) ((int)((short*)(&SB[29]))[(gpos+x)&3])
199 ////////////////////////////////////////////////////////////////////////
203 static void do_irq(void)
205 //if(!(spu.spuStat & STAT_IRQ))
207 spu.spuStat |= STAT_IRQ; // asserted status?
208 if(spu.irqCallback) spu.irqCallback();
212 static int check_irq(int ch, unsigned char *pos)
214 if((spu.spuCtrl & (CTRL_ON|CTRL_IRQ)) == (CTRL_ON|CTRL_IRQ) && pos == spu.pSpuIrq)
216 //printf("ch%d irq %04x\n", ch, pos - spu.spuMemC);
223 void check_irq_io(unsigned int addr)
225 unsigned int irq_addr = regAreaGet(H_SPUirqAddr) << 3;
227 if((spu.spuCtrl & (CTRL_ON|CTRL_IRQ)) == (CTRL_ON|CTRL_IRQ) && addr == irq_addr)
229 //printf("io irq %04x\n", irq_addr);
234 ////////////////////////////////////////////////////////////////////////
235 // START SOUND... called by main thread to setup a new sound on a channel
236 ////////////////////////////////////////////////////////////////////////
238 static void StartSoundSB(int *SB)
240 SB[26]=0; // init mixing vars
244 SB[29]=0; // init our interpolation helpers
249 static void StartSoundMain(int ch)
251 SPUCHAN *s_chan = &spu.s_chan[ch];
260 s_chan->pCurr = spu.spuMemC + ((regAreaGetCh(ch, 6) & ~1) << 3);
262 spu.dwNewChannel&=~(1<<ch); // clear new channel bit
263 spu.dwChannelDead&=~(1<<ch);
264 spu.dwChannelsAudible|=1<<ch;
267 static void StartSound(int ch)
270 StartSoundSB(spu.SB + ch * SB_SIZE);
273 ////////////////////////////////////////////////////////////////////////
274 // ALL KIND OF HELPERS
275 ////////////////////////////////////////////////////////////////////////
277 INLINE int FModChangeFrequency(int *SB, int pitch, int ns)
279 unsigned int NP=pitch;
282 NP=((32768L+iFMod[ns])*NP)>>15;
284 if(NP>0x3fff) NP=0x3fff;
287 sinc=NP<<4; // calc frequency
289 SB[32]=1; // reset interpolation
294 ////////////////////////////////////////////////////////////////////////
296 INLINE void StoreInterpolationVal(int *SB, int sinc, int fa, int fmod_freq)
298 if(fmod_freq) // fmod freq channel
304 if(spu_config.iUseInterpolation>=2) // gauss/cubic interpolation
312 if(spu_config.iUseInterpolation==1) // simple interpolation
315 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'
318 SB[32] = 1; // -> flag: calc new interolation
320 else SB[29]=fa; // no interpolation
324 ////////////////////////////////////////////////////////////////////////
326 INLINE int iGetInterpolationVal(int *SB, int sinc, int spos, int fmod_freq)
330 if(fmod_freq) return SB[29];
332 switch(spu_config.iUseInterpolation)
334 //--------------------------------------------------//
335 case 3: // cubic interpolation
341 fa = gval(3) - 3*gval(2) + 3*gval(1) - gval0;
342 fa *= (xd - (2<<15)) / 6;
344 fa += gval(2) - gval(1) - gval(1) + gval0;
345 fa *= (xd - (1<<15)) >> 1;
347 fa += gval(1) - gval0;
353 //--------------------------------------------------//
354 case 2: // gauss interpolation
357 vl = (spos >> 6) & ~3;
359 vr=(gauss[vl]*(int)gval0) >> 15;
360 vr+=(gauss[vl+1]*gval(1)) >> 15;
361 vr+=(gauss[vl+2]*gval(2)) >> 15;
362 vr+=(gauss[vl+3]*gval(3)) >> 15;
365 //--------------------------------------------------//
366 case 1: // simple interpolation
368 if(sinc<0x10000L) // -> upsampling?
369 InterpolateUp(SB, sinc); // --> interpolate up
370 else InterpolateDown(SB, sinc); // --> else down
373 //--------------------------------------------------//
374 default: // no interpolation
378 //--------------------------------------------------//
384 static void decode_block_data(int *dest, const unsigned char *src, int predict_nr, int shift_factor)
386 static const int f[16][2] = {
394 int fa, s_1, s_2, d, s;
399 for (nSample = 0; nSample < 28; src++)
402 s = (int)(signed short)((d & 0x0f) << 12);
404 fa = s >> shift_factor;
405 fa += ((s_1 * f[predict_nr][0])>>6) + ((s_2 * f[predict_nr][1])>>6);
408 dest[nSample++] = fa;
410 s = (int)(signed short)((d & 0xf0) << 8);
411 fa = s >> shift_factor;
412 fa += ((s_1 * f[predict_nr][0])>>6) + ((s_2 * f[predict_nr][1])>>6);
415 dest[nSample++] = fa;
419 static int decode_block(void *unused, int ch, int *SB)
421 SPUCHAN *s_chan = &spu.s_chan[ch];
422 unsigned char *start;
423 int predict_nr, shift_factor, flags;
426 start = s_chan->pCurr; // set up the current pos
427 if (start == spu.spuMemC) // ?
430 if (s_chan->prevflags & 1) // 1: stop/loop
432 if (!(s_chan->prevflags & 2))
435 start = s_chan->pLoop;
438 check_irq(ch, start);
440 predict_nr = start[0];
441 shift_factor = predict_nr & 0xf;
444 decode_block_data(SB, start + 2, predict_nr, shift_factor);
447 if (flags & 4 && !s_chan->bIgnoreLoop)
448 s_chan->pLoop = start; // loop adress
452 s_chan->pCurr = start; // store values for next cycle
453 s_chan->prevflags = flags;
458 // do block, but ignore sample data
459 static int skip_block(int ch)
461 SPUCHAN *s_chan = &spu.s_chan[ch];
462 unsigned char *start = s_chan->pCurr;
466 if (s_chan->prevflags & 1) {
467 if (!(s_chan->prevflags & 2))
470 start = s_chan->pLoop;
473 check_irq(ch, start);
476 if (flags & 4 && !s_chan->bIgnoreLoop)
477 s_chan->pLoop = start;
481 s_chan->pCurr = start;
482 s_chan->prevflags = flags;
487 // if irq is going to trigger sooner than in upd_samples, set upd_samples
488 static void scan_for_irq(int ch, unsigned int *upd_samples)
490 SPUCHAN *s_chan = &spu.s_chan[ch];
491 int pos, sinc, sinc_inv, end;
492 unsigned char *block;
495 block = s_chan->pCurr;
498 end = pos + *upd_samples * sinc;
500 pos += (28 - s_chan->iSBPos) << 16;
503 if (block == spu.pSpuIrq)
507 if (flags & 1) { // 1: stop/loop
508 block = s_chan->pLoop;
515 sinc_inv = s_chan->sinc_inv;
517 sinc_inv = s_chan->sinc_inv = (0x80000000u / (uint32_t)sinc) << 1;
520 *upd_samples = (((uint64_t)pos * sinc_inv) >> 32) + 1;
521 //xprintf("ch%02d: irq sched: %3d %03d\n",
522 // ch, *upd_samples, *upd_samples * 60 * 263 / 44100);
526 #define make_do_samples(name, fmod_code, interp_start, interp1_code, interp2_code, interp_end) \
527 static noinline int do_samples_##name( \
528 int (*decode_f)(void *context, int ch, int *SB), void *ctx, \
529 int ch, int ns_to, int *SB, int sinc, int *spos, int *sbpos) \
535 for (ns = 0; ns < ns_to; ns++) \
540 while (*spos >= 0x10000) \
542 fa = SB[(*sbpos)++]; \
546 d = decode_f(ctx, ch, SB); \
563 #define fmod_recv_check \
564 if(spu.s_chan[ch].bFMod==1 && iFMod[ns]) \
565 sinc = FModChangeFrequency(SB, spu.s_chan[ch].iRawPitch, ns)
567 make_do_samples(default, fmod_recv_check, ,
568 StoreInterpolationVal(SB, sinc, fa, spu.s_chan[ch].bFMod==2),
569 ChanBuf[ns] = iGetInterpolationVal(SB, sinc, *spos, spu.s_chan[ch].bFMod==2), )
570 make_do_samples(noint, , fa = SB[29], , ChanBuf[ns] = fa, SB[29] = fa)
572 #define simple_interp_store \
579 #define simple_interp_get \
580 if(sinc<0x10000) /* -> upsampling? */ \
581 InterpolateUp(SB, sinc); /* --> interpolate up */ \
582 else InterpolateDown(SB, sinc); /* --> else down */ \
585 make_do_samples(simple, , ,
586 simple_interp_store, simple_interp_get, )
588 static int do_samples_skip(int ch, int ns_to)
590 SPUCHAN *s_chan = &spu.s_chan[ch];
591 int spos = s_chan->spos;
592 int sinc = s_chan->sinc;
593 int ret = ns_to, ns, d;
595 spos += s_chan->iSBPos << 16;
597 for (ns = 0; ns < ns_to; ns++)
600 while (spos >= 28*0x10000)
609 s_chan->iSBPos = spos >> 16;
610 s_chan->spos = spos & 0xffff;
615 static void do_lsfr_samples(int ns_to, int ctrl,
616 unsigned int *dwNoiseCount, unsigned int *dwNoiseVal)
618 unsigned int counter = *dwNoiseCount;
619 unsigned int val = *dwNoiseVal;
620 unsigned int level, shift, bit;
623 // modified from DrHell/shalma, no fraction
624 level = (ctrl >> 10) & 0x0f;
625 level = 0x8000 >> level;
627 for (ns = 0; ns < ns_to; ns++)
630 if (counter >= level)
633 shift = (val >> 10) & 0x1f;
634 bit = (0x69696969 >> shift) & 1;
635 bit ^= (val >> 15) & 1;
636 val = (val << 1) | bit;
639 ChanBuf[ns] = (signed short)val;
642 *dwNoiseCount = counter;
646 static int do_samples_noise(int ch, int ns_to)
650 ret = do_samples_skip(ch, ns_to);
652 do_lsfr_samples(ns_to, spu.spuCtrl, &spu.dwNoiseCount, &spu.dwNoiseVal);
658 // asm code; lv and rv must be 0-3fff
659 extern void mix_chan(int *SSumLR, int count, int lv, int rv);
660 extern void mix_chan_rvb(int *SSumLR, int count, int lv, int rv, int *rvb);
662 static void mix_chan(int *SSumLR, int count, int lv, int rv)
664 const int *src = ChanBuf;
671 l = (sval * lv) >> 14;
672 r = (sval * rv) >> 14;
678 static void mix_chan_rvb(int *SSumLR, int count, int lv, int rv, int *rvb)
680 const int *src = ChanBuf;
689 l = (sval * lv) >> 14;
690 r = (sval * rv) >> 14;
699 // 0x0800-0x0bff Voice 1
700 // 0x0c00-0x0fff Voice 3
701 static noinline void do_decode_bufs(unsigned short *mem, int which,
702 int count, int decode_pos)
704 unsigned short *dst = &mem[0x800/2 + which*0x400/2];
705 const int *src = ChanBuf;
706 int cursor = decode_pos;
711 dst[cursor] = *src++;
715 // decode_pos is updated and irqs are checked later, after voice loop
718 static void do_silent_chans(int ns_to, int silentch)
724 mask = silentch & 0xffffff;
725 for (ch = 0; mask != 0; ch++, mask >>= 1)
727 if (!(mask & 1)) continue;
728 if (spu.dwChannelDead & (1<<ch)) continue;
730 s_chan = &spu.s_chan[ch];
731 if (s_chan->pCurr > spu.pSpuIrq && s_chan->pLoop > spu.pSpuIrq)
734 s_chan->spos += s_chan->iSBPos << 16;
737 s_chan->spos += s_chan->sinc * ns_to;
738 while (s_chan->spos >= 28 * 0x10000)
740 unsigned char *start = s_chan->pCurr;
743 if (start == s_chan->pCurr || start - spu.spuMemC < 0x1000)
745 // looping on self or stopped(?)
746 spu.dwChannelDead |= 1<<ch;
751 s_chan->spos -= 28 * 0x10000;
756 static void do_channels(int ns_to)
763 do_rvb = spu.rvb->StartAddr && spu_config.iUseReverb;
765 memset(RVB, 0, ns_to * sizeof(RVB[0]) * 2);
767 mask = spu.dwNewChannel & 0xffffff;
768 for (ch = 0; mask != 0; ch++, mask >>= 1) {
773 mask = spu.dwChannelsAudible & 0xffffff;
774 for (ch = 0; mask != 0; ch++, mask >>= 1) // loop em all...
776 if (!(mask & 1)) continue; // channel not playing? next
778 s_chan = &spu.s_chan[ch];
779 SB = spu.SB + ch * SB_SIZE;
781 if (spu.s_chan[ch].bNewPitch)
782 SB[32] = 1; // reset interpolation
783 spu.s_chan[ch].bNewPitch = 0;
786 d = do_samples_noise(ch, ns_to);
787 else if (s_chan->bFMod == 2
788 || (s_chan->bFMod == 0 && spu_config.iUseInterpolation == 0))
789 d = do_samples_noint(decode_block, NULL, ch, ns_to,
790 SB, sinc, &s_chan->spos, &s_chan->iSBPos);
791 else if (s_chan->bFMod == 0 && spu_config.iUseInterpolation == 1)
792 d = do_samples_simple(decode_block, NULL, ch, ns_to,
793 SB, sinc, &s_chan->spos, &s_chan->iSBPos);
795 d = do_samples_default(decode_block, NULL, ch, ns_to,
796 SB, sinc, &s_chan->spos, &s_chan->iSBPos);
798 d = MixADSR(&s_chan->ADSRX, d);
800 spu.dwChannelsAudible &= ~(1 << ch);
801 s_chan->ADSRX.State = ADSR_RELEASE;
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;
874 unsigned short ns_to;
875 unsigned short bNoise:1;
876 unsigned short bFMod:2;
877 unsigned short bRVBActive:1;
878 unsigned short bNewPitch:1;
881 int SSumLR[NSSIZE * 2];
885 #define WORK_MAXCNT (sizeof(worker->i) / sizeof(worker->i[0]))
886 #define WORK_I_MASK (WORK_MAXCNT - 1)
888 static void thread_work_start(void);
889 static void thread_work_wait_sync(struct work_item *work, int force);
890 static void thread_sync_caches(void);
891 static int thread_get_i_done(void);
893 static int decode_block_work(void *context, int ch, int *SB)
895 const unsigned char *ram = spu.spuMemC;
896 int predict_nr, shift_factor, flags;
897 struct work_item *work = context;
898 int start = work->ch[ch].start;
899 int loop = work->ch[ch].loop;
901 predict_nr = ram[start];
902 shift_factor = predict_nr & 0xf;
905 decode_block_data(SB, ram + start + 2, predict_nr, shift_factor);
907 flags = ram[start + 1];
909 loop = start; // loop adress
913 if (flags & 1) // 1: stop/loop
916 work->ch[ch].start = start & 0x7ffff;
917 work->ch[ch].loop = loop;
922 static void queue_channel_work(int ns_to, unsigned int silentch)
924 struct work_item *work;
929 work = &worker->i[worker->i_ready & WORK_I_MASK];
931 work->ctrl = spu.spuCtrl;
932 work->decode_pos = spu.decode_pos;
933 work->channels_silent = silentch;
935 mask = work->channels_new = spu.dwNewChannel & 0xffffff;
936 for (ch = 0; mask != 0; ch++, mask >>= 1) {
941 mask = work->channels_on = spu.dwChannelsAudible & 0xffffff;
942 spu.decode_dirty_ch |= mask & 0x0a;
944 for (ch = 0; mask != 0; ch++, mask >>= 1)
946 if (!(mask & 1)) continue;
948 s_chan = &spu.s_chan[ch];
949 work->ch[ch].spos = s_chan->spos;
950 work->ch[ch].sbpos = s_chan->iSBPos;
951 work->ch[ch].sinc = s_chan->sinc;
952 work->ch[ch].adsr = s_chan->ADSRX;
953 work->ch[ch].vol_l = s_chan->iLeftVolume;
954 work->ch[ch].vol_r = s_chan->iRightVolume;
955 work->ch[ch].start = s_chan->pCurr - spu.spuMemC;
956 work->ch[ch].loop = s_chan->pLoop - spu.spuMemC;
957 work->ch[ch].bNoise = s_chan->bNoise;
958 work->ch[ch].bFMod = s_chan->bFMod;
959 work->ch[ch].bRVBActive = s_chan->bRVBActive;
960 work->ch[ch].bNewPitch = s_chan->bNewPitch;
961 if (s_chan->prevflags & 1)
962 work->ch[ch].start = work->ch[ch].loop;
964 d = do_samples_skip(ch, ns_to);
965 work->ch[ch].ns_to = d;
967 // note: d is not accurate on skip
968 d = SkipADSR(&s_chan->ADSRX, d);
970 spu.dwChannelsAudible &= ~(1 << ch);
971 s_chan->ADSRX.State = ADSR_RELEASE;
972 s_chan->ADSRX.EnvelopeVol = 0;
974 s_chan->bNewPitch = 0;
978 if (spu.rvb->StartAddr) {
979 if (spu_config.iUseReverb)
980 work->rvb_addr = spu.rvb->CurrAddr;
982 spu.rvb->CurrAddr += ns_to / 2;
983 while (spu.rvb->CurrAddr >= 0x40000)
984 spu.rvb->CurrAddr -= 0x40000 - spu.rvb->StartAddr;
991 static void do_channel_work(struct work_item *work)
994 int *SB, sinc, spos, sbpos;
1000 memset(RVB, 0, ns_to * sizeof(RVB[0]) * 2);
1002 mask = work->channels_new;
1003 for (ch = 0; mask != 0; ch++, mask >>= 1) {
1005 StartSoundSB(spu.SB + ch * SB_SIZE);
1008 mask = work->channels_on;
1009 for (ch = 0; mask != 0; ch++, mask >>= 1)
1011 if (!(mask & 1)) continue;
1013 d = work->ch[ch].ns_to;
1014 spos = work->ch[ch].spos;
1015 sbpos = work->ch[ch].sbpos;
1016 sinc = work->ch[ch].sinc;
1018 SB = spu.SB + ch * SB_SIZE;
1019 if (work->ch[ch].bNewPitch)
1020 SB[32] = 1; // reset interpolation
1022 if (work->ch[ch].bNoise)
1023 do_lsfr_samples(d, work->ctrl, &spu.dwNoiseCount, &spu.dwNoiseVal);
1024 else if (work->ch[ch].bFMod == 2
1025 || (work->ch[ch].bFMod == 0 && spu_config.iUseInterpolation == 0))
1026 do_samples_noint(decode_block_work, work, ch, d, SB, sinc, &spos, &sbpos);
1027 else if (work->ch[ch].bFMod == 0 && spu_config.iUseInterpolation == 1)
1028 do_samples_simple(decode_block_work, work, ch, d, SB, sinc, &spos, &sbpos);
1030 do_samples_default(decode_block_work, work, ch, d, SB, sinc, &spos, &sbpos);
1032 d = MixADSR(&work->ch[ch].adsr, d);
1034 work->ch[ch].adsr.EnvelopeVol = 0;
1035 memset(&ChanBuf[d], 0, (ns_to - d) * sizeof(ChanBuf[0]));
1038 if (ch == 1 || ch == 3)
1039 do_decode_bufs(spu.spuMem, ch/2, ns_to, work->decode_pos);
1041 if (work->ch[ch].bFMod == 2) // fmod freq channel
1042 memcpy(iFMod, &ChanBuf, ns_to * sizeof(iFMod[0]));
1043 if (work->ch[ch].bRVBActive && work->rvb_addr)
1044 mix_chan_rvb(work->SSumLR, ns_to,
1045 work->ch[ch].vol_l, work->ch[ch].vol_r, RVB);
1047 mix_chan(work->SSumLR, ns_to, work->ch[ch].vol_l, work->ch[ch].vol_r);
1051 REVERBDo(work->SSumLR, RVB, ns_to, work->rvb_addr);
1054 static void sync_worker_thread(int force)
1056 struct work_item *work;
1057 int done, used_space;
1059 // rvb offsets will change, thread may be using them
1060 force |= spu.rvb->dirty && spu.rvb->StartAddr;
1062 done = thread_get_i_done() - worker->i_reaped;
1063 used_space = worker->i_ready - worker->i_reaped;
1065 //printf("done: %d use: %d dsp: %u/%u\n", done, used_space,
1066 // worker->boot_cnt, worker->i_done);
1068 while ((force && used_space > 0) || used_space >= WORK_MAXCNT || done > 0) {
1069 work = &worker->i[worker->i_reaped & WORK_I_MASK];
1070 thread_work_wait_sync(work, force);
1072 do_samples_finish(work->SSumLR, work->ns_to,
1073 work->channels_silent, work->decode_pos);
1076 done = thread_get_i_done() - worker->i_reaped;
1077 used_space = worker->i_ready - worker->i_reaped;
1080 thread_sync_caches();
1085 static void queue_channel_work(int ns_to, int silentch) {}
1086 static void sync_worker_thread(int force) {}
1088 static const void * const worker = NULL;
1090 #endif // THREAD_ENABLED
1092 ////////////////////////////////////////////////////////////////////////
1093 // MAIN SPU FUNCTION
1094 // here is the main job handler...
1095 ////////////////////////////////////////////////////////////////////////
1097 void do_samples(unsigned int cycles_to, int do_direct)
1099 unsigned int silentch;
1103 cycle_diff = cycles_to - spu.cycles_played;
1104 if (cycle_diff < -2*1048576 || cycle_diff > 2*1048576)
1106 //xprintf("desync %u %d\n", cycles_to, cycle_diff);
1107 spu.cycles_played = cycles_to;
1111 silentch = ~(spu.dwChannelsAudible | spu.dwNewChannel) & 0xffffff;
1113 do_direct |= (silentch == 0xffffff);
1115 sync_worker_thread(do_direct);
1117 if (cycle_diff < 2 * 768)
1120 ns_to = (cycle_diff / 768 + 1) & ~1;
1121 if (ns_to > NSSIZE) {
1122 // should never happen
1123 //xprintf("ns_to oflow %d %d\n", ns_to, NSSIZE);
1127 //////////////////////////////////////////////////////
1128 // special irq handling in the decode buffers (0x0000-0x1000)
1130 // the decode buffers are located in spu memory in the following way:
1131 // 0x0000-0x03ff CD audio left
1132 // 0x0400-0x07ff CD audio right
1133 // 0x0800-0x0bff Voice 1
1134 // 0x0c00-0x0fff Voice 3
1135 // and decoded data is 16 bit for one sample
1137 // even if voices 1/3 are off or no cd audio is playing, the internal
1138 // play positions will move on and wrap after 0x400 bytes.
1139 // Therefore: we just need a pointer from spumem+0 to spumem+3ff, and
1140 // increase this pointer on each sample by 2 bytes. If this pointer
1141 // (or 0x400 offsets of this pointer) hits the spuirq address, we generate
1144 if (unlikely((spu.spuCtrl & CTRL_IRQ)
1145 && spu.pSpuIrq < spu.spuMemC+0x1000))
1147 int irq_pos = (spu.pSpuIrq - spu.spuMemC) / 2 & 0x1ff;
1148 int left = (irq_pos - spu.decode_pos) & 0x1ff;
1149 if (0 < left && left <= ns_to)
1151 //xprintf("decoder irq %x\n", spu.decode_pos);
1155 check_irq_io(spu.spuAddr);
1157 if (unlikely(spu.rvb->dirty))
1160 if (do_direct || worker == NULL || !spu_config.iUseThread) {
1162 do_samples_finish(spu.SSumLR, ns_to, silentch, spu.decode_pos);
1165 queue_channel_work(ns_to, silentch);
1166 //sync_worker_thread(1); // uncomment for debug
1169 // advance "stopped" channels that can cause irqs
1170 // (all chans are always playing on the real thing..)
1171 if (spu.spuCtrl & CTRL_IRQ)
1172 do_silent_chans(ns_to, silentch);
1174 spu.cycles_played += ns_to * 768;
1175 spu.decode_pos = (spu.decode_pos + ns_to) & 0x1ff;
1178 static void do_samples_finish(int *SSumLR, int ns_to,
1179 int silentch, int decode_pos)
1181 int vol_l = ((int)regAreaGet(H_SPUmvolL) << 17) >> 17;
1182 int vol_r = ((int)regAreaGet(H_SPUmvolR) << 17) >> 17;
1186 // must clear silent channel decode buffers
1187 if(unlikely(silentch & spu.decode_dirty_ch & (1<<1)))
1189 memset(&spu.spuMem[0x800/2], 0, 0x400);
1190 spu.decode_dirty_ch &= ~(1<<1);
1192 if(unlikely(silentch & spu.decode_dirty_ch & (1<<3)))
1194 memset(&spu.spuMem[0xc00/2], 0, 0x400);
1195 spu.decode_dirty_ch &= ~(1<<3);
1198 MixXA(SSumLR, ns_to, decode_pos);
1200 vol_l = vol_l * spu_config.iVolume >> 10;
1201 vol_r = vol_r * spu_config.iVolume >> 10;
1203 if (!(spu.spuCtrl & 0x4000) || !(vol_l | vol_r))
1206 memset(spu.pS, 0, ns_to * 2 * sizeof(spu.pS[0]));
1207 memset(SSumLR, 0, ns_to * 2 * sizeof(SSumLR[0]));
1208 spu.pS += ns_to * 2;
1211 for (ns = 0; ns < ns_to * 2; )
1213 d = SSumLR[ns]; SSumLR[ns] = 0;
1214 d = d * vol_l >> 14;
1219 d = SSumLR[ns]; SSumLR[ns] = 0;
1220 d = d * vol_r >> 14;
1227 void schedule_next_irq(void)
1229 unsigned int upd_samples;
1232 if (spu.scheduleCallback == NULL)
1235 upd_samples = 44100 / 50;
1237 for (ch = 0; ch < MAXCHAN; ch++)
1239 if (spu.dwChannelDead & (1 << ch))
1241 if ((unsigned long)(spu.pSpuIrq - spu.s_chan[ch].pCurr) > IRQ_NEAR_BLOCKS * 16
1242 && (unsigned long)(spu.pSpuIrq - spu.s_chan[ch].pLoop) > IRQ_NEAR_BLOCKS * 16)
1244 if (spu.s_chan[ch].sinc == 0)
1247 scan_for_irq(ch, &upd_samples);
1250 if (unlikely(spu.pSpuIrq < spu.spuMemC + 0x1000))
1252 int irq_pos = (spu.pSpuIrq - spu.spuMemC) / 2 & 0x1ff;
1253 int left = (irq_pos - spu.decode_pos) & 0x1ff;
1254 if (0 < left && left < upd_samples) {
1255 //xprintf("decode: %3d (%3d/%3d)\n", left, spu.decode_pos, irq_pos);
1260 if (upd_samples < 44100 / 50)
1261 spu.scheduleCallback(upd_samples * 768);
1264 // SPU ASYNC... even newer epsxe func
1265 // 1 time every 'cycle' cycles... harhar
1267 // rearmed: called dynamically now
1269 void CALLBACK SPUasync(unsigned int cycle, unsigned int flags)
1271 do_samples(cycle, spu_config.iUseFixedUpdates);
1273 if (spu.spuCtrl & CTRL_IRQ)
1274 schedule_next_irq();
1277 out_current->feed(spu.pSpuBuffer, (unsigned char *)spu.pS - spu.pSpuBuffer);
1278 spu.pS = (short *)spu.pSpuBuffer;
1280 if (spu_config.iTempo) {
1281 if (!out_current->busy())
1282 // cause more samples to be generated
1283 // (and break some games because of bad sync)
1284 spu.cycles_played -= 44100 / 60 / 2 * 768;
1289 // SPU UPDATE... new epsxe func
1290 // 1 time every 32 hsync lines
1291 // (312/32)x50 in pal
1292 // (262/32)x60 in ntsc
1294 // since epsxe 1.5.2 (linux) uses SPUupdate, not SPUasync, I will
1295 // leave that func in the linux port, until epsxe linux is using
1296 // the async function as well
1298 void CALLBACK SPUupdate(void)
1304 void CALLBACK SPUplayADPCMchannel(xa_decode_t *xap, unsigned int cycle, int is_start)
1307 if(!xap->freq) return; // no xa freq ? bye
1310 do_samples(cycle, 1); // catch up to prevent source underflows later
1312 FeedXA(xap); // call main XA feeder
1316 int CALLBACK SPUplayCDDAchannel(short *pcm, int nbytes, unsigned int cycle, int is_start)
1318 if (!pcm) return -1;
1319 if (nbytes<=0) return -1;
1322 do_samples(cycle, 1); // catch up to prevent source underflows later
1324 return FeedCDDA((unsigned char *)pcm, nbytes);
1327 // to be called after state load
1328 void ClearWorkingState(void)
1330 memset(iFMod, 0, sizeof(iFMod));
1331 spu.pS=(short *)spu.pSpuBuffer; // setup soundbuffer pointer
1334 // SETUPSTREAMS: init most of the spu buffers
1335 static void SetupStreams(void)
1337 spu.pSpuBuffer = (unsigned char *)malloc(32768); // alloc mixing buffer
1338 spu.SSumLR = calloc(NSSIZE * 2, sizeof(spu.SSumLR[0]));
1340 spu.XAStart = malloc(44100 * sizeof(uint32_t)); // alloc xa buffer
1341 spu.XAEnd = spu.XAStart + 44100;
1342 spu.XAPlay = spu.XAStart;
1343 spu.XAFeed = spu.XAStart;
1345 spu.CDDAStart = malloc(CDDA_BUFFER_SIZE); // alloc cdda buffer
1346 spu.CDDAEnd = spu.CDDAStart + 16384;
1347 spu.CDDAPlay = spu.CDDAStart;
1348 spu.CDDAFeed = spu.CDDAStart;
1350 ClearWorkingState();
1353 // REMOVESTREAMS: free most buffer
1354 static void RemoveStreams(void)
1356 free(spu.pSpuBuffer); // free mixing buffer
1357 spu.pSpuBuffer = NULL;
1360 free(spu.XAStart); // free XA buffer
1362 free(spu.CDDAStart); // free CDDA buffer
1363 spu.CDDAStart = NULL;
1366 #if defined(C64X_DSP)
1368 /* special code for TI C64x DSP */
1369 #include "spu_c64x.c"
1371 #elif defined(THREAD_ENABLED)
1373 #include <pthread.h>
1374 #include <semaphore.h>
1383 /* generic pthread implementation */
1385 static void thread_work_start(void)
1387 sem_post(&t.sem_avail);
1390 static void thread_work_wait_sync(struct work_item *work, int force)
1392 sem_wait(&t.sem_done);
1395 static int thread_get_i_done(void)
1397 return worker->i_done;
1400 static void thread_sync_caches(void)
1404 static void *spu_worker_thread(void *unused)
1406 struct work_item *work;
1409 sem_wait(&t.sem_avail);
1410 if (worker->exit_thread)
1413 work = &worker->i[worker->i_done & WORK_I_MASK];
1414 do_channel_work(work);
1417 sem_post(&t.sem_done);
1423 static void init_spu_thread(void)
1427 if (sysconf(_SC_NPROCESSORS_ONLN) <= 1)
1430 worker = calloc(1, sizeof(*worker));
1433 ret = sem_init(&t.sem_avail, 0, 0);
1435 goto fail_sem_avail;
1436 ret = sem_init(&t.sem_done, 0, 0);
1440 ret = pthread_create(&t.thread, NULL, spu_worker_thread, NULL);
1444 spu_config.iThreadAvail = 1;
1448 sem_destroy(&t.sem_done);
1450 sem_destroy(&t.sem_avail);
1454 spu_config.iThreadAvail = 0;
1457 static void exit_spu_thread(void)
1461 worker->exit_thread = 1;
1462 sem_post(&t.sem_avail);
1463 pthread_join(t.thread, NULL);
1464 sem_destroy(&t.sem_done);
1465 sem_destroy(&t.sem_avail);
1470 #else // if !THREAD_ENABLED
1472 static void init_spu_thread(void)
1476 static void exit_spu_thread(void)
1482 // SPUINIT: this func will be called first by the main emu
1483 long CALLBACK SPUinit(void)
1487 spu.spuMemC = calloc(1, 512 * 1024);
1490 spu.s_chan = calloc(MAXCHAN+1, sizeof(spu.s_chan[0])); // channel + 1 infos (1 is security for fmod handling)
1491 spu.rvb = calloc(1, sizeof(REVERBInfo));
1492 spu.SB = calloc(MAXCHAN, sizeof(spu.SB[0]) * SB_SIZE);
1496 spu.pSpuIrq = spu.spuMemC;
1498 SetupStreams(); // prepare streaming
1500 if (spu_config.iVolume == 0)
1501 spu_config.iVolume = 768; // 1024 is 1.0
1505 for (i = 0; i < MAXCHAN; i++) // loop sound channels
1507 spu.s_chan[i].ADSRX.SustainLevel = 0xf; // -> init sustain
1508 spu.s_chan[i].ADSRX.SustainIncrease = 1;
1509 spu.s_chan[i].pLoop = spu.spuMemC;
1510 spu.s_chan[i].pCurr = spu.spuMemC;
1511 spu.s_chan[i].bIgnoreLoop = 0;
1514 spu.bSpuInit=1; // flag: we are inited
1519 // SPUOPEN: called by main emu after init
1520 long CALLBACK SPUopen(void)
1522 if (spu.bSPUIsOpen) return 0; // security for some stupid main emus
1524 SetupSound(); // setup sound (before init!)
1528 return PSE_SPU_ERR_SUCCESS;
1531 // SPUCLOSE: called before shutdown
1532 long CALLBACK SPUclose(void)
1534 if (!spu.bSPUIsOpen) return 0; // some security
1536 spu.bSPUIsOpen = 0; // no more open
1538 out_current->finish(); // no more sound handling
1543 // SPUSHUTDOWN: called by main emu on final exit
1544 long CALLBACK SPUshutdown(void)
1559 RemoveStreams(); // no more streaming
1565 // SPUTEST: we don't test, we are always fine ;)
1566 long CALLBACK SPUtest(void)
1571 // SPUCONFIGURE: call config dialog
1572 long CALLBACK SPUconfigure(void)
1577 // StartCfgTool("CFG");
1582 // SPUABOUT: show about window
1583 void CALLBACK SPUabout(void)
1588 // StartCfgTool("ABOUT");
1593 // this functions will be called once,
1594 // passes a callback that should be called on SPU-IRQ/cdda volume change
1595 void CALLBACK SPUregisterCallback(void (CALLBACK *callback)(void))
1597 spu.irqCallback = callback;
1600 void CALLBACK SPUregisterCDDAVolume(void (CALLBACK *CDDAVcallback)(short, short))
1602 spu.cddavCallback = CDDAVcallback;
1605 void CALLBACK SPUregisterScheduleCb(void (CALLBACK *callback)(unsigned int))
1607 spu.scheduleCallback = callback;
1610 // COMMON PLUGIN INFO FUNCS
1612 char * CALLBACK PSEgetLibName(void)
1614 return _(libraryName);
1617 unsigned long CALLBACK PSEgetLibType(void)
1622 unsigned long CALLBACK PSEgetLibVersion(void)
1624 return (1 << 16) | (6 << 8);
1627 char * SPUgetLibInfos(void)
1629 return _(libraryInfo);
1634 void spu_get_debug_info(int *chans_out, int *run_chans, int *fmod_chans_out, int *noise_chans_out)
1636 int ch = 0, fmod_chans = 0, noise_chans = 0, irq_chans = 0;
1638 if (spu.s_chan == NULL)
1641 for(;ch<MAXCHAN;ch++)
1643 if (!(spu.dwChannelsAudible & (1<<ch)))
1645 if (spu.s_chan[ch].bFMod == 2)
1646 fmod_chans |= 1 << ch;
1647 if (spu.s_chan[ch].bNoise)
1648 noise_chans |= 1 << ch;
1649 if((spu.spuCtrl&CTRL_IRQ) && spu.s_chan[ch].pCurr <= spu.pSpuIrq && spu.s_chan[ch].pLoop <= spu.pSpuIrq)
1650 irq_chans |= 1 << ch;
1653 *chans_out = spu.dwChannelsAudible;
1654 *run_chans = ~spu.dwChannelsAudible & ~spu.dwChannelDead & irq_chans;
1655 *fmod_chans_out = fmod_chans;
1656 *noise_chans_out = noise_chans;
1659 // vim:shiftwidth=1:expandtab