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 // MAIN infos struct for each channel
80 static int iFMod[NSSIZE];
83 #define CDDA_BUFFER_SIZE (16384 * sizeof(uint32_t)) // must be power of 2
85 ////////////////////////////////////////////////////////////////////////
87 ////////////////////////////////////////////////////////////////////////
89 // dirty inline func includes
94 ////////////////////////////////////////////////////////////////////////
95 // helpers for simple interpolation
98 // easy interpolation on upsampling, no special filter, just "Pete's common sense" tm
100 // instead of having n equal sample values in a row like:
104 // we compare the current delta change with the next delta change.
106 // if curr_delta is positive,
108 // - and next delta is smaller (or changing direction):
112 // - and next delta significant (at least twice) bigger:
116 // - and next delta is nearly same:
121 // if curr_delta is negative,
123 // - and next delta is smaller (or changing direction):
127 // - and next delta significant (at least twice) bigger:
131 // - and next delta is nearly same:
136 static void InterpolateUp(int *SB, int sinc)
138 if(SB[32]==1) // flag == 1? calc step and set flag... and don't change the value in this pass
140 const int id1=SB[30]-SB[29]; // curr delta to next val
141 const int id2=SB[31]-SB[30]; // and next delta to next-next val :)
145 if(id1>0) // curr delta positive
148 {SB[28]=id1;SB[32]=2;}
151 SB[28]=(id1*sinc)>>16;
153 SB[28]=(id1*sinc)>>17;
155 else // curr delta negative
158 {SB[28]=id1;SB[32]=2;}
161 SB[28]=(id1*sinc)>>16;
163 SB[28]=(id1*sinc)>>17;
167 if(SB[32]==2) // flag 1: calc step and set flag... and don't change the value in this pass
171 SB[28]=(SB[28]*sinc)>>17;
173 // SB[29]=SB[30]-(SB[28]*((0x10000/sinc)-1));
177 else // no flags? add bigger val (if possible), calc smaller step, set flag1
182 // even easier interpolation on downsampling, also no special filter, again just "Pete's common sense" tm
185 static void InterpolateDown(int *SB, int sinc)
187 if(sinc>=0x20000L) // we would skip at least one val?
189 SB[29]+=(SB[30]-SB[29])/2; // add easy weight
190 if(sinc>=0x30000L) // we would skip even more vals?
191 SB[29]+=(SB[31]-SB[30])/2; // add additional next weight
195 ////////////////////////////////////////////////////////////////////////
196 // helpers for gauss interpolation
198 #define gval0 (((short*)(&SB[29]))[gpos&3])
199 #define gval(x) ((int)((short*)(&SB[29]))[(gpos+x)&3])
203 ////////////////////////////////////////////////////////////////////////
207 static void do_irq(void)
209 //if(!(spu.spuStat & STAT_IRQ))
211 spu.spuStat |= STAT_IRQ; // asserted status?
212 if(spu.irqCallback) spu.irqCallback();
216 static int check_irq(int ch, unsigned char *pos)
218 if((spu.spuCtrl & CTRL_IRQ) && pos == spu.pSpuIrq)
220 //printf("ch%d irq %04x\n", ch, pos - spu.spuMemC);
227 ////////////////////////////////////////////////////////////////////////
228 // START SOUND... called by main thread to setup a new sound on a channel
229 ////////////////////////////////////////////////////////////////////////
231 static void StartSoundSB(int *SB)
233 SB[26]=0; // init mixing vars
237 SB[29]=0; // init our interpolation helpers
242 static void StartSoundMain(int ch)
244 SPUCHAN *s_chan = &spu.s_chan[ch];
253 spu.dwNewChannel&=~(1<<ch); // clear new channel bit
254 spu.dwChannelOn|=1<<ch;
255 spu.dwChannelDead&=~(1<<ch);
258 static void StartSound(int ch)
261 StartSoundSB(spu.SB + ch * SB_SIZE);
264 ////////////////////////////////////////////////////////////////////////
265 // ALL KIND OF HELPERS
266 ////////////////////////////////////////////////////////////////////////
268 INLINE int FModChangeFrequency(int *SB, int pitch, int ns)
270 unsigned int NP=pitch;
273 NP=((32768L+iFMod[ns])*NP)>>15;
275 if(NP>0x3fff) NP=0x3fff;
278 sinc=NP<<4; // calc frequency
279 if(spu_config.iUseInterpolation==1) // freq change in simple interpolation mode
286 ////////////////////////////////////////////////////////////////////////
288 INLINE void StoreInterpolationVal(int *SB, int sinc, int fa, int fmod_freq)
290 if(fmod_freq) // fmod freq channel
296 if(spu_config.iUseInterpolation>=2) // gauss/cubic interpolation
304 if(spu_config.iUseInterpolation==1) // simple interpolation
307 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'
310 SB[32] = 1; // -> flag: calc new interolation
312 else SB[29]=fa; // no interpolation
316 ////////////////////////////////////////////////////////////////////////
318 INLINE int iGetInterpolationVal(int *SB, int sinc, int spos, int fmod_freq)
322 if(fmod_freq) return SB[29];
324 switch(spu_config.iUseInterpolation)
326 //--------------------------------------------------//
327 case 3: // cubic interpolation
333 fa = gval(3) - 3*gval(2) + 3*gval(1) - gval0;
334 fa *= (xd - (2<<15)) / 6;
336 fa += gval(2) - gval(1) - gval(1) + gval0;
337 fa *= (xd - (1<<15)) >> 1;
339 fa += gval(1) - gval0;
345 //--------------------------------------------------//
346 case 2: // gauss interpolation
349 vl = (spos >> 6) & ~3;
351 vr=(gauss[vl]*(int)gval0)&~2047;
352 vr+=(gauss[vl+1]*gval(1))&~2047;
353 vr+=(gauss[vl+2]*gval(2))&~2047;
354 vr+=(gauss[vl+3]*gval(3))&~2047;
357 //--------------------------------------------------//
358 case 1: // simple interpolation
360 if(sinc<0x10000L) // -> upsampling?
361 InterpolateUp(SB, sinc); // --> interpolate up
362 else InterpolateDown(SB, sinc); // --> else down
365 //--------------------------------------------------//
366 default: // no interpolation
370 //--------------------------------------------------//
376 static void decode_block_data(int *dest, const unsigned char *src, int predict_nr, int shift_factor)
378 static const int f[16][2] = {
386 int fa, s_1, s_2, d, s;
391 for (nSample = 0; nSample < 28; src++)
394 s = (int)(signed short)((d & 0x0f) << 12);
396 fa = s >> shift_factor;
397 fa += ((s_1 * f[predict_nr][0])>>6) + ((s_2 * f[predict_nr][1])>>6);
400 dest[nSample++] = fa;
402 s = (int)(signed short)((d & 0xf0) << 8);
403 fa = s >> shift_factor;
404 fa += ((s_1 * f[predict_nr][0])>>6) + ((s_2 * f[predict_nr][1])>>6);
407 dest[nSample++] = fa;
411 static int decode_block(void *unused, int ch, int *SB)
413 SPUCHAN *s_chan = &spu.s_chan[ch];
414 unsigned char *start;
415 int predict_nr, shift_factor, flags;
418 start = s_chan->pCurr; // set up the current pos
419 if (start == spu.spuMemC) // ?
422 if (s_chan->prevflags & 1) // 1: stop/loop
424 if (!(s_chan->prevflags & 2))
427 start = s_chan->pLoop;
430 check_irq(ch, start); // hack, see check_irq below..
432 predict_nr = start[0];
433 shift_factor = predict_nr & 0xf;
436 decode_block_data(SB, start + 2, predict_nr, shift_factor);
440 s_chan->pLoop = start; // loop adress
444 if (flags & 1) { // 1: stop/loop
445 start = s_chan->pLoop;
446 check_irq(ch, start); // hack.. :(
449 if (start - spu.spuMemC >= 0x80000)
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);
477 s_chan->pLoop = start;
482 start = s_chan->pLoop;
483 check_irq(ch, start);
486 s_chan->pCurr = start;
487 s_chan->prevflags = flags;
492 // if irq is going to trigger sooner than in upd_samples, set upd_samples
493 static void scan_for_irq(int ch, unsigned int *upd_samples)
495 SPUCHAN *s_chan = &spu.s_chan[ch];
496 int pos, sinc, sinc_inv, end;
497 unsigned char *block;
500 block = s_chan->pCurr;
503 end = pos + *upd_samples * sinc;
505 pos += (28 - s_chan->iSBPos) << 16;
508 if (block == spu.pSpuIrq)
512 if (flags & 1) { // 1: stop/loop
513 block = s_chan->pLoop;
514 if (block == spu.pSpuIrq) // hack.. (see decode_block)
522 sinc_inv = s_chan->sinc_inv;
524 sinc_inv = s_chan->sinc_inv = (0x80000000u / (uint32_t)sinc) << 1;
527 *upd_samples = (((uint64_t)pos * sinc_inv) >> 32) + 1;
528 //xprintf("ch%02d: irq sched: %3d %03d\n",
529 // ch, *upd_samples, *upd_samples * 60 * 263 / 44100);
533 #define make_do_samples(name, fmod_code, interp_start, interp1_code, interp2_code, interp_end) \
534 static noinline int do_samples_##name( \
535 int (*decode_f)(void *context, int ch, int *SB), void *ctx, \
536 int ch, int ns_to, int *SB, int sinc, int *spos, int *sbpos) \
542 for (ns = 0; ns < ns_to; ns++) \
547 while (*spos >= 0x10000) \
549 fa = SB[(*sbpos)++]; \
553 d = decode_f(ctx, ch, SB); \
570 #define fmod_recv_check \
571 if(spu.s_chan[ch].bFMod==1 && iFMod[ns]) \
572 sinc = FModChangeFrequency(SB, spu.s_chan[ch].iRawPitch, ns)
574 make_do_samples(default, fmod_recv_check, ,
575 StoreInterpolationVal(SB, sinc, fa, spu.s_chan[ch].bFMod==2),
576 ChanBuf[ns] = iGetInterpolationVal(SB, sinc, *spos, spu.s_chan[ch].bFMod==2), )
577 make_do_samples(noint, , fa = SB[29], , ChanBuf[ns] = fa, SB[29] = fa)
579 #define simple_interp_store \
586 #define simple_interp_get \
587 if(sinc<0x10000) /* -> upsampling? */ \
588 InterpolateUp(SB, sinc); /* --> interpolate up */ \
589 else InterpolateDown(SB, sinc); /* --> else down */ \
592 make_do_samples(simple, , ,
593 simple_interp_store, simple_interp_get, )
595 static int do_samples_skip(int ch, int ns_to)
597 SPUCHAN *s_chan = &spu.s_chan[ch];
598 int ret = ns_to, ns, d;
600 s_chan->spos += s_chan->iSBPos << 16;
602 for (ns = 0; ns < ns_to; ns++)
604 s_chan->spos += s_chan->sinc;
605 while (s_chan->spos >= 28*0x10000)
610 s_chan->spos -= 28*0x10000;
614 s_chan->iSBPos = s_chan->spos >> 16;
615 s_chan->spos &= 0xffff;
620 static void do_lsfr_samples(int ns_to, int ctrl,
621 unsigned int *dwNoiseCount, unsigned int *dwNoiseVal)
623 unsigned int counter = *dwNoiseCount;
624 unsigned int val = *dwNoiseVal;
625 unsigned int level, shift, bit;
628 // modified from DrHell/shalma, no fraction
629 level = (ctrl >> 10) & 0x0f;
630 level = 0x8000 >> level;
632 for (ns = 0; ns < ns_to; ns++)
635 if (counter >= level)
638 shift = (val >> 10) & 0x1f;
639 bit = (0x69696969 >> shift) & 1;
640 bit ^= (val >> 15) & 1;
641 val = (val << 1) | bit;
644 ChanBuf[ns] = (signed short)val;
647 *dwNoiseCount = counter;
651 static int do_samples_noise(int ch, int ns_to)
655 ret = do_samples_skip(ch, ns_to);
657 do_lsfr_samples(ns_to, spu.spuCtrl, &spu.dwNoiseCount, &spu.dwNoiseVal);
663 // asm code; lv and rv must be 0-3fff
664 extern void mix_chan(int *SSumLR, int count, int lv, int rv);
665 extern void mix_chan_rvb(int *SSumLR, int count, int lv, int rv, int *rvb);
667 static void mix_chan(int *SSumLR, int count, int lv, int rv)
669 const int *src = ChanBuf;
676 l = (sval * lv) >> 14;
677 r = (sval * rv) >> 14;
683 static void mix_chan_rvb(int *SSumLR, int count, int lv, int rv, int *rvb)
685 const int *src = ChanBuf;
694 l = (sval * lv) >> 14;
695 r = (sval * rv) >> 14;
704 // 0x0800-0x0bff Voice 1
705 // 0x0c00-0x0fff Voice 3
706 static noinline void do_decode_bufs(unsigned short *mem, int which,
707 int count, int decode_pos)
709 unsigned short *dst = &mem[0x800/2 + which*0x400/2];
710 const int *src = ChanBuf;
711 int cursor = decode_pos;
716 dst[cursor] = *src++;
720 // decode_pos is updated and irqs are checked later, after voice loop
723 static void do_silent_chans(int ns_to, int silentch)
729 mask = silentch & 0xffffff;
730 for (ch = 0; mask != 0; ch++, mask >>= 1)
732 if (!(mask & 1)) continue;
733 if (spu.dwChannelDead & (1<<ch)) continue;
735 s_chan = &spu.s_chan[ch];
736 if (s_chan->pCurr > spu.pSpuIrq && s_chan->pLoop > spu.pSpuIrq)
739 s_chan->spos += s_chan->iSBPos << 16;
742 s_chan->spos += s_chan->sinc * ns_to;
743 while (s_chan->spos >= 28 * 0x10000)
745 unsigned char *start = s_chan->pCurr;
748 if (start == s_chan->pCurr || start - spu.spuMemC < 0x1000)
750 // looping on self or stopped(?)
751 spu.dwChannelDead |= 1<<ch;
756 s_chan->spos -= 28 * 0x10000;
761 static void do_channels(int ns_to)
768 memset(spu.RVB, 0, ns_to * sizeof(spu.RVB[0]) * 2);
770 mask = spu.dwNewChannel & 0xffffff;
771 for (ch = 0; mask != 0; ch++, mask >>= 1) {
776 mask = spu.dwChannelOn & 0xffffff;
777 for (ch = 0; mask != 0; ch++, mask >>= 1) // loop em all...
779 if (!(mask & 1)) continue; // channel not playing? next
781 s_chan = &spu.s_chan[ch];
782 SB = spu.SB + ch * SB_SIZE;
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.dwChannelOn &= ~(1 << ch);
801 s_chan->ADSRX.EnvelopeVol = 0;
802 memset(&ChanBuf[d], 0, (ns_to - d) * sizeof(ChanBuf[0]));
805 if (ch == 1 || ch == 3)
807 do_decode_bufs(spu.spuMem, ch/2, ns_to, spu.decode_pos);
808 spu.decode_dirty_ch |= 1 << ch;
811 if (s_chan->bFMod == 2) // fmod freq channel
812 memcpy(iFMod, &ChanBuf, ns_to * sizeof(iFMod[0]));
813 if (s_chan->bRVBActive)
814 mix_chan_rvb(spu.SSumLR, ns_to, s_chan->iLeftVolume, s_chan->iRightVolume, spu.RVB);
816 mix_chan(spu.SSumLR, ns_to, s_chan->iLeftVolume, s_chan->iRightVolume);
820 static void do_samples_finish(int *SSumLR, int *RVB, int ns_to,
821 int silentch, int decode_pos);
823 // optional worker thread handling
825 #if defined(THREAD_ENABLED) || defined(WANT_THREAD_CODE)
827 // worker thread state
828 static struct spu_worker {
831 unsigned int exit_thread;
832 unsigned int i_ready;
833 unsigned int i_reaped;
834 unsigned int req_sent; // dsp
835 unsigned int last_boot_cnt;
837 // aligning for C64X_DSP
838 unsigned int _pad0[128/4];
843 unsigned int active; // dsp
844 unsigned int boot_cnt;
846 unsigned int _pad1[128/4];
852 unsigned int channels_new;
853 unsigned int channels_on;
854 unsigned int channels_silent;
863 // might want to add vol and fmod flags..
866 int SSumLR[NSSIZE * 2];
870 #define WORK_MAXCNT (sizeof(worker->i) / sizeof(worker->i[0]))
871 #define WORK_I_MASK (WORK_MAXCNT - 1)
873 static void thread_work_start(void);
874 static void thread_work_wait_sync(struct work_item *work, int force);
875 static int thread_get_i_done(void);
877 static int decode_block_work(void *context, int ch, int *SB)
879 const unsigned char *ram = spu.spuMemC;
880 int predict_nr, shift_factor, flags;
881 struct work_item *work = context;
882 int start = work->ch[ch].start;
883 int loop = work->ch[ch].loop;
885 predict_nr = ram[start];
886 shift_factor = predict_nr & 0xf;
889 decode_block_data(SB, ram + start + 2, predict_nr, shift_factor);
891 flags = ram[start + 1];
893 loop = start; // loop adress
897 if (flags & 1) // 1: stop/loop
900 work->ch[ch].start = start & 0x7ffff;
901 work->ch[ch].loop = loop;
906 static void queue_channel_work(int ns_to, unsigned int silentch)
908 struct work_item *work;
913 work = &worker->i[worker->i_ready & WORK_I_MASK];
915 work->ctrl = spu.spuCtrl;
916 work->decode_pos = spu.decode_pos;
917 work->channels_silent = silentch;
919 mask = work->channels_new = spu.dwNewChannel & 0xffffff;
920 for (ch = 0; mask != 0; ch++, mask >>= 1) {
925 mask = work->channels_on = spu.dwChannelOn & 0xffffff;
926 spu.decode_dirty_ch |= mask & 0x0a;
928 for (ch = 0; mask != 0; ch++, mask >>= 1)
930 if (!(mask & 1)) continue;
932 s_chan = &spu.s_chan[ch];
933 work->ch[ch].spos = s_chan->spos;
934 work->ch[ch].sbpos = s_chan->iSBPos;
935 work->ch[ch].sinc = s_chan->sinc;
936 work->ch[ch].adsr = s_chan->ADSRX;
937 work->ch[ch].start = s_chan->pCurr - spu.spuMemC;
938 work->ch[ch].loop = s_chan->pLoop - spu.spuMemC;
939 if (s_chan->prevflags & 1)
940 work->ch[ch].start = work->ch[ch].loop;
942 d = do_samples_skip(ch, ns_to);
943 work->ch[ch].ns_to = d;
945 // note: d is not accurate on skip
946 d = SkipADSR(&s_chan->ADSRX, d);
948 spu.dwChannelOn &= ~(1 << ch);
949 s_chan->ADSRX.EnvelopeVol = 0;
957 static void do_channel_work(struct work_item *work)
960 unsigned int decode_dirty_ch = 0;
961 int *SB, sinc, spos, sbpos;
966 memset(work->RVB, 0, ns_to * sizeof(work->RVB[0]) * 2);
968 mask = work->channels_new;
969 for (ch = 0; mask != 0; ch++, mask >>= 1) {
971 StartSoundSB(spu.SB + ch * SB_SIZE);
974 mask = work->channels_on;
975 for (ch = 0; mask != 0; ch++, mask >>= 1)
977 if (!(mask & 1)) continue;
979 d = work->ch[ch].ns_to;
980 spos = work->ch[ch].spos;
981 sbpos = work->ch[ch].sbpos;
982 sinc = work->ch[ch].sinc;
984 s_chan = &spu.s_chan[ch];
985 SB = spu.SB + ch * SB_SIZE;
988 do_lsfr_samples(d, work->ctrl, &spu.dwNoiseCount, &spu.dwNoiseVal);
989 else if (s_chan->bFMod == 2
990 || (s_chan->bFMod == 0 && spu_config.iUseInterpolation == 0))
991 do_samples_noint(decode_block_work, work, ch, d, SB, sinc, &spos, &sbpos);
992 else if (s_chan->bFMod == 0 && spu_config.iUseInterpolation == 1)
993 do_samples_simple(decode_block_work, work, ch, d, SB, sinc, &spos, &sbpos);
995 do_samples_default(decode_block_work, work, ch, d, SB, sinc, &spos, &sbpos);
997 d = MixADSR(&work->ch[ch].adsr, d);
999 work->ch[ch].adsr.EnvelopeVol = 0;
1000 memset(&ChanBuf[d], 0, (ns_to - d) * sizeof(ChanBuf[0]));
1003 if (ch == 1 || ch == 3)
1005 do_decode_bufs(spu.spuMem, ch/2, ns_to, work->decode_pos);
1006 decode_dirty_ch |= 1 << ch;
1009 if (s_chan->bFMod == 2) // fmod freq channel
1010 memcpy(iFMod, &ChanBuf, ns_to * sizeof(iFMod[0]));
1011 if (s_chan->bRVBActive)
1012 mix_chan_rvb(work->SSumLR, ns_to,
1013 s_chan->iLeftVolume, s_chan->iRightVolume, work->RVB);
1015 mix_chan(work->SSumLR, ns_to, s_chan->iLeftVolume, s_chan->iRightVolume);
1019 static void sync_worker_thread(int force)
1021 struct work_item *work;
1022 int done, used_space;
1024 done = thread_get_i_done() - worker->i_reaped;
1025 used_space = worker->i_ready - worker->i_reaped;
1026 //printf("done: %d use: %d dsp: %u/%u\n", done, used_space,
1027 // worker->boot_cnt, worker->i_done);
1029 while ((force && used_space > 0) || used_space >= WORK_MAXCNT || done > 0) {
1030 work = &worker->i[worker->i_reaped & WORK_I_MASK];
1031 thread_work_wait_sync(work, force);
1033 do_samples_finish(work->SSumLR, work->RVB, work->ns_to,
1034 work->channels_silent, work->decode_pos);
1037 done = thread_get_i_done() - worker->i_reaped;
1038 used_space = worker->i_ready - worker->i_reaped;
1044 static void queue_channel_work(int ns_to, int silentch) {}
1045 static void sync_worker_thread(int force) {}
1047 static const void * const worker = NULL;
1049 #endif // THREAD_ENABLED
1051 ////////////////////////////////////////////////////////////////////////
1052 // MAIN SPU FUNCTION
1053 // here is the main job handler...
1054 ////////////////////////////////////////////////////////////////////////
1056 void do_samples(unsigned int cycles_to, int do_direct)
1058 unsigned int silentch;
1062 cycle_diff = cycles_to - spu.cycles_played;
1063 if (cycle_diff < -2*1048576 || cycle_diff > 2*1048576)
1065 //xprintf("desync %u %d\n", cycles_to, cycle_diff);
1066 spu.cycles_played = cycles_to;
1070 silentch = ~(spu.dwChannelOn | spu.dwNewChannel) & 0xffffff;
1072 do_direct |= (silentch == 0xffffff);
1074 sync_worker_thread(do_direct);
1076 if (cycle_diff < 2 * 768)
1079 ns_to = (cycle_diff / 768 + 1) & ~1;
1080 if (ns_to > NSSIZE) {
1081 // should never happen
1082 //xprintf("ns_to oflow %d %d\n", ns_to, NSSIZE);
1086 //////////////////////////////////////////////////////
1087 // special irq handling in the decode buffers (0x0000-0x1000)
1089 // the decode buffers are located in spu memory in the following way:
1090 // 0x0000-0x03ff CD audio left
1091 // 0x0400-0x07ff CD audio right
1092 // 0x0800-0x0bff Voice 1
1093 // 0x0c00-0x0fff Voice 3
1094 // and decoded data is 16 bit for one sample
1096 // even if voices 1/3 are off or no cd audio is playing, the internal
1097 // play positions will move on and wrap after 0x400 bytes.
1098 // Therefore: we just need a pointer from spumem+0 to spumem+3ff, and
1099 // increase this pointer on each sample by 2 bytes. If this pointer
1100 // (or 0x400 offsets of this pointer) hits the spuirq address, we generate
1103 if (unlikely((spu.spuCtrl & CTRL_IRQ)
1104 && spu.pSpuIrq < spu.spuMemC+0x1000))
1106 int irq_pos = (spu.pSpuIrq - spu.spuMemC) / 2 & 0x1ff;
1107 int left = (irq_pos - spu.decode_pos) & 0x1ff;
1108 if (0 < left && left <= ns_to)
1110 //xprintf("decoder irq %x\n", spu.decode_pos);
1115 if (do_direct || worker == NULL || !spu_config.iUseThread) {
1117 do_samples_finish(spu.SSumLR, spu.RVB, ns_to, silentch, spu.decode_pos);
1120 queue_channel_work(ns_to, silentch);
1123 // advance "stopped" channels that can cause irqs
1124 // (all chans are always playing on the real thing..)
1125 if (spu.spuCtrl & CTRL_IRQ)
1126 do_silent_chans(ns_to, silentch);
1128 spu.cycles_played += ns_to * 768;
1129 spu.decode_pos = (spu.decode_pos + ns_to) & 0x1ff;
1132 static void do_samples_finish(int *SSumLR, int *RVB, int ns_to,
1133 int silentch, int decode_pos)
1135 int volmult = spu_config.iVolume;
1139 // must clear silent channel decode buffers
1140 if(unlikely(silentch & spu.decode_dirty_ch & (1<<1)))
1142 memset(&spu.spuMem[0x800/2], 0, 0x400);
1143 spu.decode_dirty_ch &= ~(1<<1);
1145 if(unlikely(silentch & spu.decode_dirty_ch & (1<<3)))
1147 memset(&spu.spuMem[0xc00/2], 0, 0x400);
1148 spu.decode_dirty_ch &= ~(1<<3);
1151 //---------------------------------------------------//
1152 // mix XA infos (if any)
1154 MixXA(SSumLR, ns_to, decode_pos);
1156 ///////////////////////////////////////////////////////
1157 // mix all channels (including reverb) into one buffer
1159 if(spu_config.iUseReverb)
1160 REVERBDo(SSumLR, RVB, ns_to);
1162 if((spu.spuCtrl&0x4000)==0) // muted? (rare, don't optimize for this)
1164 memset(spu.pS, 0, ns_to * 2 * sizeof(spu.pS[0]));
1165 spu.pS += ns_to * 2;
1168 for (ns = 0; ns < ns_to * 2; )
1170 d = SSumLR[ns]; SSumLR[ns] = 0;
1171 d = d * volmult >> 10;
1176 d = SSumLR[ns]; SSumLR[ns] = 0;
1177 d = d * volmult >> 10;
1184 void schedule_next_irq(void)
1186 unsigned int upd_samples;
1189 if (spu.scheduleCallback == NULL)
1192 upd_samples = 44100 / 50;
1194 for (ch = 0; ch < MAXCHAN; ch++)
1196 if (spu.dwChannelDead & (1 << ch))
1198 if ((unsigned long)(spu.pSpuIrq - spu.s_chan[ch].pCurr) > IRQ_NEAR_BLOCKS * 16
1199 && (unsigned long)(spu.pSpuIrq - spu.s_chan[ch].pLoop) > IRQ_NEAR_BLOCKS * 16)
1202 scan_for_irq(ch, &upd_samples);
1205 if (unlikely(spu.pSpuIrq < spu.spuMemC + 0x1000))
1207 int irq_pos = (spu.pSpuIrq - spu.spuMemC) / 2 & 0x1ff;
1208 int left = (irq_pos - spu.decode_pos) & 0x1ff;
1209 if (0 < left && left < upd_samples) {
1210 //xprintf("decode: %3d (%3d/%3d)\n", left, spu.decode_pos, irq_pos);
1215 if (upd_samples < 44100 / 50)
1216 spu.scheduleCallback(upd_samples * 768);
1219 // SPU ASYNC... even newer epsxe func
1220 // 1 time every 'cycle' cycles... harhar
1222 // rearmed: called dynamically now
1224 void CALLBACK SPUasync(unsigned int cycle, unsigned int flags)
1226 do_samples(cycle, 0);
1228 if (spu.spuCtrl & CTRL_IRQ)
1229 schedule_next_irq();
1232 out_current->feed(spu.pSpuBuffer, (unsigned char *)spu.pS - spu.pSpuBuffer);
1233 spu.pS = (short *)spu.pSpuBuffer;
1235 if (spu_config.iTempo) {
1236 if (!out_current->busy())
1237 // cause more samples to be generated
1238 // (and break some games because of bad sync)
1239 spu.cycles_played -= 44100 / 60 / 2 * 768;
1244 // SPU UPDATE... new epsxe func
1245 // 1 time every 32 hsync lines
1246 // (312/32)x50 in pal
1247 // (262/32)x60 in ntsc
1249 // since epsxe 1.5.2 (linux) uses SPUupdate, not SPUasync, I will
1250 // leave that func in the linux port, until epsxe linux is using
1251 // the async function as well
1253 void CALLBACK SPUupdate(void)
1259 void CALLBACK SPUplayADPCMchannel(xa_decode_t *xap)
1262 if(!xap->freq) return; // no xa freq ? bye
1264 FeedXA(xap); // call main XA feeder
1268 int CALLBACK SPUplayCDDAchannel(short *pcm, int nbytes)
1270 if (!pcm) return -1;
1271 if (nbytes<=0) return -1;
1273 return FeedCDDA((unsigned char *)pcm, nbytes);
1276 // to be called after state load
1277 void ClearWorkingState(void)
1279 memset(iFMod, 0, sizeof(iFMod));
1280 spu.pS=(short *)spu.pSpuBuffer; // setup soundbuffer pointer
1283 // SETUPSTREAMS: init most of the spu buffers
1284 void SetupStreams(void)
1288 spu.pSpuBuffer = (unsigned char *)malloc(32768); // alloc mixing buffer
1289 spu.RVB = calloc(NSSIZE * 2, sizeof(spu.RVB[0]));
1290 spu.SSumLR = calloc(NSSIZE * 2, sizeof(spu.SSumLR[0]));
1292 spu.XAStart = // alloc xa buffer
1293 (uint32_t *)malloc(44100 * sizeof(uint32_t));
1294 spu.XAEnd = spu.XAStart + 44100;
1295 spu.XAPlay = spu.XAStart;
1296 spu.XAFeed = spu.XAStart;
1298 spu.CDDAStart = // alloc cdda buffer
1299 (uint32_t *)malloc(CDDA_BUFFER_SIZE);
1300 spu.CDDAEnd = spu.CDDAStart + 16384;
1301 spu.CDDAPlay = spu.CDDAStart;
1302 spu.CDDAFeed = spu.CDDAStart;
1304 for(i=0;i<MAXCHAN;i++) // loop sound channels
1306 spu.s_chan[i].ADSRX.SustainLevel = 0xf; // -> init sustain
1307 spu.s_chan[i].ADSRX.SustainIncrease = 1;
1308 spu.s_chan[i].pLoop=spu.spuMemC;
1309 spu.s_chan[i].pCurr=spu.spuMemC;
1312 ClearWorkingState();
1314 spu.bSpuInit=1; // flag: we are inited
1317 // REMOVESTREAMS: free most buffer
1318 void RemoveStreams(void)
1320 free(spu.pSpuBuffer); // free mixing buffer
1321 spu.pSpuBuffer = NULL;
1322 free(spu.RVB); // free reverb buffer
1326 free(spu.XAStart); // free XA buffer
1328 free(spu.CDDAStart); // free CDDA buffer
1329 spu.CDDAStart = NULL;
1332 #if defined(C64X_DSP)
1334 /* special code for TI C64x DSP */
1335 #include "spu_c64x.c"
1337 #elif defined(THREAD_ENABLED)
1339 #include <pthread.h>
1340 #include <semaphore.h>
1349 /* generic pthread implementation */
1351 static void thread_work_start(void)
1353 sem_post(&t.sem_avail);
1356 static void thread_work_wait_sync(struct work_item *work, int force)
1358 sem_wait(&t.sem_done);
1361 static int thread_get_i_done(void)
1363 return worker->i_done;
1366 static void *spu_worker_thread(void *unused)
1368 struct work_item *work;
1371 sem_wait(&t.sem_avail);
1372 if (worker->exit_thread)
1375 work = &worker->i[worker->i_done & WORK_I_MASK];
1376 do_channel_work(work);
1379 sem_post(&t.sem_done);
1385 static void init_spu_thread(void)
1389 if (sysconf(_SC_NPROCESSORS_ONLN) <= 1)
1392 worker = calloc(1, sizeof(*worker));
1395 ret = sem_init(&t.sem_avail, 0, 0);
1397 goto fail_sem_avail;
1398 ret = sem_init(&t.sem_done, 0, 0);
1402 ret = pthread_create(&t.thread, NULL, spu_worker_thread, NULL);
1406 spu_config.iThreadAvail = 1;
1410 sem_destroy(&t.sem_done);
1412 sem_destroy(&t.sem_avail);
1416 spu_config.iThreadAvail = 0;
1419 static void exit_spu_thread(void)
1423 worker->exit_thread = 1;
1424 sem_post(&t.sem_avail);
1425 pthread_join(t.thread, NULL);
1426 sem_destroy(&t.sem_done);
1427 sem_destroy(&t.sem_avail);
1432 #else // if !THREAD_ENABLED
1434 static void init_spu_thread(void)
1438 static void exit_spu_thread(void)
1444 // SPUINIT: this func will be called first by the main emu
1445 long CALLBACK SPUinit(void)
1447 spu.spuMemC = calloc(1, 512 * 1024);
1448 memset((void *)&rvb, 0, sizeof(REVERBInfo));
1451 spu.s_chan = calloc(MAXCHAN+1, sizeof(spu.s_chan[0])); // channel + 1 infos (1 is security for fmod handling)
1452 spu.SB = calloc(MAXCHAN, sizeof(spu.SB[0]) * SB_SIZE);
1456 spu.pSpuIrq = spu.spuMemC;
1458 SetupStreams(); // prepare streaming
1460 if (spu_config.iVolume == 0)
1461 spu_config.iVolume = 768; // 1024 is 1.0
1468 // SPUOPEN: called by main emu after init
1469 long CALLBACK SPUopen(void)
1471 if (spu.bSPUIsOpen) return 0; // security for some stupid main emus
1473 SetupSound(); // setup sound (before init!)
1477 return PSE_SPU_ERR_SUCCESS;
1480 // SPUCLOSE: called before shutdown
1481 long CALLBACK SPUclose(void)
1483 if (!spu.bSPUIsOpen) return 0; // some security
1485 spu.bSPUIsOpen = 0; // no more open
1487 out_current->finish(); // no more sound handling
1492 // SPUSHUTDOWN: called by main emu on final exit
1493 long CALLBACK SPUshutdown(void)
1506 RemoveStreams(); // no more streaming
1512 // SPUTEST: we don't test, we are always fine ;)
1513 long CALLBACK SPUtest(void)
1518 // SPUCONFIGURE: call config dialog
1519 long CALLBACK SPUconfigure(void)
1524 // StartCfgTool("CFG");
1529 // SPUABOUT: show about window
1530 void CALLBACK SPUabout(void)
1535 // StartCfgTool("ABOUT");
1540 // this functions will be called once,
1541 // passes a callback that should be called on SPU-IRQ/cdda volume change
1542 void CALLBACK SPUregisterCallback(void (CALLBACK *callback)(void))
1544 spu.irqCallback = callback;
1547 void CALLBACK SPUregisterCDDAVolume(void (CALLBACK *CDDAVcallback)(unsigned short,unsigned short))
1549 spu.cddavCallback = CDDAVcallback;
1552 void CALLBACK SPUregisterScheduleCb(void (CALLBACK *callback)(unsigned int))
1554 spu.scheduleCallback = callback;
1557 // COMMON PLUGIN INFO FUNCS
1559 char * CALLBACK PSEgetLibName(void)
1561 return _(libraryName);
1564 unsigned long CALLBACK PSEgetLibType(void)
1569 unsigned long CALLBACK PSEgetLibVersion(void)
1571 return (1 << 16) | (6 << 8);
1574 char * SPUgetLibInfos(void)
1576 return _(libraryInfo);
1581 void spu_get_debug_info(int *chans_out, int *run_chans, int *fmod_chans_out, int *noise_chans_out)
1583 int ch = 0, fmod_chans = 0, noise_chans = 0, irq_chans = 0;
1585 if (spu.s_chan == NULL)
1588 for(;ch<MAXCHAN;ch++)
1590 if (!(spu.dwChannelOn & (1<<ch)))
1592 if (spu.s_chan[ch].bFMod == 2)
1593 fmod_chans |= 1 << ch;
1594 if (spu.s_chan[ch].bNoise)
1595 noise_chans |= 1 << ch;
1596 if((spu.spuCtrl&CTRL_IRQ) && spu.s_chan[ch].pCurr <= spu.pSpuIrq && spu.s_chan[ch].pLoop <= spu.pSpuIrq)
1597 irq_chans |= 1 << ch;
1600 *chans_out = spu.dwChannelOn;
1601 *run_chans = ~spu.dwChannelOn & ~spu.dwChannelDead & irq_chans;
1602 *fmod_chans_out = fmod_chans;
1603 *noise_chans_out = noise_chans;
1606 // vim:shiftwidth=1:expandtab