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 #if defined(THREAD_ENABLED) || defined(WANT_THREAD_CODE)
82 // worker thread state
83 static struct spu_worker {
84 unsigned int pending:1;
85 unsigned int exit_thread:1;
86 unsigned int stale_cache:1;
100 // might want to add vol and fmod flags..
107 unsigned int chan_end;
108 unsigned int decode_dirty;
113 static const void * const worker = NULL;
116 // certain globals (were local before, but with the new timeproc I need em global)
118 static int iFMod[NSSIZE];
122 #define CDDA_BUFFER_SIZE (16384 * sizeof(uint32_t)) // must be power of 2
124 ////////////////////////////////////////////////////////////////////////
126 ////////////////////////////////////////////////////////////////////////
128 // dirty inline func includes
133 ////////////////////////////////////////////////////////////////////////
134 // helpers for simple interpolation
137 // easy interpolation on upsampling, no special filter, just "Pete's common sense" tm
139 // instead of having n equal sample values in a row like:
143 // we compare the current delta change with the next delta change.
145 // if curr_delta is positive,
147 // - and next delta is smaller (or changing direction):
151 // - and next delta significant (at least twice) bigger:
155 // - and next delta is nearly same:
160 // if curr_delta is negative,
162 // - and next delta is smaller (or changing direction):
166 // - and next delta significant (at least twice) bigger:
170 // - and next delta is nearly same:
175 static void InterpolateUp(int *SB, int sinc)
177 if(SB[32]==1) // flag == 1? calc step and set flag... and don't change the value in this pass
179 const int id1=SB[30]-SB[29]; // curr delta to next val
180 const int id2=SB[31]-SB[30]; // and next delta to next-next val :)
184 if(id1>0) // curr delta positive
187 {SB[28]=id1;SB[32]=2;}
190 SB[28]=(id1*sinc)>>16;
192 SB[28]=(id1*sinc)>>17;
194 else // curr delta negative
197 {SB[28]=id1;SB[32]=2;}
200 SB[28]=(id1*sinc)>>16;
202 SB[28]=(id1*sinc)>>17;
206 if(SB[32]==2) // flag 1: calc step and set flag... and don't change the value in this pass
210 SB[28]=(SB[28]*sinc)>>17;
212 // SB[29]=SB[30]-(SB[28]*((0x10000/sinc)-1));
216 else // no flags? add bigger val (if possible), calc smaller step, set flag1
221 // even easier interpolation on downsampling, also no special filter, again just "Pete's common sense" tm
224 static void InterpolateDown(int *SB, int sinc)
226 if(sinc>=0x20000L) // we would skip at least one val?
228 SB[29]+=(SB[30]-SB[29])/2; // add easy weight
229 if(sinc>=0x30000L) // we would skip even more vals?
230 SB[29]+=(SB[31]-SB[30])/2; // add additional next weight
234 ////////////////////////////////////////////////////////////////////////
235 // helpers for gauss interpolation
237 #define gval0 (((short*)(&SB[29]))[gpos&3])
238 #define gval(x) ((int)((short*)(&SB[29]))[(gpos+x)&3])
242 ////////////////////////////////////////////////////////////////////////
246 static void do_irq(void)
248 //if(!(spu.spuStat & STAT_IRQ))
250 spu.spuStat |= STAT_IRQ; // asserted status?
251 if(spu.irqCallback) spu.irqCallback();
255 static int check_irq(int ch, unsigned char *pos)
257 if((spu.spuCtrl & CTRL_IRQ) && pos == spu.pSpuIrq)
259 //printf("ch%d irq %04x\n", ch, pos - spu.spuMemC);
266 ////////////////////////////////////////////////////////////////////////
267 // START SOUND... called by main thread to setup a new sound on a channel
268 ////////////////////////////////////////////////////////////////////////
270 INLINE void StartSound(int ch)
272 SPUCHAN *s_chan = &spu.s_chan[ch];
273 int *SB = spu.SB + ch * SB_SIZE;
281 SB[26]=0; // init mixing vars
285 SB[29]=0; // init our interpolation helpers
290 spu.dwNewChannel&=~(1<<ch); // clear new channel bit
291 spu.dwChannelOn|=1<<ch;
292 spu.dwChannelDead&=~(1<<ch);
295 ////////////////////////////////////////////////////////////////////////
296 // ALL KIND OF HELPERS
297 ////////////////////////////////////////////////////////////////////////
299 INLINE int FModChangeFrequency(int *SB, int pitch, int ns)
301 unsigned int NP=pitch;
304 NP=((32768L+iFMod[ns])*NP)>>15;
306 if(NP>0x3fff) NP=0x3fff;
309 sinc=NP<<4; // calc frequency
310 if(spu_config.iUseInterpolation==1) // freq change in simple interpolation mode
317 ////////////////////////////////////////////////////////////////////////
319 INLINE void StoreInterpolationVal(int *SB, int sinc, int fa, int fmod_freq)
321 if(fmod_freq) // fmod freq channel
327 if(spu_config.iUseInterpolation>=2) // gauss/cubic interpolation
335 if(spu_config.iUseInterpolation==1) // simple interpolation
338 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'
341 SB[32] = 1; // -> flag: calc new interolation
343 else SB[29]=fa; // no interpolation
347 ////////////////////////////////////////////////////////////////////////
349 INLINE int iGetInterpolationVal(int *SB, int sinc, int spos, int fmod_freq)
353 if(fmod_freq) return SB[29];
355 switch(spu_config.iUseInterpolation)
357 //--------------------------------------------------//
358 case 3: // cubic interpolation
364 fa = gval(3) - 3*gval(2) + 3*gval(1) - gval0;
365 fa *= (xd - (2<<15)) / 6;
367 fa += gval(2) - gval(1) - gval(1) + gval0;
368 fa *= (xd - (1<<15)) >> 1;
370 fa += gval(1) - gval0;
376 //--------------------------------------------------//
377 case 2: // gauss interpolation
380 vl = (spos >> 6) & ~3;
382 vr=(gauss[vl]*(int)gval0)&~2047;
383 vr+=(gauss[vl+1]*gval(1))&~2047;
384 vr+=(gauss[vl+2]*gval(2))&~2047;
385 vr+=(gauss[vl+3]*gval(3))&~2047;
388 //--------------------------------------------------//
389 case 1: // simple interpolation
391 if(sinc<0x10000L) // -> upsampling?
392 InterpolateUp(SB, sinc); // --> interpolate up
393 else InterpolateDown(SB, sinc); // --> else down
396 //--------------------------------------------------//
397 default: // no interpolation
401 //--------------------------------------------------//
407 static void decode_block_data(int *dest, const unsigned char *src, int predict_nr, int shift_factor)
409 static const int f[16][2] = {
417 int fa, s_1, s_2, d, s;
422 for (nSample = 0; nSample < 28; src++)
425 s = (int)(signed short)((d & 0x0f) << 12);
427 fa = s >> shift_factor;
428 fa += ((s_1 * f[predict_nr][0])>>6) + ((s_2 * f[predict_nr][1])>>6);
431 dest[nSample++] = fa;
433 s = (int)(signed short)((d & 0xf0) << 8);
434 fa = s >> shift_factor;
435 fa += ((s_1 * f[predict_nr][0])>>6) + ((s_2 * f[predict_nr][1])>>6);
438 dest[nSample++] = fa;
442 static int decode_block(int ch, int *SB)
444 SPUCHAN *s_chan = &spu.s_chan[ch];
445 unsigned char *start;
446 int predict_nr, shift_factor, flags;
449 start = s_chan->pCurr; // set up the current pos
450 if (start == spu.spuMemC) // ?
453 if (s_chan->prevflags & 1) // 1: stop/loop
455 if (!(s_chan->prevflags & 2))
458 start = s_chan->pLoop;
461 check_irq(ch, start); // hack, see check_irq below..
463 predict_nr = start[0];
464 shift_factor = predict_nr & 0xf;
467 decode_block_data(SB, start + 2, predict_nr, shift_factor);
471 s_chan->pLoop = start; // loop adress
475 if (flags & 1) { // 1: stop/loop
476 start = s_chan->pLoop;
477 check_irq(ch, start); // hack.. :(
480 if (start - spu.spuMemC >= 0x80000)
483 s_chan->pCurr = start; // store values for next cycle
484 s_chan->prevflags = flags;
489 // do block, but ignore sample data
490 static int skip_block(int ch)
492 SPUCHAN *s_chan = &spu.s_chan[ch];
493 unsigned char *start = s_chan->pCurr;
497 if (s_chan->prevflags & 1) {
498 if (!(s_chan->prevflags & 2))
501 start = s_chan->pLoop;
504 check_irq(ch, start);
508 s_chan->pLoop = start;
513 start = s_chan->pLoop;
514 check_irq(ch, start);
517 s_chan->pCurr = start;
518 s_chan->prevflags = flags;
523 #if defined(THREAD_ENABLED) || defined(WANT_THREAD_CODE)
525 static int decode_block_work(int ch, int *SB)
527 const unsigned char *ram = spu.spuMemC;
528 int predict_nr, shift_factor, flags;
529 int start = worker->ch[ch].start;
530 int loop = worker->ch[ch].loop;
532 predict_nr = ram[start];
533 shift_factor = predict_nr & 0xf;
536 decode_block_data(SB, ram + start + 2, predict_nr, shift_factor);
538 flags = ram[start + 1];
540 loop = start; // loop adress
544 if (flags & 1) // 1: stop/loop
547 worker->ch[ch].start = start & 0x7ffff;
548 worker->ch[ch].loop = loop;
555 // if irq is going to trigger sooner than in upd_samples, set upd_samples
556 static void scan_for_irq(int ch, unsigned int *upd_samples)
558 SPUCHAN *s_chan = &spu.s_chan[ch];
559 int pos, sinc, sinc_inv, end;
560 unsigned char *block;
563 block = s_chan->pCurr;
566 end = pos + *upd_samples * sinc;
568 pos += (28 - s_chan->iSBPos) << 16;
571 if (block == spu.pSpuIrq)
575 if (flags & 1) { // 1: stop/loop
576 block = s_chan->pLoop;
577 if (block == spu.pSpuIrq) // hack.. (see decode_block)
585 sinc_inv = s_chan->sinc_inv;
587 sinc_inv = s_chan->sinc_inv = (0x80000000u / (uint32_t)sinc) << 1;
590 *upd_samples = (((uint64_t)pos * sinc_inv) >> 32) + 1;
591 //xprintf("ch%02d: irq sched: %3d %03d\n",
592 // ch, *upd_samples, *upd_samples * 60 * 263 / 44100);
596 #define make_do_samples(name, fmod_code, interp_start, interp1_code, interp2_code, interp_end) \
597 static noinline int do_samples_##name(int (*decode_f)(int ch, int *SB), int ch, \
598 int ns_to, int *SB, int sinc, int *spos, int *sbpos) \
604 for (ns = 0; ns < ns_to; ns++) \
609 while (*spos >= 0x10000) \
611 fa = SB[(*sbpos)++]; \
615 d = decode_f(ch, SB); \
632 #define fmod_recv_check \
633 if(spu.s_chan[ch].bFMod==1 && iFMod[ns]) \
634 sinc = FModChangeFrequency(SB, spu.s_chan[ch].iRawPitch, ns)
636 make_do_samples(default, fmod_recv_check, ,
637 StoreInterpolationVal(SB, sinc, fa, spu.s_chan[ch].bFMod==2),
638 ChanBuf[ns] = iGetInterpolationVal(SB, sinc, *spos, spu.s_chan[ch].bFMod==2), )
639 make_do_samples(noint, , fa = SB[29], , ChanBuf[ns] = fa, SB[29] = fa)
641 #define simple_interp_store \
648 #define simple_interp_get \
649 if(sinc<0x10000) /* -> upsampling? */ \
650 InterpolateUp(SB, sinc); /* --> interpolate up */ \
651 else InterpolateDown(SB, sinc); /* --> else down */ \
654 make_do_samples(simple, , ,
655 simple_interp_store, simple_interp_get, )
657 static int do_samples_skip(int ch, int ns_to)
659 SPUCHAN *s_chan = &spu.s_chan[ch];
660 int ret = ns_to, ns, d;
662 s_chan->spos += s_chan->iSBPos << 16;
664 for (ns = 0; ns < ns_to; ns++)
666 s_chan->spos += s_chan->sinc;
667 while (s_chan->spos >= 28*0x10000)
672 s_chan->spos -= 28*0x10000;
676 s_chan->iSBPos = s_chan->spos >> 16;
677 s_chan->spos &= 0xffff;
682 static void do_lsfr_samples(int ns_to, int ctrl,
683 unsigned int *dwNoiseCount, unsigned int *dwNoiseVal)
685 unsigned int counter = *dwNoiseCount;
686 unsigned int val = *dwNoiseVal;
687 unsigned int level, shift, bit;
690 // modified from DrHell/shalma, no fraction
691 level = (ctrl >> 10) & 0x0f;
692 level = 0x8000 >> level;
694 for (ns = 0; ns < ns_to; ns++)
697 if (counter >= level)
700 shift = (val >> 10) & 0x1f;
701 bit = (0x69696969 >> shift) & 1;
702 bit ^= (val >> 15) & 1;
703 val = (val << 1) | bit;
706 ChanBuf[ns] = (signed short)val;
709 *dwNoiseCount = counter;
713 static int do_samples_noise(int ch, int ns_to)
717 ret = do_samples_skip(ch, ns_to);
719 do_lsfr_samples(ns_to, spu.spuCtrl, &spu.dwNoiseCount, &spu.dwNoiseVal);
725 // asm code; lv and rv must be 0-3fff
726 extern void mix_chan(int start, int count, int lv, int rv);
727 extern void mix_chan_rvb(int start, int count, int lv, int rv, int *rvb);
729 static void mix_chan(int start, int count, int lv, int rv)
731 int *dst = SSumLR + start * 2;
732 const int *src = ChanBuf + start;
739 l = (sval * lv) >> 14;
740 r = (sval * rv) >> 14;
746 static void mix_chan_rvb(int start, int count, int lv, int rv, int *rvb)
748 int *dst = SSumLR + start * 2;
749 int *drvb = rvb + start * 2;
750 const int *src = ChanBuf + start;
757 l = (sval * lv) >> 14;
758 r = (sval * rv) >> 14;
767 // 0x0800-0x0bff Voice 1
768 // 0x0c00-0x0fff Voice 3
769 static noinline void do_decode_bufs(unsigned short *mem, int which,
770 int count, int decode_pos)
772 unsigned short *dst = &mem[0x800/2 + which*0x400/2];
773 const int *src = ChanBuf;
774 int cursor = decode_pos;
779 dst[cursor] = *src++;
783 // decode_pos is updated and irqs are checked later, after voice loop
786 static void do_silent_chans(int ns_to, int silentch)
792 mask = silentch & 0xffffff;
793 for (ch = 0; mask != 0; ch++, mask >>= 1)
795 if (!(mask & 1)) continue;
796 if (spu.dwChannelDead & (1<<ch)) continue;
798 s_chan = &spu.s_chan[ch];
799 if (s_chan->pCurr > spu.pSpuIrq && s_chan->pLoop > spu.pSpuIrq)
802 s_chan->spos += s_chan->iSBPos << 16;
805 s_chan->spos += s_chan->sinc * ns_to;
806 while (s_chan->spos >= 28 * 0x10000)
808 unsigned char *start = s_chan->pCurr;
811 if (start == s_chan->pCurr || start - spu.spuMemC < 0x1000)
813 // looping on self or stopped(?)
814 spu.dwChannelDead |= 1<<ch;
819 s_chan->spos -= 28 * 0x10000;
824 static void do_channels(int ns_to)
833 mask = spu.dwChannelOn & 0xffffff;
834 for (ch = 0; mask != 0; ch++, mask >>= 1) // loop em all...
836 if (!(mask & 1)) continue; // channel not playing? next
838 s_chan = &spu.s_chan[ch];
839 SB = spu.SB + ch * SB_SIZE;
843 d = do_samples_noise(ch, ns_to);
844 else if (s_chan->bFMod == 2
845 || (s_chan->bFMod == 0 && spu_config.iUseInterpolation == 0))
846 d = do_samples_noint(decode_block, ch, ns_to,
847 SB, sinc, &s_chan->spos, &s_chan->iSBPos);
848 else if (s_chan->bFMod == 0 && spu_config.iUseInterpolation == 1)
849 d = do_samples_simple(decode_block, ch, ns_to,
850 SB, sinc, &s_chan->spos, &s_chan->iSBPos);
852 d = do_samples_default(decode_block, ch, ns_to,
853 SB, sinc, &s_chan->spos, &s_chan->iSBPos);
855 d = MixADSR(&s_chan->ADSRX, d);
857 spu.dwChannelOn &= ~(1 << ch);
858 s_chan->ADSRX.EnvelopeVol = 0;
859 memset(&ChanBuf[d], 0, (ns_to - d) * sizeof(ChanBuf[0]));
862 if (ch == 1 || ch == 3)
864 do_decode_bufs(spu.spuMem, ch/2, ns_to, spu.decode_pos);
865 spu.decode_dirty_ch |= 1 << ch;
868 if (s_chan->bFMod == 2) // fmod freq channel
869 memcpy(iFMod, &ChanBuf, ns_to * sizeof(iFMod[0]));
870 if (s_chan->bRVBActive)
871 mix_chan_rvb(0, ns_to, s_chan->iLeftVolume, s_chan->iRightVolume, spu.sRVBStart);
873 mix_chan(0, ns_to, s_chan->iLeftVolume, s_chan->iRightVolume);
877 static void do_samples_finish(int ns_to, int silentch, int decode_pos);
879 // optional worker thread handling
881 #if defined(THREAD_ENABLED) || defined(WANT_THREAD_CODE)
883 static void thread_work_start(void);
884 static void thread_work_wait_sync(void);
885 static void thread_sync_caches(void);
887 static void queue_channel_work(int ns_to, int silentch)
889 const SPUCHAN *s_chan;
893 worker->ns_to = ns_to;
894 worker->ctrl = spu.spuCtrl;
895 worker->decode_pos = spu.decode_pos;
896 worker->silentch = silentch;
898 mask = worker->chmask = spu.dwChannelOn & 0xffffff;
899 for (ch = 0; mask != 0; ch++, mask >>= 1)
901 if (!(mask & 1)) continue;
903 s_chan = &spu.s_chan[ch];
904 worker->ch[ch].spos = s_chan->spos;
905 worker->ch[ch].sbpos = s_chan->iSBPos;
906 worker->ch[ch].sinc = s_chan->sinc;
907 worker->ch[ch].adsr = s_chan->ADSRX;
908 worker->ch[ch].start = s_chan->pCurr - spu.spuMemC;
909 worker->ch[ch].loop = s_chan->pLoop - spu.spuMemC;
910 if (s_chan->prevflags & 1)
911 worker->ch[ch].start = worker->ch[ch].loop;
913 worker->ch[ch].ns_to = do_samples_skip(ch, ns_to);
920 static void do_channel_work(void)
922 unsigned int mask, endmask = 0;
923 unsigned int decode_dirty_ch = 0;
924 int *SB, sinc, spos, sbpos;
928 ns_to = worker->ns_to;
929 memset(spu.sRVBStart, 0, ns_to * sizeof(spu.sRVBStart[0]) * 2);
931 mask = worker->chmask;
932 for (ch = 0; mask != 0; ch++, mask >>= 1)
934 if (!(mask & 1)) continue;
936 d = worker->ch[ch].ns_to;
937 spos = worker->ch[ch].spos;
938 sbpos = worker->ch[ch].sbpos;
939 sinc = worker->ch[ch].sinc;
941 s_chan = &spu.s_chan[ch];
942 SB = spu.SB + ch * SB_SIZE;
945 do_lsfr_samples(d, worker->ctrl, &spu.dwNoiseCount, &spu.dwNoiseVal);
946 else if (s_chan->bFMod == 2
947 || (s_chan->bFMod == 0 && spu_config.iUseInterpolation == 0))
948 do_samples_noint(decode_block_work, ch, d, SB, sinc, &spos, &sbpos);
949 else if (s_chan->bFMod == 0 && spu_config.iUseInterpolation == 1)
950 do_samples_simple(decode_block_work, ch, d, SB, sinc, &spos, &sbpos);
952 do_samples_default(decode_block_work, ch, d, SB, sinc, &spos, &sbpos);
954 d = MixADSR(&worker->ch[ch].adsr, d);
957 worker->ch[ch].adsr.EnvelopeVol = 0;
958 memset(&ChanBuf[d], 0, (ns_to - d) * sizeof(ChanBuf[0]));
960 worker->r.ch[ch].adsrState = worker->ch[ch].adsr.State;
961 worker->r.ch[ch].adsrEnvelopeVol = worker->ch[ch].adsr.EnvelopeVol;
963 if (ch == 1 || ch == 3)
965 do_decode_bufs(spu.spuMem, ch/2, ns_to, worker->decode_pos);
966 decode_dirty_ch |= 1 << ch;
969 if (s_chan->bFMod == 2) // fmod freq channel
970 memcpy(iFMod, &ChanBuf, ns_to * sizeof(iFMod[0]));
971 if (s_chan->bRVBActive)
972 mix_chan_rvb(0, ns_to, s_chan->iLeftVolume, s_chan->iRightVolume, spu.sRVBStart);
974 mix_chan(0, ns_to, s_chan->iLeftVolume, s_chan->iRightVolume);
977 worker->r.chan_end = endmask;
978 worker->r.decode_dirty = decode_dirty_ch;
981 static void sync_worker_thread(int do_direct)
987 thread_sync_caches();
988 if (!worker->pending)
991 thread_work_wait_sync();
994 mask = worker->chmask;
995 for (ch = 0; mask != 0; ch++, mask >>= 1) {
996 if (!(mask & 1)) continue;
998 // be sure there was no keyoff while thread was working
999 if (spu.s_chan[ch].ADSRX.State != ADSR_RELEASE)
1000 spu.s_chan[ch].ADSRX.State = worker->r.ch[ch].adsrState;
1001 spu.s_chan[ch].ADSRX.EnvelopeVol = worker->r.ch[ch].adsrEnvelopeVol;
1004 spu.dwChannelOn &= ~worker->r.chan_end;
1005 spu.decode_dirty_ch |= worker->r.decode_dirty;
1007 do_samples_finish(worker->ns_to, worker->silentch,
1008 worker->decode_pos);
1013 static void queue_channel_work(int ns_to, int silentch) {}
1014 static void sync_worker_thread(int do_direct) {}
1016 #endif // THREAD_ENABLED
1018 ////////////////////////////////////////////////////////////////////////
1019 // MAIN SPU FUNCTION
1020 // here is the main job handler...
1021 ////////////////////////////////////////////////////////////////////////
1023 void do_samples(unsigned int cycles_to, int do_direct)
1030 cycle_diff = cycles_to - spu.cycles_played;
1031 if (cycle_diff < -2*1048576 || cycle_diff > 2*1048576)
1033 //xprintf("desync %u %d\n", cycles_to, cycle_diff);
1034 spu.cycles_played = cycles_to;
1038 do_direct |= (cycle_diff < 64 * 768);
1040 sync_worker_thread(do_direct);
1042 if (cycle_diff < 2 * 768)
1045 ns_to = (cycle_diff / 768 + 1) & ~1;
1046 if (ns_to > NSSIZE) {
1047 // should never happen
1048 //xprintf("ns_to oflow %d %d\n", ns_to, NSSIZE);
1052 //////////////////////////////////////////////////////
1053 // special irq handling in the decode buffers (0x0000-0x1000)
1055 // the decode buffers are located in spu memory in the following way:
1056 // 0x0000-0x03ff CD audio left
1057 // 0x0400-0x07ff CD audio right
1058 // 0x0800-0x0bff Voice 1
1059 // 0x0c00-0x0fff Voice 3
1060 // and decoded data is 16 bit for one sample
1062 // even if voices 1/3 are off or no cd audio is playing, the internal
1063 // play positions will move on and wrap after 0x400 bytes.
1064 // Therefore: we just need a pointer from spumem+0 to spumem+3ff, and
1065 // increase this pointer on each sample by 2 bytes. If this pointer
1066 // (or 0x400 offsets of this pointer) hits the spuirq address, we generate
1069 if (unlikely((spu.spuCtrl & CTRL_IRQ)
1070 && spu.pSpuIrq < spu.spuMemC+0x1000))
1072 int irq_pos = (spu.pSpuIrq - spu.spuMemC) / 2 & 0x1ff;
1073 int left = (irq_pos - spu.decode_pos) & 0x1ff;
1074 if (0 < left && left <= ns_to)
1076 //xprintf("decoder irq %x\n", spu.decode_pos);
1081 mask = spu.dwNewChannel & 0xffffff;
1082 for (ch = 0; mask != 0; ch++, mask >>= 1) {
1087 silentch = ~spu.dwChannelOn & 0xffffff;
1089 if (spu.dwChannelOn == 0) {
1091 do_samples_finish(ns_to, silentch, spu.decode_pos);
1094 if (do_direct || worker == NULL || !spu_config.iUseThread) {
1096 do_samples_finish(ns_to, silentch, spu.decode_pos);
1099 queue_channel_work(ns_to, silentch);
1103 // advance "stopped" channels that can cause irqs
1104 // (all chans are always playing on the real thing..)
1105 if (spu.spuCtrl & CTRL_IRQ)
1106 do_silent_chans(ns_to, silentch);
1108 spu.cycles_played += ns_to * 768;
1109 spu.decode_pos = (spu.decode_pos + ns_to) & 0x1ff;
1112 static void do_samples_finish(int ns_to, int silentch, int decode_pos)
1114 int volmult = spu_config.iVolume;
1118 if(unlikely(silentch & spu.decode_dirty_ch & (1<<1))) // must clear silent channel decode buffers
1120 memset(&spu.spuMem[0x800/2], 0, 0x400);
1121 spu.decode_dirty_ch &= ~(1<<1);
1123 if(unlikely(silentch & spu.decode_dirty_ch & (1<<3)))
1125 memset(&spu.spuMem[0xc00/2], 0, 0x400);
1126 spu.decode_dirty_ch &= ~(1<<3);
1129 //---------------------------------------------------//
1130 // mix XA infos (if any)
1132 MixXA(ns_to, decode_pos);
1134 ///////////////////////////////////////////////////////
1135 // mix all channels (including reverb) into one buffer
1137 if(spu_config.iUseReverb)
1140 if((spu.spuCtrl&0x4000)==0) // muted? (rare, don't optimize for this)
1142 memset(spu.pS, 0, ns_to * 2 * sizeof(spu.pS[0]));
1143 spu.pS += ns_to * 2;
1146 for (ns = 0; ns < ns_to * 2; )
1148 d = SSumLR[ns]; SSumLR[ns] = 0;
1149 d = d * volmult >> 10;
1154 d = SSumLR[ns]; SSumLR[ns] = 0;
1155 d = d * volmult >> 10;
1162 void schedule_next_irq(void)
1164 unsigned int upd_samples;
1167 if (spu.scheduleCallback == NULL)
1170 upd_samples = 44100 / 50;
1172 for (ch = 0; ch < MAXCHAN; ch++)
1174 if (spu.dwChannelDead & (1 << ch))
1176 if ((unsigned long)(spu.pSpuIrq - spu.s_chan[ch].pCurr) > IRQ_NEAR_BLOCKS * 16
1177 && (unsigned long)(spu.pSpuIrq - spu.s_chan[ch].pLoop) > IRQ_NEAR_BLOCKS * 16)
1180 scan_for_irq(ch, &upd_samples);
1183 if (unlikely(spu.pSpuIrq < spu.spuMemC + 0x1000))
1185 int irq_pos = (spu.pSpuIrq - spu.spuMemC) / 2 & 0x1ff;
1186 int left = (irq_pos - spu.decode_pos) & 0x1ff;
1187 if (0 < left && left < upd_samples) {
1188 //xprintf("decode: %3d (%3d/%3d)\n", left, spu.decode_pos, irq_pos);
1193 if (upd_samples < 44100 / 50)
1194 spu.scheduleCallback(upd_samples * 768);
1197 // SPU ASYNC... even newer epsxe func
1198 // 1 time every 'cycle' cycles... harhar
1200 // rearmed: called dynamically now
1202 void CALLBACK SPUasync(unsigned int cycle, unsigned int flags)
1204 do_samples(cycle, 0);
1206 if (spu.spuCtrl & CTRL_IRQ)
1207 schedule_next_irq();
1210 out_current->feed(spu.pSpuBuffer, (unsigned char *)spu.pS - spu.pSpuBuffer);
1211 spu.pS = (short *)spu.pSpuBuffer;
1213 if (spu_config.iTempo) {
1214 if (!out_current->busy())
1215 // cause more samples to be generated
1216 // (and break some games because of bad sync)
1217 spu.cycles_played -= 44100 / 60 / 2 * 768;
1222 // SPU UPDATE... new epsxe func
1223 // 1 time every 32 hsync lines
1224 // (312/32)x50 in pal
1225 // (262/32)x60 in ntsc
1227 // since epsxe 1.5.2 (linux) uses SPUupdate, not SPUasync, I will
1228 // leave that func in the linux port, until epsxe linux is using
1229 // the async function as well
1231 void CALLBACK SPUupdate(void)
1237 void CALLBACK SPUplayADPCMchannel(xa_decode_t *xap)
1240 if(!xap->freq) return; // no xa freq ? bye
1242 FeedXA(xap); // call main XA feeder
1246 int CALLBACK SPUplayCDDAchannel(short *pcm, int nbytes)
1248 if (!pcm) return -1;
1249 if (nbytes<=0) return -1;
1251 return FeedCDDA((unsigned char *)pcm, nbytes);
1254 // to be called after state load
1255 void ClearWorkingState(void)
1257 memset(SSumLR, 0, NSSIZE * 2 * 4); // init some mixing buffers
1258 memset(iFMod, 0, sizeof(iFMod));
1259 spu.pS=(short *)spu.pSpuBuffer; // setup soundbuffer pointer
1262 // SETUPSTREAMS: init most of the spu buffers
1263 void SetupStreams(void)
1267 spu.pSpuBuffer = (unsigned char *)malloc(32768); // alloc mixing buffer
1268 spu.sRVBStart = calloc(NSSIZE * 2, sizeof(spu.sRVBStart[0]));
1269 SSumLR = calloc(NSSIZE * 2, sizeof(SSumLR[0]));
1271 spu.XAStart = // alloc xa buffer
1272 (uint32_t *)malloc(44100 * sizeof(uint32_t));
1273 spu.XAEnd = spu.XAStart + 44100;
1274 spu.XAPlay = spu.XAStart;
1275 spu.XAFeed = spu.XAStart;
1277 spu.CDDAStart = // alloc cdda buffer
1278 (uint32_t *)malloc(CDDA_BUFFER_SIZE);
1279 spu.CDDAEnd = spu.CDDAStart + 16384;
1280 spu.CDDAPlay = spu.CDDAStart;
1281 spu.CDDAFeed = spu.CDDAStart;
1283 for(i=0;i<MAXCHAN;i++) // loop sound channels
1285 spu.s_chan[i].ADSRX.SustainLevel = 0xf; // -> init sustain
1286 spu.s_chan[i].ADSRX.SustainIncrease = 1;
1287 spu.s_chan[i].pLoop=spu.spuMemC;
1288 spu.s_chan[i].pCurr=spu.spuMemC;
1291 ClearWorkingState();
1293 spu.bSpuInit=1; // flag: we are inited
1296 // REMOVESTREAMS: free most buffer
1297 void RemoveStreams(void)
1299 free(spu.pSpuBuffer); // free mixing buffer
1300 spu.pSpuBuffer = NULL;
1301 free(spu.sRVBStart); // free reverb buffer
1302 spu.sRVBStart = NULL;
1305 free(spu.XAStart); // free XA buffer
1307 free(spu.CDDAStart); // free CDDA buffer
1308 spu.CDDAStart = NULL;
1311 #if defined(C64X_DSP)
1313 /* special code for TI C64x DSP */
1314 #include "spu_c64x.c"
1316 #elif defined(THREAD_ENABLED)
1318 #include <pthread.h>
1319 #include <semaphore.h>
1328 /* generic pthread implementation */
1330 static void thread_work_start(void)
1332 sem_post(&t.sem_avail);
1335 static void thread_work_wait_sync(void)
1337 sem_wait(&t.sem_done);
1340 static void thread_sync_caches(void)
1344 static void *spu_worker_thread(void *unused)
1347 sem_wait(&t.sem_avail);
1348 if (worker->exit_thread)
1353 sem_post(&t.sem_done);
1359 static void init_spu_thread(void)
1363 if (sysconf(_SC_NPROCESSORS_ONLN) <= 1)
1366 worker = calloc(1, sizeof(*worker));
1369 ret = sem_init(&t.sem_avail, 0, 0);
1371 goto fail_sem_avail;
1372 ret = sem_init(&t.sem_done, 0, 0);
1376 ret = pthread_create(&t.thread, NULL, spu_worker_thread, NULL);
1383 sem_destroy(&t.sem_done);
1385 sem_destroy(&t.sem_avail);
1391 static void exit_spu_thread(void)
1395 worker->exit_thread = 1;
1396 sem_post(&t.sem_avail);
1397 pthread_join(t.thread, NULL);
1398 sem_destroy(&t.sem_done);
1399 sem_destroy(&t.sem_avail);
1404 #else // if !THREAD_ENABLED
1406 static void init_spu_thread(void)
1410 static void exit_spu_thread(void)
1416 // SPUINIT: this func will be called first by the main emu
1417 long CALLBACK SPUinit(void)
1419 spu.spuMemC = calloc(1, 512 * 1024);
1420 memset((void *)&rvb, 0, sizeof(REVERBInfo));
1423 spu.s_chan = calloc(MAXCHAN+1, sizeof(spu.s_chan[0])); // channel + 1 infos (1 is security for fmod handling)
1424 spu.SB = calloc(MAXCHAN, sizeof(spu.SB[0]) * SB_SIZE);
1428 spu.pSpuIrq = spu.spuMemC;
1430 SetupStreams(); // prepare streaming
1432 if (spu_config.iVolume == 0)
1433 spu_config.iVolume = 768; // 1024 is 1.0
1440 // SPUOPEN: called by main emu after init
1441 long CALLBACK SPUopen(void)
1443 if (spu.bSPUIsOpen) return 0; // security for some stupid main emus
1445 SetupSound(); // setup sound (before init!)
1449 return PSE_SPU_ERR_SUCCESS;
1452 // SPUCLOSE: called before shutdown
1453 long CALLBACK SPUclose(void)
1455 if (!spu.bSPUIsOpen) return 0; // some security
1457 spu.bSPUIsOpen = 0; // no more open
1459 out_current->finish(); // no more sound handling
1464 // SPUSHUTDOWN: called by main emu on final exit
1465 long CALLBACK SPUshutdown(void)
1478 RemoveStreams(); // no more streaming
1484 // SPUTEST: we don't test, we are always fine ;)
1485 long CALLBACK SPUtest(void)
1490 // SPUCONFIGURE: call config dialog
1491 long CALLBACK SPUconfigure(void)
1496 // StartCfgTool("CFG");
1501 // SPUABOUT: show about window
1502 void CALLBACK SPUabout(void)
1507 // StartCfgTool("ABOUT");
1512 // this functions will be called once,
1513 // passes a callback that should be called on SPU-IRQ/cdda volume change
1514 void CALLBACK SPUregisterCallback(void (CALLBACK *callback)(void))
1516 spu.irqCallback = callback;
1519 void CALLBACK SPUregisterCDDAVolume(void (CALLBACK *CDDAVcallback)(unsigned short,unsigned short))
1521 spu.cddavCallback = CDDAVcallback;
1524 void CALLBACK SPUregisterScheduleCb(void (CALLBACK *callback)(unsigned int))
1526 spu.scheduleCallback = callback;
1529 // COMMON PLUGIN INFO FUNCS
1531 char * CALLBACK PSEgetLibName(void)
1533 return _(libraryName);
1536 unsigned long CALLBACK PSEgetLibType(void)
1541 unsigned long CALLBACK PSEgetLibVersion(void)
1543 return (1 << 16) | (6 << 8);
1546 char * SPUgetLibInfos(void)
1548 return _(libraryInfo);
1553 void spu_get_debug_info(int *chans_out, int *run_chans, int *fmod_chans_out, int *noise_chans_out)
1555 int ch = 0, fmod_chans = 0, noise_chans = 0, irq_chans = 0;
1557 if (spu.s_chan == NULL)
1560 for(;ch<MAXCHAN;ch++)
1562 if (!(spu.dwChannelOn & (1<<ch)))
1564 if (spu.s_chan[ch].bFMod == 2)
1565 fmod_chans |= 1 << ch;
1566 if (spu.s_chan[ch].bNoise)
1567 noise_chans |= 1 << ch;
1568 if((spu.spuCtrl&CTRL_IRQ) && spu.s_chan[ch].pCurr <= spu.pSpuIrq && spu.s_chan[ch].pLoop <= spu.pSpuIrq)
1569 irq_chans |= 1 << ch;
1572 *chans_out = spu.dwChannelOn;
1573 *run_chans = ~spu.dwChannelOn & ~spu.dwChannelDead & irq_chans;
1574 *fmod_chans_out = fmod_chans;
1575 *noise_chans_out = noise_chans;
1578 // vim:shiftwidth=1:expandtab