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 ***************************************************************************/
26 #include "externals.h"
27 #include "registers.h"
29 #include "spu_config.h"
32 #include "arm_features.h"
36 #define ssat32_to_16(v) \
37 asm("ssat %0,#16,%1" : "=r" (v) : "r" (v))
39 #define ssat32_to_16(v) do { \
40 if (v < -32768) v = -32768; \
41 else if (v > 32767) v = 32767; \
45 #define PSXCLK 33868800 /* 33.8688 MHz */
47 // intended to be ~1 frame
48 #define IRQ_NEAR_BLOCKS 32
51 #if defined (USEMACOSX)
52 static char * libraryName = N_("Mac OS X Sound");
53 #elif defined (USEALSA)
54 static char * libraryName = N_("ALSA Sound");
55 #elif defined (USEOSS)
56 static char * libraryName = N_("OSS Sound");
57 #elif defined (USESDL)
58 static char * libraryName = N_("SDL Sound");
59 #elif defined (USEPULSEAUDIO)
60 static char * libraryName = N_("PulseAudio Sound");
62 static char * libraryName = N_("NULL Sound");
65 static char * libraryInfo = N_("P.E.Op.S. Sound Driver V1.7\nCoded by Pete Bernert and the P.E.Op.S. team\n");
73 static int iFMod[NSSIZE];
74 static int RVB[NSSIZE * 2];
77 #define CDDA_BUFFER_SIZE (16384 * sizeof(uint32_t)) // must be power of 2
79 ////////////////////////////////////////////////////////////////////////
81 ////////////////////////////////////////////////////////////////////////
83 // dirty inline func includes
88 ////////////////////////////////////////////////////////////////////////
89 // helpers for simple interpolation
92 // easy interpolation on upsampling, no special filter, just "Pete's common sense" tm
94 // instead of having n equal sample values in a row like:
98 // we compare the current delta change with the next delta change.
100 // if curr_delta is positive,
102 // - and next delta is smaller (or changing direction):
106 // - and next delta significant (at least twice) bigger:
110 // - and next delta is nearly same:
115 // if curr_delta is negative,
117 // - and next delta is smaller (or changing direction):
121 // - and next delta significant (at least twice) bigger:
125 // - and next delta is nearly same:
130 static void InterpolateUp(sample_buf *sb, int sinc)
133 if (sb->sinc_old != 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(sample_buf *sb, int sinc)
188 if(sinc>=0x20000L) // we would skip at least one val?
190 SB[29]+=(SB[30]-SB[29])/2; // add easy weight
191 if(sinc>=0x30000L) // we would skip even more vals?
192 SB[29]+=(SB[31]-SB[30])/2; // add additional next weight
196 ////////////////////////////////////////////////////////////////////////
201 static void do_irq(void)
203 //if(!(spu.spuStat & STAT_IRQ))
205 spu.spuStat |= STAT_IRQ; // asserted status?
206 if(spu.irqCallback) spu.irqCallback(0);
210 static int check_irq(int ch, unsigned char *pos)
212 if((spu.spuCtrl & (CTRL_ON|CTRL_IRQ)) == (CTRL_ON|CTRL_IRQ) && pos == spu.pSpuIrq)
214 //printf("ch%d irq %04zx\n", ch, pos - spu.spuMemC);
221 void check_irq_io(unsigned int addr)
223 unsigned int irq_addr = regAreaGet(H_SPUirqAddr) << 3;
225 if((spu.spuCtrl & (CTRL_ON|CTRL_IRQ)) == (CTRL_ON|CTRL_IRQ) && addr == irq_addr)
227 //printf("io irq %04x\n", irq_addr);
232 ////////////////////////////////////////////////////////////////////////
233 // START SOUND... called by main thread to setup a new sound on a channel
234 ////////////////////////////////////////////////////////////////////////
236 static void ResetInterpolation(sample_buf *sb)
238 memset(&sb->interp, 0, sizeof(sb->interp));
242 static void StartSoundSB(sample_buf *sb)
244 sb->SB[26] = 0; // init mixing vars
246 ResetInterpolation(sb);
249 static void StartSoundMain(int ch)
251 SPUCHAN *s_chan = &spu.s_chan[ch];
256 s_chan->prevflags = 2;
259 s_chan->bStarting = 1;
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]);
274 ////////////////////////////////////////////////////////////////////////
275 // ALL KIND OF HELPERS
276 ////////////////////////////////////////////////////////////////////////
278 INLINE int FModChangeFrequency(int pitch, int ns, int *fmod_buf)
280 pitch = (signed short)pitch;
281 pitch = ((32768 + fmod_buf[ns]) * pitch) >> 15;
291 INLINE void StoreInterpolationGaussCubic(sample_buf *sb, int fa)
293 int gpos = sb->interp.gauss.pos & 3;
294 sb->interp.gauss.val[gpos++] = fa;
295 sb->interp.gauss.pos = gpos & 3;
298 #define gval(x) (int)sb->interp.gauss.val[(gpos + x) & 3]
300 INLINE int GetInterpolationCubic(const sample_buf *sb, int spos)
302 int gpos = sb->interp.gauss.pos;
303 int xd = (spos >> 1) + 1;
306 fa = gval(3) - 3*gval(2) + 3*gval(1) - gval(0);
307 fa *= (xd - (2<<15)) / 6;
309 fa += gval(2) - gval(1) - gval(1) + gval(0);
310 fa *= (xd - (1<<15)) >> 1;
312 fa += gval(1) - gval(0);
319 INLINE int GetInterpolationGauss(const sample_buf *sb, int spos)
321 int gpos = sb->interp.gauss.pos;
322 int vl = (spos >> 6) & ~3;
324 vr = (gauss[vl+0] * gval(0)) >> 15;
325 vr += (gauss[vl+1] * gval(1)) >> 15;
326 vr += (gauss[vl+2] * gval(2)) >> 15;
327 vr += (gauss[vl+3] * gval(3)) >> 15;
331 static void decode_block_data(int *dest, const unsigned char *src, int predict_nr, int shift_factor)
333 static const int f[16][2] = {
341 int fa, s_1, s_2, d, s;
346 for (nSample = 0; nSample < 28; src++)
349 s = (int)(signed short)((d & 0x0f) << 12);
351 fa = s >> shift_factor;
352 fa += ((s_1 * f[predict_nr][0])>>6) + ((s_2 * f[predict_nr][1])>>6);
356 dest[nSample++] = fa;
358 s = (int)(signed short)((d & 0xf0) << 8);
359 fa = s >> shift_factor;
360 fa += ((s_1 * f[predict_nr][0])>>6) + ((s_2 * f[predict_nr][1])>>6);
364 dest[nSample++] = fa;
368 static int decode_block(void *unused, int ch, int *SB)
370 SPUCHAN *s_chan = &spu.s_chan[ch];
371 unsigned char *start;
372 int predict_nr, shift_factor, flags;
375 start = s_chan->pCurr; // set up the current pos
376 if (start - spu.spuMemC < 0x1000) { // ?
377 //log_unhandled("ch%02d plays decode bufs @%05lx\n",
378 // ch, (long)(start - spu.spuMemC));
382 if (s_chan->prevflags & 1) // 1: stop/loop
384 if (!(s_chan->prevflags & 2))
387 start = s_chan->pLoop;
390 check_irq(ch, start);
392 predict_nr = start[0];
393 shift_factor = predict_nr & 0xf;
396 decode_block_data(SB, start + 2, predict_nr, shift_factor);
399 if (flags & 4 && !s_chan->bIgnoreLoop)
400 s_chan->pLoop = start; // loop adress
404 s_chan->pCurr = start; // store values for next cycle
405 s_chan->prevflags = flags;
406 s_chan->bStarting = 0;
411 // do block, but ignore sample data
412 static int skip_block(int ch)
414 SPUCHAN *s_chan = &spu.s_chan[ch];
415 unsigned char *start = s_chan->pCurr;
419 if (s_chan->prevflags & 1) {
420 if (!(s_chan->prevflags & 2))
423 start = s_chan->pLoop;
426 check_irq(ch, start);
429 if (flags & 4 && !s_chan->bIgnoreLoop)
430 s_chan->pLoop = start;
434 s_chan->pCurr = start;
435 s_chan->prevflags = flags;
436 s_chan->bStarting = 0;
441 // if irq is going to trigger sooner than in upd_samples, set upd_samples
442 static void scan_for_irq(int ch, unsigned int *upd_samples)
444 SPUCHAN *s_chan = &spu.s_chan[ch];
445 int pos, sinc, sinc_inv, end;
446 unsigned char *block;
449 block = s_chan->pCurr;
452 end = pos + *upd_samples * sinc;
453 if (s_chan->prevflags & 1) // 1: stop/loop
454 block = s_chan->pLoop;
456 pos += (28 - s_chan->iSBPos) << 16;
459 if (block == spu.pSpuIrq)
463 if (flags & 1) { // 1: stop/loop
464 block = s_chan->pLoop;
471 sinc_inv = s_chan->sinc_inv;
473 sinc_inv = s_chan->sinc_inv = (0x80000000u / (uint32_t)sinc) << 1;
476 *upd_samples = (((uint64_t)pos * sinc_inv) >> 32) + 1;
477 //xprintf("ch%02d: irq sched: %3d %03d\n",
478 // ch, *upd_samples, *upd_samples * 60 * 263 / 44100);
482 #define make_do_samples(name, fmod_code, interp_start, interp_store, interp_get, interp_end) \
483 static noinline int name(int *dst, \
484 int (*decode_f)(void *context, int ch, int *SB), void *ctx, \
485 int ch, int ns_to, sample_buf *sb, int sinc, int *spos, int *sbpos) \
491 for (ns = 0; ns < ns_to; ns++) \
496 while (*spos >= 0x10000) \
498 fa = sb->SB[(*sbpos)++]; \
502 d = decode_f(ctx, ch, sb->SB); \
519 // helpers for simple linear interpolation: delay real val for two slots,
520 // and calc the two deltas, for a 'look at the future behaviour'
521 #define simple_interp_store \
523 sb->SB[29] = sb->SB[30]; \
524 sb->SB[30] = sb->SB[31]; \
528 #define simple_interp_get \
529 if(sinc<0x10000) /* -> upsampling? */ \
530 InterpolateUp(sb, sinc); /* --> interpolate up */ \
531 else InterpolateDown(sb, sinc); /* --> else down */ \
534 make_do_samples(do_samples_nointerp, , fa = sb->SB[29],
535 , dst[ns] = fa, sb->SB[29] = fa)
536 make_do_samples(do_samples_simple, , ,
537 simple_interp_store, simple_interp_get, )
538 make_do_samples(do_samples_gauss, , ,
539 StoreInterpolationGaussCubic(sb, fa),
540 dst[ns] = GetInterpolationGauss(sb, *spos), )
541 make_do_samples(do_samples_cubic, , ,
542 StoreInterpolationGaussCubic(sb, fa),
543 dst[ns] = GetInterpolationCubic(sb, *spos), )
544 make_do_samples(do_samples_fmod,
545 sinc = FModChangeFrequency(spu.s_chan[ch].iRawPitch, ns, iFMod), ,
546 StoreInterpolationGaussCubic(sb, fa),
547 dst[ns] = GetInterpolationGauss(sb, *spos), )
549 INLINE int do_samples_adpcm(int *dst,
550 int (*decode_f)(void *context, int ch, int *SB), void *ctx,
551 int ch, int ns_to, int fmod, sample_buf *sb, int sinc, int *spos, int *sbpos)
553 int interp = spu.interpolation;
555 return do_samples_fmod(dst, decode_f, ctx, ch, ns_to, sb, sinc, spos, sbpos);
560 return do_samples_nointerp(dst, decode_f, ctx, ch, ns_to, sb, sinc, spos, sbpos);
562 return do_samples_simple (dst, decode_f, ctx, ch, ns_to, sb, sinc, spos, sbpos);
564 return do_samples_gauss (dst, decode_f, ctx, ch, ns_to, sb, sinc, spos, sbpos);
566 return do_samples_cubic (dst, decode_f, ctx, ch, ns_to, sb, sinc, spos, sbpos);
570 static int do_samples_skip(int ch, int ns_to)
572 SPUCHAN *s_chan = &spu.s_chan[ch];
573 int spos = s_chan->spos;
574 int sinc = s_chan->sinc;
575 int ret = ns_to, ns, d;
577 spos += s_chan->iSBPos << 16;
579 for (ns = 0; ns < ns_to; ns++)
582 while (spos >= 28*0x10000)
591 s_chan->iSBPos = spos >> 16;
592 s_chan->spos = spos & 0xffff;
597 static int do_samples_skip_fmod(int ch, int ns_to, int *fmod_buf)
599 SPUCHAN *s_chan = &spu.s_chan[ch];
600 int spos = s_chan->spos;
601 int ret = ns_to, ns, d;
603 spos += s_chan->iSBPos << 16;
605 for (ns = 0; ns < ns_to; ns++)
607 spos += FModChangeFrequency(s_chan->iRawPitch, ns, fmod_buf);
608 while (spos >= 28*0x10000)
617 s_chan->iSBPos = spos >> 16;
618 s_chan->spos = spos & 0xffff;
623 static void do_lsfr_samples(int *dst, int ns_to, int ctrl,
624 unsigned int *dwNoiseCount, unsigned int *dwNoiseVal)
626 unsigned int counter = *dwNoiseCount;
627 unsigned int val = *dwNoiseVal;
628 unsigned int level, shift, bit;
631 // modified from DrHell/shalma, no fraction
632 level = (ctrl >> 10) & 0x0f;
633 level = 0x8000 >> level;
635 for (ns = 0; ns < ns_to; ns++)
638 if (counter >= level)
641 shift = (val >> 10) & 0x1f;
642 bit = (0x69696969 >> shift) & 1;
643 bit ^= (val >> 15) & 1;
644 val = (val << 1) | bit;
647 dst[ns] = (signed short)val;
650 *dwNoiseCount = counter;
654 static int do_samples_noise(int *dst, int ch, int ns_to)
658 ret = do_samples_skip(ch, ns_to);
660 do_lsfr_samples(dst, ns_to, spu.spuCtrl, &spu.dwNoiseCount, &spu.dwNoiseVal);
666 // asm code; lv and rv must be 0-3fff
667 extern void mix_chan(int *SSumLR, int count, int lv, int rv);
668 extern void mix_chan_rvb(int *SSumLR, int count, int lv, int rv, int *rvb);
670 static void mix_chan(int *SSumLR, int count, int lv, int rv)
672 const int *src = ChanBuf;
679 l = (sval * lv) >> 14;
680 r = (sval * rv) >> 14;
686 static void mix_chan_rvb(int *SSumLR, int count, int lv, int rv, int *rvb)
688 const int *src = ChanBuf;
697 l = (sval * lv) >> 14;
698 r = (sval * rv) >> 14;
707 // 0x0800-0x0bff Voice 1
708 // 0x0c00-0x0fff Voice 3
709 static noinline void do_decode_bufs(unsigned short *mem, int which,
710 int count, int decode_pos)
712 unsigned short *dst = &mem[0x800/2 + which*0x400/2];
713 const int *src = ChanBuf;
714 int cursor = decode_pos;
719 dst[cursor] = *src++;
723 // decode_pos is updated and irqs are checked later, after voice loop
726 static void do_silent_chans(int ns_to, int silentch)
732 mask = silentch & 0xffffff;
733 for (ch = 0; mask != 0; ch++, mask >>= 1)
735 if (!(mask & 1)) continue;
736 if (spu.dwChannelDead & (1<<ch)) continue;
738 s_chan = &spu.s_chan[ch];
739 if (s_chan->pCurr > spu.pSpuIrq && s_chan->pLoop > spu.pSpuIrq)
742 s_chan->spos += s_chan->iSBPos << 16;
745 s_chan->spos += s_chan->sinc * ns_to;
746 while (s_chan->spos >= 28 * 0x10000)
748 unsigned char *start = s_chan->pCurr;
751 if (start == s_chan->pCurr || start - spu.spuMemC < 0x1000)
753 // looping on self or stopped(?)
754 spu.dwChannelDead |= 1<<ch;
759 s_chan->spos -= 28 * 0x10000;
764 static void do_channels(int ns_to)
770 if (unlikely(spu.interpolation != spu_config.iUseInterpolation))
772 spu.interpolation = spu_config.iUseInterpolation;
773 mask = spu.dwChannelsAudible & 0xffffff;
774 for (ch = 0; mask != 0; ch++, mask >>= 1)
776 ResetInterpolation(&spu.sb[ch]);
779 do_rvb = spu.rvb->StartAddr && spu_config.iUseReverb;
781 memset(RVB, 0, ns_to * sizeof(RVB[0]) * 2);
783 mask = spu.dwNewChannel & 0xffffff;
784 for (ch = 0; mask != 0; ch++, mask >>= 1) {
789 mask = spu.dwChannelsAudible & 0xffffff;
790 for (ch = 0; mask != 0; ch++, mask >>= 1) // loop em all...
792 if (!(mask & 1)) continue; // channel not playing? next
794 s_chan = &spu.s_chan[ch];
796 d = do_samples_noise(ChanBuf, ch, ns_to);
798 d = do_samples_adpcm(ChanBuf, decode_block, NULL, ch, ns_to, s_chan->bFMod,
799 &spu.sb[ch], s_chan->sinc, &s_chan->spos, &s_chan->iSBPos);
801 if (!s_chan->bStarting) {
802 d = MixADSR(ChanBuf, &s_chan->ADSRX, d);
804 spu.dwChannelsAudible &= ~(1 << ch);
805 s_chan->ADSRX.State = ADSR_RELEASE;
806 s_chan->ADSRX.EnvelopeVol = 0;
807 memset(&ChanBuf[d], 0, (ns_to - d) * sizeof(ChanBuf[0]));
811 if (ch == 1 || ch == 3)
813 do_decode_bufs(spu.spuMem, ch/2, ns_to, spu.decode_pos);
814 spu.decode_dirty_ch |= 1 << ch;
817 if (s_chan->bFMod == 2) // fmod freq channel
818 memcpy(iFMod, &ChanBuf, ns_to * sizeof(iFMod[0]));
819 if (!(spu.spuCtrl & CTRL_MUTE))
821 else if (s_chan->bRVBActive && do_rvb)
822 mix_chan_rvb(spu.SSumLR, ns_to, s_chan->iLeftVolume, s_chan->iRightVolume, RVB);
824 mix_chan(spu.SSumLR, ns_to, s_chan->iLeftVolume, s_chan->iRightVolume);
827 MixXA(spu.SSumLR, RVB, ns_to, spu.decode_pos);
829 if (spu.rvb->StartAddr) {
831 REVERBDo(spu.SSumLR, RVB, ns_to, spu.rvb->CurrAddr);
833 spu.rvb->CurrAddr += ns_to / 2;
834 while (spu.rvb->CurrAddr >= 0x40000)
835 spu.rvb->CurrAddr -= 0x40000 - spu.rvb->StartAddr;
839 static void do_samples_finish(int *SSumLR, int ns_to,
840 int silentch, int decode_pos);
842 // optional worker thread handling
844 #if P_HAVE_PTHREAD || defined(WANT_THREAD_CODE)
846 // worker thread state
847 static struct spu_worker {
850 unsigned int exit_thread;
851 unsigned int i_ready;
852 unsigned int i_reaped;
853 unsigned int last_boot_cnt; // dsp
854 unsigned int ram_dirty;
856 // aligning for C64X_DSP
857 unsigned int _pad0[128/4];
862 unsigned int active; // dsp
863 unsigned int boot_cnt;
865 unsigned int _pad1[128/4];
872 unsigned int channels_new;
873 unsigned int channels_on;
874 unsigned int channels_silent;
883 unsigned short ns_to;
884 unsigned short bNoise:1;
885 unsigned short bFMod:2;
886 unsigned short bRVBActive:1;
887 unsigned short bStarting:1;
890 int SSumLR[NSSIZE * 2];
894 #define WORK_MAXCNT (sizeof(worker->i) / sizeof(worker->i[0]))
895 #define WORK_I_MASK (WORK_MAXCNT - 1)
897 static void thread_work_start(void);
898 static void thread_work_wait_sync(struct work_item *work, int force);
899 static void thread_sync_caches(void);
900 static int thread_get_i_done(void);
902 static int decode_block_work(void *context, int ch, int *SB)
904 const unsigned char *ram = spu.spuMemC;
905 int predict_nr, shift_factor, flags;
906 struct work_item *work = context;
907 int start = work->ch[ch].start;
908 int loop = work->ch[ch].loop;
910 predict_nr = ram[start];
911 shift_factor = predict_nr & 0xf;
914 decode_block_data(SB, ram + start + 2, predict_nr, shift_factor);
916 flags = ram[start + 1];
918 loop = start; // loop adress
922 if (flags & 1) // 1: stop/loop
925 work->ch[ch].start = start & 0x7ffff;
926 work->ch[ch].loop = loop;
931 static void queue_channel_work(int ns_to, unsigned int silentch)
934 struct work_item *work;
939 work = &worker->i[worker->i_ready & WORK_I_MASK];
941 work->ctrl = spu.spuCtrl;
942 work->decode_pos = spu.decode_pos;
943 work->channels_silent = silentch;
945 mask = work->channels_new = spu.dwNewChannel & 0xffffff;
946 for (ch = 0; mask != 0; ch++, mask >>= 1) {
951 mask = work->channels_on = spu.dwChannelsAudible & 0xffffff;
952 spu.decode_dirty_ch |= mask & 0x0a;
954 for (ch = 0; mask != 0; ch++, mask >>= 1)
956 if (!(mask & 1)) continue;
958 s_chan = &spu.s_chan[ch];
959 work->ch[ch].spos = s_chan->spos;
960 work->ch[ch].sbpos = s_chan->iSBPos;
961 work->ch[ch].sinc = s_chan->sinc;
962 work->ch[ch].adsr = s_chan->ADSRX;
963 work->ch[ch].vol_l = s_chan->iLeftVolume;
964 work->ch[ch].vol_r = s_chan->iRightVolume;
965 work->ch[ch].start = s_chan->pCurr - spu.spuMemC;
966 work->ch[ch].loop = s_chan->pLoop - spu.spuMemC;
967 work->ch[ch].bNoise = s_chan->bNoise;
968 work->ch[ch].bFMod = s_chan->bFMod;
969 work->ch[ch].bRVBActive = s_chan->bRVBActive;
970 work->ch[ch].bStarting = s_chan->bStarting;
971 if (s_chan->prevflags & 1)
972 work->ch[ch].start = work->ch[ch].loop;
974 if (unlikely(s_chan->bFMod == 2))
976 // sucks, have to do double work
977 assert(!s_chan->bNoise);
978 d = do_samples_gauss(tmpFMod, decode_block, NULL, ch, ns_to,
979 &spu.sb[ch], s_chan->sinc, &s_chan->spos, &s_chan->iSBPos);
980 if (!s_chan->bStarting) {
981 d = MixADSR(tmpFMod, &s_chan->ADSRX, d);
983 spu.dwChannelsAudible &= ~(1 << ch);
984 s_chan->ADSRX.State = ADSR_RELEASE;
985 s_chan->ADSRX.EnvelopeVol = 0;
988 memset(&tmpFMod[d], 0, (ns_to - d) * sizeof(tmpFMod[d]));
989 work->ch[ch].ns_to = d;
992 if (unlikely(s_chan->bFMod))
993 d = do_samples_skip_fmod(ch, ns_to, tmpFMod);
995 d = do_samples_skip(ch, ns_to);
996 work->ch[ch].ns_to = d;
998 if (!s_chan->bStarting) {
999 // note: d is not accurate on skip
1000 d = SkipADSR(&s_chan->ADSRX, d);
1002 spu.dwChannelsAudible &= ~(1 << ch);
1003 s_chan->ADSRX.State = ADSR_RELEASE;
1004 s_chan->ADSRX.EnvelopeVol = 0;
1010 if (spu.rvb->StartAddr) {
1011 if (spu_config.iUseReverb)
1012 work->rvb_addr = spu.rvb->CurrAddr;
1014 spu.rvb->CurrAddr += ns_to / 2;
1015 while (spu.rvb->CurrAddr >= 0x40000)
1016 spu.rvb->CurrAddr -= 0x40000 - spu.rvb->StartAddr;
1020 thread_work_start();
1023 static void do_channel_work(struct work_item *work)
1029 ns_to = work->ns_to;
1031 if (unlikely(spu.interpolation != spu_config.iUseInterpolation))
1033 spu.interpolation = spu_config.iUseInterpolation;
1034 mask = work->channels_on;
1035 for (ch = 0; mask != 0; ch++, mask >>= 1)
1037 ResetInterpolation(&spu.sb_thread[ch]);
1041 memset(RVB, 0, ns_to * sizeof(RVB[0]) * 2);
1043 mask = work->channels_new;
1044 for (ch = 0; mask != 0; ch++, mask >>= 1) {
1046 StartSoundSB(&spu.sb_thread[ch]);
1049 mask = work->channels_on;
1050 for (ch = 0; mask != 0; ch++, mask >>= 1)
1052 if (!(mask & 1)) continue;
1054 d = work->ch[ch].ns_to;
1055 spos = work->ch[ch].spos;
1056 sbpos = work->ch[ch].sbpos;
1058 if (work->ch[ch].bNoise)
1059 do_lsfr_samples(ChanBuf, d, work->ctrl, &spu.dwNoiseCount, &spu.dwNoiseVal);
1061 do_samples_adpcm(ChanBuf, decode_block_work, work, ch, d, work->ch[ch].bFMod,
1062 &spu.sb_thread[ch], work->ch[ch].sinc, &spos, &sbpos);
1064 d = MixADSR(ChanBuf, &work->ch[ch].adsr, d);
1066 work->ch[ch].adsr.EnvelopeVol = 0;
1067 memset(&ChanBuf[d], 0, (ns_to - d) * sizeof(ChanBuf[0]));
1070 if (ch == 1 || ch == 3)
1071 do_decode_bufs(spu.spuMem, ch/2, ns_to, work->decode_pos);
1073 if (work->ch[ch].bFMod == 2) // fmod freq channel
1074 memcpy(iFMod, &ChanBuf, ns_to * sizeof(iFMod[0]));
1075 if (work->ch[ch].bRVBActive && work->rvb_addr)
1076 mix_chan_rvb(work->SSumLR, ns_to,
1077 work->ch[ch].vol_l, work->ch[ch].vol_r, RVB);
1079 mix_chan(work->SSumLR, ns_to, work->ch[ch].vol_l, work->ch[ch].vol_r);
1083 REVERBDo(work->SSumLR, RVB, ns_to, work->rvb_addr);
1086 static void sync_worker_thread(int force)
1088 struct work_item *work;
1089 int done, used_space;
1091 // rvb offsets will change, thread may be using them
1092 force |= spu.rvb->dirty && spu.rvb->StartAddr;
1094 done = thread_get_i_done() - worker->i_reaped;
1095 used_space = worker->i_ready - worker->i_reaped;
1097 //printf("done: %d use: %d dsp: %u/%u\n", done, used_space,
1098 // worker->boot_cnt, worker->i_done);
1100 while ((force && used_space > 0) || used_space >= WORK_MAXCNT || done > 0) {
1101 work = &worker->i[worker->i_reaped & WORK_I_MASK];
1102 thread_work_wait_sync(work, force);
1104 MixXA(work->SSumLR, RVB, work->ns_to, work->decode_pos);
1105 do_samples_finish(work->SSumLR, work->ns_to,
1106 work->channels_silent, work->decode_pos);
1109 done = thread_get_i_done() - worker->i_reaped;
1110 used_space = worker->i_ready - worker->i_reaped;
1113 thread_sync_caches();
1118 static void queue_channel_work(int ns_to, int silentch) {}
1119 static void sync_worker_thread(int force) {}
1121 static const void * const worker = NULL;
1123 #endif // P_HAVE_PTHREAD || defined(WANT_THREAD_CODE)
1125 ////////////////////////////////////////////////////////////////////////
1126 // MAIN SPU FUNCTION
1127 // here is the main job handler...
1128 ////////////////////////////////////////////////////////////////////////
1130 void do_samples(unsigned int cycles_to, int do_direct)
1132 unsigned int silentch;
1136 cycle_diff = cycles_to - spu.cycles_played;
1137 if (cycle_diff < -2*1048576 || cycle_diff > 2*1048576)
1139 //xprintf("desync %u %d\n", cycles_to, cycle_diff);
1140 spu.cycles_played = cycles_to;
1144 silentch = ~(spu.dwChannelsAudible | spu.dwNewChannel) & 0xffffff;
1146 do_direct |= (silentch == 0xffffff);
1148 sync_worker_thread(do_direct);
1150 if (cycle_diff < 2 * 768)
1153 ns_to = (cycle_diff / 768 + 1) & ~1;
1154 if (ns_to > NSSIZE) {
1155 // should never happen
1156 //xprintf("ns_to oflow %d %d\n", ns_to, NSSIZE);
1160 //////////////////////////////////////////////////////
1161 // special irq handling in the decode buffers (0x0000-0x1000)
1163 // the decode buffers are located in spu memory in the following way:
1164 // 0x0000-0x03ff CD audio left
1165 // 0x0400-0x07ff CD audio right
1166 // 0x0800-0x0bff Voice 1
1167 // 0x0c00-0x0fff Voice 3
1168 // and decoded data is 16 bit for one sample
1170 // even if voices 1/3 are off or no cd audio is playing, the internal
1171 // play positions will move on and wrap after 0x400 bytes.
1172 // Therefore: we just need a pointer from spumem+0 to spumem+3ff, and
1173 // increase this pointer on each sample by 2 bytes. If this pointer
1174 // (or 0x400 offsets of this pointer) hits the spuirq address, we generate
1177 if (unlikely((spu.spuCtrl & CTRL_IRQ)
1178 && spu.pSpuIrq < spu.spuMemC+0x1000))
1180 int irq_pos = (spu.pSpuIrq - spu.spuMemC) / 2 & 0x1ff;
1181 int left = (irq_pos - spu.decode_pos) & 0x1ff;
1182 if (0 < left && left <= ns_to)
1184 //xprintf("decoder irq %x\n", spu.decode_pos);
1188 if (!spu.cycles_dma_end || (int)(spu.cycles_dma_end - cycles_to) < 0) {
1189 spu.cycles_dma_end = 0;
1190 check_irq_io(spu.spuAddr);
1193 if (unlikely(spu.rvb->dirty))
1196 if (do_direct || worker == NULL || !spu_config.iUseThread) {
1198 do_samples_finish(spu.SSumLR, ns_to, silentch, spu.decode_pos);
1201 queue_channel_work(ns_to, silentch);
1202 //sync_worker_thread(1); // uncomment for debug
1205 // advance "stopped" channels that can cause irqs
1206 // (all chans are always playing on the real thing..)
1207 if (spu.spuCtrl & CTRL_IRQ)
1208 do_silent_chans(ns_to, silentch);
1210 spu.cycles_played += ns_to * 768;
1211 spu.decode_pos = (spu.decode_pos + ns_to) & 0x1ff;
1213 static int ccount; static time_t ctime; ccount++;
1214 if (time(NULL) != ctime)
1215 { printf("%d\n", ccount); ccount = 0; ctime = time(NULL); }
1219 static void do_samples_finish(int *SSumLR, int ns_to,
1220 int silentch, int decode_pos)
1222 int vol_l = ((int)regAreaGet(H_SPUmvolL) << 17) >> 17;
1223 int vol_r = ((int)regAreaGet(H_SPUmvolR) << 17) >> 17;
1227 // must clear silent channel decode buffers
1228 if(unlikely(silentch & spu.decode_dirty_ch & (1<<1)))
1230 memset(&spu.spuMem[0x800/2], 0, 0x400);
1231 spu.decode_dirty_ch &= ~(1<<1);
1233 if(unlikely(silentch & spu.decode_dirty_ch & (1<<3)))
1235 memset(&spu.spuMem[0xc00/2], 0, 0x400);
1236 spu.decode_dirty_ch &= ~(1<<3);
1239 vol_l = vol_l * spu_config.iVolume >> 10;
1240 vol_r = vol_r * spu_config.iVolume >> 10;
1242 if (!(vol_l | vol_r))
1245 memset(spu.pS, 0, ns_to * 2 * sizeof(spu.pS[0]));
1246 memset(SSumLR, 0, ns_to * 2 * sizeof(SSumLR[0]));
1247 spu.pS += ns_to * 2;
1250 for (ns = 0; ns < ns_to * 2; )
1252 d = SSumLR[ns]; SSumLR[ns] = 0;
1253 d = d * vol_l >> 14;
1258 d = SSumLR[ns]; SSumLR[ns] = 0;
1259 d = d * vol_r >> 14;
1266 void schedule_next_irq(void)
1268 unsigned int upd_samples;
1271 if (spu.scheduleCallback == NULL)
1274 upd_samples = 44100 / 50;
1276 for (ch = 0; ch < MAXCHAN; ch++)
1278 if (spu.dwChannelDead & (1 << ch))
1280 if ((unsigned long)(spu.pSpuIrq - spu.s_chan[ch].pCurr) > IRQ_NEAR_BLOCKS * 16
1281 && (unsigned long)(spu.pSpuIrq - spu.s_chan[ch].pLoop) > IRQ_NEAR_BLOCKS * 16)
1283 if (spu.s_chan[ch].sinc == 0)
1286 scan_for_irq(ch, &upd_samples);
1289 if (unlikely(spu.pSpuIrq < spu.spuMemC + 0x1000))
1291 int irq_pos = (spu.pSpuIrq - spu.spuMemC) / 2 & 0x1ff;
1292 int left = (irq_pos - spu.decode_pos) & 0x1ff;
1293 if (0 < left && left < upd_samples) {
1294 //xprintf("decode: %3d (%3d/%3d)\n", left, spu.decode_pos, irq_pos);
1299 if (upd_samples < 44100 / 50)
1300 spu.scheduleCallback(upd_samples * 768);
1303 // SPU ASYNC... even newer epsxe func
1304 // 1 time every 'cycle' cycles... harhar
1306 // rearmed: called dynamically now
1308 void CALLBACK SPUasync(unsigned int cycle, unsigned int flags)
1310 do_samples(cycle, 0);
1312 if (spu.spuCtrl & CTRL_IRQ)
1313 schedule_next_irq();
1316 out_current->feed(spu.pSpuBuffer, (unsigned char *)spu.pS - spu.pSpuBuffer);
1317 spu.pS = (short *)spu.pSpuBuffer;
1319 if (spu_config.iTempo) {
1320 if (!out_current->busy())
1321 // cause more samples to be generated
1322 // (and break some games because of bad sync)
1323 spu.cycles_played -= 44100 / 60 / 2 * 768;
1328 // SPU UPDATE... new epsxe func
1329 // 1 time every 32 hsync lines
1330 // (312/32)x50 in pal
1331 // (262/32)x60 in ntsc
1333 // since epsxe 1.5.2 (linux) uses SPUupdate, not SPUasync, I will
1334 // leave that func in the linux port, until epsxe linux is using
1335 // the async function as well
1337 void CALLBACK SPUupdate(void)
1343 void CALLBACK SPUplayADPCMchannel(xa_decode_t *xap, unsigned int cycle, int unused)
1346 if(!xap->freq) return; // no xa freq ? bye
1348 if (spu.XAPlay == spu.XAFeed)
1349 do_samples(cycle, 1); // catch up to prevent source underflows later
1351 FeedXA(xap); // call main XA feeder
1352 spu.xapGlobal = xap; // store info for save states
1356 int CALLBACK SPUplayCDDAchannel(short *pcm, int nbytes, unsigned int cycle, int unused)
1358 if (!pcm) return -1;
1359 if (nbytes<=0) return -1;
1361 if (spu.CDDAPlay == spu.CDDAFeed)
1362 do_samples(cycle, 1); // catch up to prevent source underflows later
1364 FeedCDDA((unsigned char *)pcm, nbytes);
1368 // to be called after state load
1369 void ClearWorkingState(void)
1371 memset(iFMod, 0, sizeof(iFMod));
1372 spu.pS=(short *)spu.pSpuBuffer; // setup soundbuffer pointer
1375 // SETUPSTREAMS: init most of the spu buffers
1376 static void SetupStreams(void)
1378 spu.pSpuBuffer = (unsigned char *)malloc(32768); // alloc mixing buffer
1379 spu.SSumLR = calloc(NSSIZE * 2, sizeof(spu.SSumLR[0]));
1381 spu.XAStart = malloc(44100 * sizeof(uint32_t)); // alloc xa buffer
1382 spu.XAEnd = spu.XAStart + 44100;
1383 spu.XAPlay = spu.XAStart;
1384 spu.XAFeed = spu.XAStart;
1386 spu.CDDAStart = malloc(CDDA_BUFFER_SIZE); // alloc cdda buffer
1387 spu.CDDAEnd = spu.CDDAStart + CDDA_BUFFER_SIZE / sizeof(uint32_t);
1388 spu.CDDAPlay = spu.CDDAStart;
1389 spu.CDDAFeed = spu.CDDAStart;
1391 ClearWorkingState();
1394 // REMOVESTREAMS: free most buffer
1395 static void RemoveStreams(void)
1397 free(spu.pSpuBuffer); // free mixing buffer
1398 spu.pSpuBuffer = NULL;
1401 free(spu.XAStart); // free XA buffer
1403 free(spu.CDDAStart); // free CDDA buffer
1404 spu.CDDAStart = NULL;
1407 #if defined(C64X_DSP)
1409 /* special code for TI C64x DSP */
1410 #include "spu_c64x.c"
1412 #elif P_HAVE_PTHREAD
1414 #include <pthread.h>
1415 #include <semaphore.h>
1424 /* generic pthread implementation */
1426 static void thread_work_start(void)
1428 sem_post(&t.sem_avail);
1431 static void thread_work_wait_sync(struct work_item *work, int force)
1433 sem_wait(&t.sem_done);
1436 static int thread_get_i_done(void)
1438 return worker->i_done;
1441 static void thread_sync_caches(void)
1445 static void *spu_worker_thread(void *unused)
1447 struct work_item *work;
1450 sem_wait(&t.sem_avail);
1451 if (worker->exit_thread)
1454 work = &worker->i[worker->i_done & WORK_I_MASK];
1455 do_channel_work(work);
1458 sem_post(&t.sem_done);
1464 static void init_spu_thread(void)
1468 if (sysconf(_SC_NPROCESSORS_ONLN) <= 1)
1471 worker = calloc(1, sizeof(*worker));
1474 ret = sem_init(&t.sem_avail, 0, 0);
1476 goto fail_sem_avail;
1477 ret = sem_init(&t.sem_done, 0, 0);
1481 ret = pthread_create(&t.thread, NULL, spu_worker_thread, NULL);
1485 spu_config.iThreadAvail = 1;
1489 sem_destroy(&t.sem_done);
1491 sem_destroy(&t.sem_avail);
1495 spu_config.iThreadAvail = 0;
1498 static void exit_spu_thread(void)
1502 worker->exit_thread = 1;
1503 sem_post(&t.sem_avail);
1504 pthread_join(t.thread, NULL);
1505 sem_destroy(&t.sem_done);
1506 sem_destroy(&t.sem_avail);
1511 #else // if !P_HAVE_PTHREAD
1513 static void init_spu_thread(void)
1517 static void exit_spu_thread(void)
1523 // SPUINIT: this func will be called first by the main emu
1524 long CALLBACK SPUinit(void)
1528 memset(&spu, 0, sizeof(spu));
1529 spu.spuMemC = calloc(1, 512 * 1024);
1532 spu.s_chan = calloc(MAXCHAN+1, sizeof(spu.s_chan[0])); // channel + 1 infos (1 is security for fmod handling)
1533 spu.rvb = calloc(1, sizeof(REVERBInfo));
1537 spu.pSpuIrq = spu.spuMemC;
1539 SetupStreams(); // prepare streaming
1541 if (spu_config.iVolume == 0)
1542 spu_config.iVolume = 768; // 1024 is 1.0
1546 for (i = 0; i < MAXCHAN; i++) // loop sound channels
1548 spu.s_chan[i].ADSRX.SustainLevel = 0xf; // -> init sustain
1549 spu.s_chan[i].ADSRX.SustainIncrease = 1;
1550 spu.s_chan[i].pLoop = spu.spuMemC;
1551 spu.s_chan[i].pCurr = spu.spuMemC;
1552 spu.s_chan[i].bIgnoreLoop = 0;
1555 spu.bSpuInit=1; // flag: we are inited
1560 // SPUOPEN: called by main emu after init
1561 long CALLBACK SPUopen(void)
1563 if (spu.bSPUIsOpen) return 0; // security for some stupid main emus
1565 SetupSound(); // setup sound (before init!)
1569 return PSE_SPU_ERR_SUCCESS;
1572 // SPUCLOSE: called before shutdown
1573 long CALLBACK SPUclose(void)
1575 if (!spu.bSPUIsOpen) return 0; // some security
1577 spu.bSPUIsOpen = 0; // no more open
1579 out_current->finish(); // no more sound handling
1584 // SPUSHUTDOWN: called by main emu on final exit
1585 long CALLBACK SPUshutdown(void)
1598 RemoveStreams(); // no more streaming
1605 // this functions will be called once,
1606 // passes a callback that should be called on SPU-IRQ/cdda volume change
1607 void CALLBACK SPUregisterCallback(void (CALLBACK *callback)(int))
1609 spu.irqCallback = callback;
1612 void CALLBACK SPUregisterCDDAVolume(void (CALLBACK *CDDAVcallback)(short, short))
1614 //spu.cddavCallback = CDDAVcallback;
1617 void CALLBACK SPUregisterScheduleCb(void (CALLBACK *callback)(unsigned int))
1619 spu.scheduleCallback = callback;
1622 // COMMON PLUGIN INFO FUNCS
1624 char * CALLBACK PSEgetLibName(void)
1626 return _(libraryName);
1629 unsigned long CALLBACK PSEgetLibType(void)
1634 unsigned long CALLBACK PSEgetLibVersion(void)
1636 return (1 << 16) | (6 << 8);
1639 char * SPUgetLibInfos(void)
1641 return _(libraryInfo);
1646 void spu_get_debug_info(int *chans_out, int *run_chans, int *fmod_chans_out, int *noise_chans_out)
1648 int ch = 0, fmod_chans = 0, noise_chans = 0, irq_chans = 0;
1650 if (spu.s_chan == NULL)
1653 for(;ch<MAXCHAN;ch++)
1655 if (!(spu.dwChannelsAudible & (1<<ch)))
1657 if (spu.s_chan[ch].bFMod == 2)
1658 fmod_chans |= 1 << ch;
1659 if (spu.s_chan[ch].bNoise)
1660 noise_chans |= 1 << ch;
1661 if((spu.spuCtrl&CTRL_IRQ) && spu.s_chan[ch].pCurr <= spu.pSpuIrq && spu.s_chan[ch].pLoop <= spu.pSpuIrq)
1662 irq_chans |= 1 << ch;
1665 *chans_out = spu.dwChannelsAudible;
1666 *run_chans = ~spu.dwChannelsAudible & ~spu.dwChannelDead & irq_chans;
1667 *fmod_chans_out = fmod_chans;
1668 *noise_chans_out = noise_chans;
1671 // vim:shiftwidth=1:expandtab