1 /***************************************************************************
4 begin : Wed May 15 2002
5 copyright : (C) 2002 by Pete Bernert
6 email : BlackDove@addcom.de
8 Portions (C) GraÅžvydas "notaz" Ignotas, 2010-2012,2014,2015
10 ***************************************************************************/
11 /***************************************************************************
13 * This program is free software; you can redistribute it and/or modify *
14 * it under the terms of the GNU General Public License as published by *
15 * the Free Software Foundation; either version 2 of the License, or *
16 * (at your option) any later version. See also the license.txt file for *
17 * additional informations. *
19 ***************************************************************************/
21 #if !defined(_WIN32) && !defined(NO_OS)
22 #include <sys/time.h> // gettimeofday in xa.c
23 #define THREAD_ENABLED 1
29 #include "externals.h"
30 #include "registers.h"
32 #include "spu_config.h"
35 #include "arm_features.h"
39 #define ssat32_to_16(v) \
40 asm("ssat %0,#16,%1" : "=r" (v) : "r" (v))
42 #define ssat32_to_16(v) do { \
43 if (v < -32768) v = -32768; \
44 else if (v > 32767) v = 32767; \
48 #define PSXCLK 33868800 /* 33.8688 MHz */
50 // intended to be ~1 frame
51 #define IRQ_NEAR_BLOCKS 32
54 #if defined (USEMACOSX)
55 static char * libraryName = N_("Mac OS X Sound");
56 #elif defined (USEALSA)
57 static char * libraryName = N_("ALSA Sound");
58 #elif defined (USEOSS)
59 static char * libraryName = N_("OSS Sound");
60 #elif defined (USESDL)
61 static char * libraryName = N_("SDL Sound");
62 #elif defined (USEPULSEAUDIO)
63 static char * libraryName = N_("PulseAudio Sound");
65 static char * libraryName = N_("NULL Sound");
68 static char * libraryInfo = N_("P.E.Op.S. Sound Driver V1.7\nCoded by Pete Bernert and the P.E.Op.S. team\n");
76 static int iFMod[NSSIZE];
77 static int RVB[NSSIZE * 2];
80 #define CDDA_BUFFER_SIZE (16384 * sizeof(uint32_t)) // must be power of 2
82 ////////////////////////////////////////////////////////////////////////
84 ////////////////////////////////////////////////////////////////////////
86 // dirty inline func includes
91 ////////////////////////////////////////////////////////////////////////
92 // helpers for simple interpolation
95 // easy interpolation on upsampling, no special filter, just "Pete's common sense" tm
97 // instead of having n equal sample values in a row like:
101 // we compare the current delta change with the next delta change.
103 // if curr_delta is positive,
105 // - and next delta is smaller (or changing direction):
109 // - and next delta significant (at least twice) bigger:
113 // - and next delta is nearly same:
118 // if curr_delta is negative,
120 // - and next delta is smaller (or changing direction):
124 // - and next delta significant (at least twice) bigger:
128 // - and next delta is nearly same:
133 static void InterpolateUp(int *SB, int sinc)
135 if(SB[32]==1) // flag == 1? calc step and set flag... and don't change the value in this pass
137 const int id1=SB[30]-SB[29]; // curr delta to next val
138 const int id2=SB[31]-SB[30]; // and next delta to next-next val :)
142 if(id1>0) // curr delta positive
145 {SB[28]=id1;SB[32]=2;}
148 SB[28]=(id1*sinc)>>16;
150 SB[28]=(id1*sinc)>>17;
152 else // curr delta negative
155 {SB[28]=id1;SB[32]=2;}
158 SB[28]=(id1*sinc)>>16;
160 SB[28]=(id1*sinc)>>17;
164 if(SB[32]==2) // flag 1: calc step and set flag... and don't change the value in this pass
168 SB[28]=(SB[28]*sinc)>>17;
170 // SB[29]=SB[30]-(SB[28]*((0x10000/sinc)-1));
174 else // no flags? add bigger val (if possible), calc smaller step, set flag1
179 // even easier interpolation on downsampling, also no special filter, again just "Pete's common sense" tm
182 static void InterpolateDown(int *SB, int sinc)
184 if(sinc>=0x20000L) // we would skip at least one val?
186 SB[29]+=(SB[30]-SB[29])/2; // add easy weight
187 if(sinc>=0x30000L) // we would skip even more vals?
188 SB[29]+=(SB[31]-SB[30])/2; // add additional next weight
192 ////////////////////////////////////////////////////////////////////////
193 // helpers for gauss interpolation
195 #define gval0 (((short*)(&SB[29]))[gpos&3])
196 #define gval(x) ((int)((short*)(&SB[29]))[(gpos+x)&3])
200 ////////////////////////////////////////////////////////////////////////
204 static void do_irq(void)
206 //if(!(spu.spuStat & STAT_IRQ))
208 spu.spuStat |= STAT_IRQ; // asserted status?
209 if(spu.irqCallback) spu.irqCallback();
213 static int check_irq(int ch, unsigned char *pos)
215 if((spu.spuCtrl & (CTRL_ON|CTRL_IRQ)) == (CTRL_ON|CTRL_IRQ) && pos == spu.pSpuIrq)
217 //printf("ch%d irq %04x\n", ch, pos - spu.spuMemC);
224 void check_irq_io(unsigned int addr)
226 unsigned int irq_addr = regAreaGet(H_SPUirqAddr) << 3;
228 if((spu.spuCtrl & (CTRL_ON|CTRL_IRQ)) == (CTRL_ON|CTRL_IRQ) && addr == irq_addr)
230 //printf("io irq %04x\n", irq_addr);
235 ////////////////////////////////////////////////////////////////////////
236 // START SOUND... called by main thread to setup a new sound on a channel
237 ////////////////////////////////////////////////////////////////////////
239 static void StartSoundSB(int *SB)
241 SB[26]=0; // init mixing vars
245 SB[29]=0; // init our interpolation helpers
250 static void StartSoundMain(int ch)
252 SPUCHAN *s_chan = &spu.s_chan[ch];
261 s_chan->pCurr = spu.spuMemC + ((regAreaGetCh(ch, 6) & ~1) << 3);
263 spu.dwNewChannel&=~(1<<ch); // clear new channel bit
264 spu.dwChannelDead&=~(1<<ch);
265 spu.dwChannelsAudible|=1<<ch;
268 static void StartSound(int ch)
271 StartSoundSB(spu.SB + ch * SB_SIZE);
274 ////////////////////////////////////////////////////////////////////////
275 // ALL KIND OF HELPERS
276 ////////////////////////////////////////////////////////////////////////
278 INLINE int FModChangeFrequency(int *SB, int pitch, int ns)
280 unsigned int NP=pitch;
283 NP=((32768L+iFMod[ns])*NP)>>15;
285 if(NP>0x3fff) NP=0x3fff;
288 sinc=NP<<4; // calc frequency
289 if(spu_config.iUseInterpolation==1) // freq change in simple interpolation mode
296 ////////////////////////////////////////////////////////////////////////
298 INLINE void StoreInterpolationVal(int *SB, int sinc, int fa, int fmod_freq)
300 if(fmod_freq) // fmod freq channel
306 if(spu_config.iUseInterpolation>=2) // gauss/cubic interpolation
314 if(spu_config.iUseInterpolation==1) // simple interpolation
317 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'
320 SB[32] = 1; // -> flag: calc new interolation
322 else SB[29]=fa; // no interpolation
326 ////////////////////////////////////////////////////////////////////////
328 INLINE int iGetInterpolationVal(int *SB, int sinc, int spos, int fmod_freq)
332 if(fmod_freq) return SB[29];
334 switch(spu_config.iUseInterpolation)
336 //--------------------------------------------------//
337 case 3: // cubic interpolation
343 fa = gval(3) - 3*gval(2) + 3*gval(1) - gval0;
344 fa *= (xd - (2<<15)) / 6;
346 fa += gval(2) - gval(1) - gval(1) + gval0;
347 fa *= (xd - (1<<15)) >> 1;
349 fa += gval(1) - gval0;
355 //--------------------------------------------------//
356 case 2: // gauss interpolation
359 vl = (spos >> 6) & ~3;
361 vr=(gauss[vl]*(int)gval0) >> 15;
362 vr+=(gauss[vl+1]*gval(1)) >> 15;
363 vr+=(gauss[vl+2]*gval(2)) >> 15;
364 vr+=(gauss[vl+3]*gval(3)) >> 15;
367 //--------------------------------------------------//
368 case 1: // simple interpolation
370 if(sinc<0x10000L) // -> upsampling?
371 InterpolateUp(SB, sinc); // --> interpolate up
372 else InterpolateDown(SB, sinc); // --> else down
375 //--------------------------------------------------//
376 default: // no interpolation
380 //--------------------------------------------------//
386 static void decode_block_data(int *dest, const unsigned char *src, int predict_nr, int shift_factor)
388 static const int f[16][2] = {
396 int fa, s_1, s_2, d, s;
401 for (nSample = 0; nSample < 28; src++)
404 s = (int)(signed short)((d & 0x0f) << 12);
406 fa = s >> shift_factor;
407 fa += ((s_1 * f[predict_nr][0])>>6) + ((s_2 * f[predict_nr][1])>>6);
410 dest[nSample++] = fa;
412 s = (int)(signed short)((d & 0xf0) << 8);
413 fa = s >> shift_factor;
414 fa += ((s_1 * f[predict_nr][0])>>6) + ((s_2 * f[predict_nr][1])>>6);
417 dest[nSample++] = fa;
421 static int decode_block(void *unused, int ch, int *SB)
423 SPUCHAN *s_chan = &spu.s_chan[ch];
424 unsigned char *start;
425 int predict_nr, shift_factor, flags;
428 start = s_chan->pCurr; // set up the current pos
429 if (start == spu.spuMemC) // ?
432 if (s_chan->prevflags & 1) // 1: stop/loop
434 if (!(s_chan->prevflags & 2))
437 start = s_chan->pLoop;
440 check_irq(ch, start);
442 predict_nr = start[0];
443 shift_factor = predict_nr & 0xf;
446 decode_block_data(SB, start + 2, predict_nr, shift_factor);
449 if (flags & 4 && !s_chan->bIgnoreLoop)
450 s_chan->pLoop = start; // loop adress
454 s_chan->pCurr = start; // store values for next cycle
455 s_chan->prevflags = flags;
460 // do block, but ignore sample data
461 static int skip_block(int ch)
463 SPUCHAN *s_chan = &spu.s_chan[ch];
464 unsigned char *start = s_chan->pCurr;
468 if (s_chan->prevflags & 1) {
469 if (!(s_chan->prevflags & 2))
472 start = s_chan->pLoop;
475 check_irq(ch, start);
478 if (flags & 4 && !s_chan->bIgnoreLoop)
479 s_chan->pLoop = start;
483 s_chan->pCurr = start;
484 s_chan->prevflags = flags;
489 // if irq is going to trigger sooner than in upd_samples, set upd_samples
490 static void scan_for_irq(int ch, unsigned int *upd_samples)
492 SPUCHAN *s_chan = &spu.s_chan[ch];
493 int pos, sinc, sinc_inv, end;
494 unsigned char *block;
497 block = s_chan->pCurr;
500 end = pos + *upd_samples * sinc;
502 pos += (28 - s_chan->iSBPos) << 16;
505 if (block == spu.pSpuIrq)
509 if (flags & 1) { // 1: stop/loop
510 block = s_chan->pLoop;
517 sinc_inv = s_chan->sinc_inv;
519 sinc_inv = s_chan->sinc_inv = (0x80000000u / (uint32_t)sinc) << 1;
522 *upd_samples = (((uint64_t)pos * sinc_inv) >> 32) + 1;
523 //xprintf("ch%02d: irq sched: %3d %03d\n",
524 // ch, *upd_samples, *upd_samples * 60 * 263 / 44100);
528 #define make_do_samples(name, fmod_code, interp_start, interp1_code, interp2_code, interp_end) \
529 static noinline int do_samples_##name( \
530 int (*decode_f)(void *context, int ch, int *SB), void *ctx, \
531 int ch, int ns_to, int *SB, int sinc, int *spos, int *sbpos) \
537 for (ns = 0; ns < ns_to; ns++) \
542 while (*spos >= 0x10000) \
544 fa = SB[(*sbpos)++]; \
548 d = decode_f(ctx, ch, SB); \
565 #define fmod_recv_check \
566 if(spu.s_chan[ch].bFMod==1 && iFMod[ns]) \
567 sinc = FModChangeFrequency(SB, spu.s_chan[ch].iRawPitch, ns)
569 make_do_samples(default, fmod_recv_check, ,
570 StoreInterpolationVal(SB, sinc, fa, spu.s_chan[ch].bFMod==2),
571 ChanBuf[ns] = iGetInterpolationVal(SB, sinc, *spos, spu.s_chan[ch].bFMod==2), )
572 make_do_samples(noint, , fa = SB[29], , ChanBuf[ns] = fa, SB[29] = fa)
574 #define simple_interp_store \
581 #define simple_interp_get \
582 if(sinc<0x10000) /* -> upsampling? */ \
583 InterpolateUp(SB, sinc); /* --> interpolate up */ \
584 else InterpolateDown(SB, sinc); /* --> else down */ \
587 make_do_samples(simple, , ,
588 simple_interp_store, simple_interp_get, )
590 static int do_samples_skip(int ch, int ns_to)
592 SPUCHAN *s_chan = &spu.s_chan[ch];
593 int spos = s_chan->spos;
594 int sinc = s_chan->sinc;
595 int ret = ns_to, ns, d;
597 spos += s_chan->iSBPos << 16;
599 for (ns = 0; ns < ns_to; ns++)
602 while (spos >= 28*0x10000)
611 s_chan->iSBPos = spos >> 16;
612 s_chan->spos = spos & 0xffff;
617 static void do_lsfr_samples(int ns_to, int ctrl,
618 unsigned int *dwNoiseCount, unsigned int *dwNoiseVal)
620 unsigned int counter = *dwNoiseCount;
621 unsigned int val = *dwNoiseVal;
622 unsigned int level, shift, bit;
625 // modified from DrHell/shalma, no fraction
626 level = (ctrl >> 10) & 0x0f;
627 level = 0x8000 >> level;
629 for (ns = 0; ns < ns_to; ns++)
632 if (counter >= level)
635 shift = (val >> 10) & 0x1f;
636 bit = (0x69696969 >> shift) & 1;
637 bit ^= (val >> 15) & 1;
638 val = (val << 1) | bit;
641 ChanBuf[ns] = (signed short)val;
644 *dwNoiseCount = counter;
648 static int do_samples_noise(int ch, int ns_to)
652 ret = do_samples_skip(ch, ns_to);
654 do_lsfr_samples(ns_to, spu.spuCtrl, &spu.dwNoiseCount, &spu.dwNoiseVal);
660 // asm code; lv and rv must be 0-3fff
661 extern void mix_chan(int *SSumLR, int count, int lv, int rv);
662 extern void mix_chan_rvb(int *SSumLR, int count, int lv, int rv, int *rvb);
664 static void mix_chan(int *SSumLR, int count, int lv, int rv)
666 const int *src = ChanBuf;
673 l = (sval * lv) >> 14;
674 r = (sval * rv) >> 14;
680 static void mix_chan_rvb(int *SSumLR, int count, int lv, int rv, int *rvb)
682 const int *src = ChanBuf;
691 l = (sval * lv) >> 14;
692 r = (sval * rv) >> 14;
701 // 0x0800-0x0bff Voice 1
702 // 0x0c00-0x0fff Voice 3
703 static noinline void do_decode_bufs(unsigned short *mem, int which,
704 int count, int decode_pos)
706 unsigned short *dst = &mem[0x800/2 + which*0x400/2];
707 const int *src = ChanBuf;
708 int cursor = decode_pos;
713 dst[cursor] = *src++;
717 // decode_pos is updated and irqs are checked later, after voice loop
720 static void do_silent_chans(int ns_to, int silentch)
726 mask = silentch & 0xffffff;
727 for (ch = 0; mask != 0; ch++, mask >>= 1)
729 if (!(mask & 1)) continue;
730 if (spu.dwChannelDead & (1<<ch)) continue;
732 s_chan = &spu.s_chan[ch];
733 if (s_chan->pCurr > spu.pSpuIrq && s_chan->pLoop > spu.pSpuIrq)
736 s_chan->spos += s_chan->iSBPos << 16;
739 s_chan->spos += s_chan->sinc * ns_to;
740 while (s_chan->spos >= 28 * 0x10000)
742 unsigned char *start = s_chan->pCurr;
745 if (start == s_chan->pCurr || start - spu.spuMemC < 0x1000)
747 // looping on self or stopped(?)
748 spu.dwChannelDead |= 1<<ch;
753 s_chan->spos -= 28 * 0x10000;
758 static void do_channels(int ns_to)
765 do_rvb = spu.rvb->StartAddr && spu_config.iUseReverb;
767 memset(RVB, 0, ns_to * sizeof(RVB[0]) * 2);
769 mask = spu.dwNewChannel & 0xffffff;
770 for (ch = 0; mask != 0; ch++, mask >>= 1) {
775 mask = spu.dwChannelsAudible & 0xffffff;
776 for (ch = 0; mask != 0; ch++, mask >>= 1) // loop em all...
778 if (!(mask & 1)) continue; // channel not playing? next
780 s_chan = &spu.s_chan[ch];
781 SB = spu.SB + ch * SB_SIZE;
785 d = do_samples_noise(ch, ns_to);
786 else if (s_chan->bFMod == 2
787 || (s_chan->bFMod == 0 && spu_config.iUseInterpolation == 0))
788 d = do_samples_noint(decode_block, NULL, ch, ns_to,
789 SB, sinc, &s_chan->spos, &s_chan->iSBPos);
790 else if (s_chan->bFMod == 0 && spu_config.iUseInterpolation == 1)
791 d = do_samples_simple(decode_block, NULL, ch, ns_to,
792 SB, sinc, &s_chan->spos, &s_chan->iSBPos);
794 d = do_samples_default(decode_block, NULL, ch, ns_to,
795 SB, sinc, &s_chan->spos, &s_chan->iSBPos);
797 d = MixADSR(&s_chan->ADSRX, d);
799 spu.dwChannelsAudible &= ~(1 << ch);
800 s_chan->ADSRX.State = ADSR_RELEASE;
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 && do_rvb)
814 mix_chan_rvb(spu.SSumLR, ns_to, s_chan->iLeftVolume, s_chan->iRightVolume, RVB);
816 mix_chan(spu.SSumLR, ns_to, s_chan->iLeftVolume, s_chan->iRightVolume);
819 if (spu.rvb->StartAddr) {
821 REVERBDo(spu.SSumLR, RVB, ns_to, spu.rvb->CurrAddr);
823 spu.rvb->CurrAddr += ns_to / 2;
824 while (spu.rvb->CurrAddr >= 0x40000)
825 spu.rvb->CurrAddr -= 0x40000 - spu.rvb->StartAddr;
829 static void do_samples_finish(int *SSumLR, int ns_to,
830 int silentch, int decode_pos);
832 // optional worker thread handling
834 #if defined(THREAD_ENABLED) || defined(WANT_THREAD_CODE)
836 // worker thread state
837 static struct spu_worker {
840 unsigned int exit_thread;
841 unsigned int i_ready;
842 unsigned int i_reaped;
843 unsigned int last_boot_cnt; // dsp
844 unsigned int ram_dirty;
846 // aligning for C64X_DSP
847 unsigned int _pad0[128/4];
852 unsigned int active; // dsp
853 unsigned int boot_cnt;
855 unsigned int _pad1[128/4];
862 unsigned int channels_new;
863 unsigned int channels_on;
864 unsigned int channels_silent;
875 // might also want to add fmod flags..
877 int SSumLR[NSSIZE * 2];
881 #define WORK_MAXCNT (sizeof(worker->i) / sizeof(worker->i[0]))
882 #define WORK_I_MASK (WORK_MAXCNT - 1)
884 static void thread_work_start(void);
885 static void thread_work_wait_sync(struct work_item *work, int force);
886 static void thread_sync_caches(void);
887 static int thread_get_i_done(void);
889 static int decode_block_work(void *context, int ch, int *SB)
891 const unsigned char *ram = spu.spuMemC;
892 int predict_nr, shift_factor, flags;
893 struct work_item *work = context;
894 int start = work->ch[ch].start;
895 int loop = work->ch[ch].loop;
897 predict_nr = ram[start];
898 shift_factor = predict_nr & 0xf;
901 decode_block_data(SB, ram + start + 2, predict_nr, shift_factor);
903 flags = ram[start + 1];
905 loop = start; // loop adress
909 if (flags & 1) // 1: stop/loop
912 work->ch[ch].start = start & 0x7ffff;
913 work->ch[ch].loop = loop;
918 static void queue_channel_work(int ns_to, unsigned int silentch)
920 struct work_item *work;
925 work = &worker->i[worker->i_ready & WORK_I_MASK];
927 work->ctrl = spu.spuCtrl;
928 work->decode_pos = spu.decode_pos;
929 work->channels_silent = silentch;
931 mask = work->channels_new = spu.dwNewChannel & 0xffffff;
932 for (ch = 0; mask != 0; ch++, mask >>= 1) {
937 mask = work->channels_on = spu.dwChannelsAudible & 0xffffff;
938 spu.decode_dirty_ch |= mask & 0x0a;
940 for (ch = 0; mask != 0; ch++, mask >>= 1)
942 if (!(mask & 1)) continue;
944 s_chan = &spu.s_chan[ch];
945 work->ch[ch].spos = s_chan->spos;
946 work->ch[ch].sbpos = s_chan->iSBPos;
947 work->ch[ch].sinc = s_chan->sinc;
948 work->ch[ch].adsr = s_chan->ADSRX;
949 work->ch[ch].vol_l = s_chan->iLeftVolume;
950 work->ch[ch].vol_r = s_chan->iRightVolume;
951 work->ch[ch].start = s_chan->pCurr - spu.spuMemC;
952 work->ch[ch].loop = s_chan->pLoop - spu.spuMemC;
953 if (s_chan->prevflags & 1)
954 work->ch[ch].start = work->ch[ch].loop;
956 d = do_samples_skip(ch, ns_to);
957 work->ch[ch].ns_to = d;
959 // note: d is not accurate on skip
960 d = SkipADSR(&s_chan->ADSRX, d);
962 spu.dwChannelsAudible &= ~(1 << ch);
963 s_chan->ADSRX.State = ADSR_RELEASE;
964 s_chan->ADSRX.EnvelopeVol = 0;
969 if (spu.rvb->StartAddr) {
970 if (spu_config.iUseReverb)
971 work->rvb_addr = spu.rvb->CurrAddr;
973 spu.rvb->CurrAddr += ns_to / 2;
974 while (spu.rvb->CurrAddr >= 0x40000)
975 spu.rvb->CurrAddr -= 0x40000 - spu.rvb->StartAddr;
982 static void do_channel_work(struct work_item *work)
985 unsigned int decode_dirty_ch = 0;
986 const SPUCHAN *s_chan;
987 int *SB, sinc, spos, sbpos;
993 memset(RVB, 0, ns_to * sizeof(RVB[0]) * 2);
995 mask = work->channels_new;
996 for (ch = 0; mask != 0; ch++, mask >>= 1) {
998 StartSoundSB(spu.SB + ch * SB_SIZE);
1001 mask = work->channels_on;
1002 for (ch = 0; mask != 0; ch++, mask >>= 1)
1004 if (!(mask & 1)) continue;
1006 d = work->ch[ch].ns_to;
1007 spos = work->ch[ch].spos;
1008 sbpos = work->ch[ch].sbpos;
1009 sinc = work->ch[ch].sinc;
1011 s_chan = &spu.s_chan[ch];
1012 SB = spu.SB + ch * SB_SIZE;
1015 do_lsfr_samples(d, work->ctrl, &spu.dwNoiseCount, &spu.dwNoiseVal);
1016 else if (s_chan->bFMod == 2
1017 || (s_chan->bFMod == 0 && spu_config.iUseInterpolation == 0))
1018 do_samples_noint(decode_block_work, work, ch, d, SB, sinc, &spos, &sbpos);
1019 else if (s_chan->bFMod == 0 && spu_config.iUseInterpolation == 1)
1020 do_samples_simple(decode_block_work, work, ch, d, SB, sinc, &spos, &sbpos);
1022 do_samples_default(decode_block_work, work, ch, d, SB, sinc, &spos, &sbpos);
1024 d = MixADSR(&work->ch[ch].adsr, d);
1026 work->ch[ch].adsr.EnvelopeVol = 0;
1027 memset(&ChanBuf[d], 0, (ns_to - d) * sizeof(ChanBuf[0]));
1030 if (ch == 1 || ch == 3)
1032 do_decode_bufs(spu.spuMem, ch/2, ns_to, work->decode_pos);
1033 decode_dirty_ch |= 1 << ch;
1036 if (s_chan->bFMod == 2) // fmod freq channel
1037 memcpy(iFMod, &ChanBuf, ns_to * sizeof(iFMod[0]));
1038 if (s_chan->bRVBActive && work->rvb_addr)
1039 mix_chan_rvb(work->SSumLR, ns_to,
1040 work->ch[ch].vol_l, work->ch[ch].vol_r, RVB);
1042 mix_chan(work->SSumLR, ns_to, work->ch[ch].vol_l, work->ch[ch].vol_r);
1046 REVERBDo(work->SSumLR, RVB, ns_to, work->rvb_addr);
1049 static void sync_worker_thread(int force)
1051 struct work_item *work;
1052 int done, used_space;
1054 // rvb offsets will change, thread may be using them
1055 force |= spu.rvb->dirty && spu.rvb->StartAddr;
1057 done = thread_get_i_done() - worker->i_reaped;
1058 used_space = worker->i_ready - worker->i_reaped;
1060 //printf("done: %d use: %d dsp: %u/%u\n", done, used_space,
1061 // worker->boot_cnt, worker->i_done);
1063 while ((force && used_space > 0) || used_space >= WORK_MAXCNT || done > 0) {
1064 work = &worker->i[worker->i_reaped & WORK_I_MASK];
1065 thread_work_wait_sync(work, force);
1067 do_samples_finish(work->SSumLR, work->ns_to,
1068 work->channels_silent, work->decode_pos);
1071 done = thread_get_i_done() - worker->i_reaped;
1072 used_space = worker->i_ready - worker->i_reaped;
1075 thread_sync_caches();
1080 static void queue_channel_work(int ns_to, int silentch) {}
1081 static void sync_worker_thread(int force) {}
1083 static const void * const worker = NULL;
1085 #endif // THREAD_ENABLED
1087 ////////////////////////////////////////////////////////////////////////
1088 // MAIN SPU FUNCTION
1089 // here is the main job handler...
1090 ////////////////////////////////////////////////////////////////////////
1092 void do_samples(unsigned int cycles_to, int do_direct)
1094 unsigned int silentch;
1098 cycle_diff = cycles_to - spu.cycles_played;
1099 if (cycle_diff < -2*1048576 || cycle_diff > 2*1048576)
1101 //xprintf("desync %u %d\n", cycles_to, cycle_diff);
1102 spu.cycles_played = cycles_to;
1106 silentch = ~(spu.dwChannelsAudible | spu.dwNewChannel) & 0xffffff;
1108 do_direct |= (silentch == 0xffffff);
1110 sync_worker_thread(do_direct);
1112 if (cycle_diff < 2 * 768)
1115 ns_to = (cycle_diff / 768 + 1) & ~1;
1116 if (ns_to > NSSIZE) {
1117 // should never happen
1118 //xprintf("ns_to oflow %d %d\n", ns_to, NSSIZE);
1122 //////////////////////////////////////////////////////
1123 // special irq handling in the decode buffers (0x0000-0x1000)
1125 // the decode buffers are located in spu memory in the following way:
1126 // 0x0000-0x03ff CD audio left
1127 // 0x0400-0x07ff CD audio right
1128 // 0x0800-0x0bff Voice 1
1129 // 0x0c00-0x0fff Voice 3
1130 // and decoded data is 16 bit for one sample
1132 // even if voices 1/3 are off or no cd audio is playing, the internal
1133 // play positions will move on and wrap after 0x400 bytes.
1134 // Therefore: we just need a pointer from spumem+0 to spumem+3ff, and
1135 // increase this pointer on each sample by 2 bytes. If this pointer
1136 // (or 0x400 offsets of this pointer) hits the spuirq address, we generate
1139 if (unlikely((spu.spuCtrl & CTRL_IRQ)
1140 && spu.pSpuIrq < spu.spuMemC+0x1000))
1142 int irq_pos = (spu.pSpuIrq - spu.spuMemC) / 2 & 0x1ff;
1143 int left = (irq_pos - spu.decode_pos) & 0x1ff;
1144 if (0 < left && left <= ns_to)
1146 //xprintf("decoder irq %x\n", spu.decode_pos);
1150 check_irq_io(spu.spuAddr);
1152 if (unlikely(spu.rvb->dirty))
1155 if (do_direct || worker == NULL || !spu_config.iUseThread) {
1157 do_samples_finish(spu.SSumLR, ns_to, silentch, spu.decode_pos);
1160 queue_channel_work(ns_to, silentch);
1163 // advance "stopped" channels that can cause irqs
1164 // (all chans are always playing on the real thing..)
1165 if (spu.spuCtrl & CTRL_IRQ)
1166 do_silent_chans(ns_to, silentch);
1168 spu.cycles_played += ns_to * 768;
1169 spu.decode_pos = (spu.decode_pos + ns_to) & 0x1ff;
1172 static void do_samples_finish(int *SSumLR, int ns_to,
1173 int silentch, int decode_pos)
1175 int vol_l = ((int)regAreaGet(H_SPUmvolL) << 17) >> 17;
1176 int vol_r = ((int)regAreaGet(H_SPUmvolR) << 17) >> 17;
1180 // must clear silent channel decode buffers
1181 if(unlikely(silentch & spu.decode_dirty_ch & (1<<1)))
1183 memset(&spu.spuMem[0x800/2], 0, 0x400);
1184 spu.decode_dirty_ch &= ~(1<<1);
1186 if(unlikely(silentch & spu.decode_dirty_ch & (1<<3)))
1188 memset(&spu.spuMem[0xc00/2], 0, 0x400);
1189 spu.decode_dirty_ch &= ~(1<<3);
1192 MixXA(SSumLR, ns_to, decode_pos);
1194 vol_l = vol_l * spu_config.iVolume >> 10;
1195 vol_r = vol_r * spu_config.iVolume >> 10;
1197 if (!(spu.spuCtrl & 0x4000) || !(vol_l | vol_r))
1200 memset(spu.pS, 0, ns_to * 2 * sizeof(spu.pS[0]));
1201 memset(SSumLR, 0, ns_to * 2 * sizeof(SSumLR[0]));
1202 spu.pS += ns_to * 2;
1205 for (ns = 0; ns < ns_to * 2; )
1207 d = SSumLR[ns]; SSumLR[ns] = 0;
1208 d = d * vol_l >> 14;
1213 d = SSumLR[ns]; SSumLR[ns] = 0;
1214 d = d * vol_r >> 14;
1221 void schedule_next_irq(void)
1223 unsigned int upd_samples;
1226 if (spu.scheduleCallback == NULL)
1229 upd_samples = 44100 / 50;
1231 for (ch = 0; ch < MAXCHAN; ch++)
1233 if (spu.dwChannelDead & (1 << ch))
1235 if ((unsigned long)(spu.pSpuIrq - spu.s_chan[ch].pCurr) > IRQ_NEAR_BLOCKS * 16
1236 && (unsigned long)(spu.pSpuIrq - spu.s_chan[ch].pLoop) > IRQ_NEAR_BLOCKS * 16)
1238 if (spu.s_chan[ch].sinc == 0)
1241 scan_for_irq(ch, &upd_samples);
1244 if (unlikely(spu.pSpuIrq < spu.spuMemC + 0x1000))
1246 int irq_pos = (spu.pSpuIrq - spu.spuMemC) / 2 & 0x1ff;
1247 int left = (irq_pos - spu.decode_pos) & 0x1ff;
1248 if (0 < left && left < upd_samples) {
1249 //xprintf("decode: %3d (%3d/%3d)\n", left, spu.decode_pos, irq_pos);
1254 if (upd_samples < 44100 / 50)
1255 spu.scheduleCallback(upd_samples * 768);
1258 // SPU ASYNC... even newer epsxe func
1259 // 1 time every 'cycle' cycles... harhar
1261 // rearmed: called dynamically now
1263 void CALLBACK SPUasync(unsigned int cycle, unsigned int flags)
1265 do_samples(cycle, spu_config.iUseFixedUpdates);
1267 if (spu.spuCtrl & CTRL_IRQ)
1268 schedule_next_irq();
1271 out_current->feed(spu.pSpuBuffer, (unsigned char *)spu.pS - spu.pSpuBuffer);
1272 spu.pS = (short *)spu.pSpuBuffer;
1274 if (spu_config.iTempo) {
1275 if (!out_current->busy())
1276 // cause more samples to be generated
1277 // (and break some games because of bad sync)
1278 spu.cycles_played -= 44100 / 60 / 2 * 768;
1283 // SPU UPDATE... new epsxe func
1284 // 1 time every 32 hsync lines
1285 // (312/32)x50 in pal
1286 // (262/32)x60 in ntsc
1288 // since epsxe 1.5.2 (linux) uses SPUupdate, not SPUasync, I will
1289 // leave that func in the linux port, until epsxe linux is using
1290 // the async function as well
1292 void CALLBACK SPUupdate(void)
1298 void CALLBACK SPUplayADPCMchannel(xa_decode_t *xap, unsigned int cycle, int is_start)
1301 if(!xap->freq) return; // no xa freq ? bye
1304 do_samples(cycle, 1); // catch up to prevent source underflows later
1306 FeedXA(xap); // call main XA feeder
1310 int CALLBACK SPUplayCDDAchannel(short *pcm, int nbytes, unsigned int cycle, int is_start)
1312 if (!pcm) return -1;
1313 if (nbytes<=0) return -1;
1316 do_samples(cycle, 1); // catch up to prevent source underflows later
1318 return FeedCDDA((unsigned char *)pcm, nbytes);
1321 // to be called after state load
1322 void ClearWorkingState(void)
1324 memset(iFMod, 0, sizeof(iFMod));
1325 spu.pS=(short *)spu.pSpuBuffer; // setup soundbuffer pointer
1328 // SETUPSTREAMS: init most of the spu buffers
1329 static void SetupStreams(void)
1331 spu.pSpuBuffer = (unsigned char *)malloc(32768); // alloc mixing buffer
1332 spu.SSumLR = calloc(NSSIZE * 2, sizeof(spu.SSumLR[0]));
1334 spu.XAStart = malloc(44100 * sizeof(uint32_t)); // alloc xa buffer
1335 spu.XAEnd = spu.XAStart + 44100;
1336 spu.XAPlay = spu.XAStart;
1337 spu.XAFeed = spu.XAStart;
1339 spu.CDDAStart = malloc(CDDA_BUFFER_SIZE); // alloc cdda buffer
1340 spu.CDDAEnd = spu.CDDAStart + 16384;
1341 spu.CDDAPlay = spu.CDDAStart;
1342 spu.CDDAFeed = spu.CDDAStart;
1344 ClearWorkingState();
1347 // REMOVESTREAMS: free most buffer
1348 static void RemoveStreams(void)
1350 free(spu.pSpuBuffer); // free mixing buffer
1351 spu.pSpuBuffer = NULL;
1354 free(spu.XAStart); // free XA buffer
1356 free(spu.CDDAStart); // free CDDA buffer
1357 spu.CDDAStart = NULL;
1360 #if defined(C64X_DSP)
1362 /* special code for TI C64x DSP */
1363 #include "spu_c64x.c"
1365 #elif defined(THREAD_ENABLED)
1367 #include <pthread.h>
1368 #include <semaphore.h>
1377 /* generic pthread implementation */
1379 static void thread_work_start(void)
1381 sem_post(&t.sem_avail);
1384 static void thread_work_wait_sync(struct work_item *work, int force)
1386 sem_wait(&t.sem_done);
1389 static int thread_get_i_done(void)
1391 return worker->i_done;
1394 static void thread_sync_caches(void)
1398 static void *spu_worker_thread(void *unused)
1400 struct work_item *work;
1403 sem_wait(&t.sem_avail);
1404 if (worker->exit_thread)
1407 work = &worker->i[worker->i_done & WORK_I_MASK];
1408 do_channel_work(work);
1411 sem_post(&t.sem_done);
1417 static void init_spu_thread(void)
1421 if (sysconf(_SC_NPROCESSORS_ONLN) <= 1)
1424 worker = calloc(1, sizeof(*worker));
1427 ret = sem_init(&t.sem_avail, 0, 0);
1429 goto fail_sem_avail;
1430 ret = sem_init(&t.sem_done, 0, 0);
1434 ret = pthread_create(&t.thread, NULL, spu_worker_thread, NULL);
1438 spu_config.iThreadAvail = 1;
1442 sem_destroy(&t.sem_done);
1444 sem_destroy(&t.sem_avail);
1448 spu_config.iThreadAvail = 0;
1451 static void exit_spu_thread(void)
1455 worker->exit_thread = 1;
1456 sem_post(&t.sem_avail);
1457 pthread_join(t.thread, NULL);
1458 sem_destroy(&t.sem_done);
1459 sem_destroy(&t.sem_avail);
1464 #else // if !THREAD_ENABLED
1466 static void init_spu_thread(void)
1470 static void exit_spu_thread(void)
1476 // SPUINIT: this func will be called first by the main emu
1477 long CALLBACK SPUinit(void)
1481 spu.spuMemC = calloc(1, 512 * 1024);
1484 spu.s_chan = calloc(MAXCHAN+1, sizeof(spu.s_chan[0])); // channel + 1 infos (1 is security for fmod handling)
1485 spu.rvb = calloc(1, sizeof(REVERBInfo));
1486 spu.SB = calloc(MAXCHAN, sizeof(spu.SB[0]) * SB_SIZE);
1490 spu.pSpuIrq = spu.spuMemC;
1492 SetupStreams(); // prepare streaming
1494 if (spu_config.iVolume == 0)
1495 spu_config.iVolume = 768; // 1024 is 1.0
1499 for (i = 0; i < MAXCHAN; i++) // loop sound channels
1501 spu.s_chan[i].ADSRX.SustainLevel = 0xf; // -> init sustain
1502 spu.s_chan[i].ADSRX.SustainIncrease = 1;
1503 spu.s_chan[i].pLoop = spu.spuMemC;
1504 spu.s_chan[i].pCurr = spu.spuMemC;
1505 spu.s_chan[i].bIgnoreLoop = 0;
1508 spu.bSpuInit=1; // flag: we are inited
1513 // SPUOPEN: called by main emu after init
1514 long CALLBACK SPUopen(void)
1516 if (spu.bSPUIsOpen) return 0; // security for some stupid main emus
1518 SetupSound(); // setup sound (before init!)
1522 return PSE_SPU_ERR_SUCCESS;
1525 // SPUCLOSE: called before shutdown
1526 long CALLBACK SPUclose(void)
1528 if (!spu.bSPUIsOpen) return 0; // some security
1530 spu.bSPUIsOpen = 0; // no more open
1532 out_current->finish(); // no more sound handling
1537 // SPUSHUTDOWN: called by main emu on final exit
1538 long CALLBACK SPUshutdown(void)
1553 RemoveStreams(); // no more streaming
1559 // SPUTEST: we don't test, we are always fine ;)
1560 long CALLBACK SPUtest(void)
1565 // SPUCONFIGURE: call config dialog
1566 long CALLBACK SPUconfigure(void)
1571 // StartCfgTool("CFG");
1576 // SPUABOUT: show about window
1577 void CALLBACK SPUabout(void)
1582 // StartCfgTool("ABOUT");
1587 // this functions will be called once,
1588 // passes a callback that should be called on SPU-IRQ/cdda volume change
1589 void CALLBACK SPUregisterCallback(void (CALLBACK *callback)(void))
1591 spu.irqCallback = callback;
1594 void CALLBACK SPUregisterCDDAVolume(void (CALLBACK *CDDAVcallback)(short, short))
1596 spu.cddavCallback = CDDAVcallback;
1599 void CALLBACK SPUregisterScheduleCb(void (CALLBACK *callback)(unsigned int))
1601 spu.scheduleCallback = callback;
1604 // COMMON PLUGIN INFO FUNCS
1606 char * CALLBACK PSEgetLibName(void)
1608 return _(libraryName);
1611 unsigned long CALLBACK PSEgetLibType(void)
1616 unsigned long CALLBACK PSEgetLibVersion(void)
1618 return (1 << 16) | (6 << 8);
1621 char * SPUgetLibInfos(void)
1623 return _(libraryInfo);
1628 void spu_get_debug_info(int *chans_out, int *run_chans, int *fmod_chans_out, int *noise_chans_out)
1630 int ch = 0, fmod_chans = 0, noise_chans = 0, irq_chans = 0;
1632 if (spu.s_chan == NULL)
1635 for(;ch<MAXCHAN;ch++)
1637 if (!(spu.dwChannelsAudible & (1<<ch)))
1639 if (spu.s_chan[ch].bFMod == 2)
1640 fmod_chans |= 1 << ch;
1641 if (spu.s_chan[ch].bNoise)
1642 noise_chans |= 1 << ch;
1643 if((spu.spuCtrl&CTRL_IRQ) && spu.s_chan[ch].pCurr <= spu.pSpuIrq && spu.s_chan[ch].pLoop <= spu.pSpuIrq)
1644 irq_chans |= 1 << ch;
1647 *chans_out = spu.dwChannelsAudible;
1648 *run_chans = ~spu.dwChannelsAudible & ~spu.dwChannelDead & irq_chans;
1649 *fmod_chans_out = fmod_chans;
1650 *noise_chans_out = noise_chans;
1653 // vim:shiftwidth=1:expandtab