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"
33 #include "arm_features.h"
37 #define ssat32_to_16(v) \
38 asm("ssat %0,#16,%1" : "=r" (v) : "r" (v))
40 #define ssat32_to_16(v) do { \
41 if (v < -32768) v = -32768; \
42 else if (v > 32767) v = 32767; \
46 #define PSXCLK 33868800 /* 33.8688 MHz */
48 // intended to be ~1 frame
49 #define IRQ_NEAR_BLOCKS 32
52 #if defined (USEMACOSX)
53 static char * libraryName = N_("Mac OS X Sound");
54 #elif defined (USEALSA)
55 static char * libraryName = N_("ALSA Sound");
56 #elif defined (USEOSS)
57 static char * libraryName = N_("OSS Sound");
58 #elif defined (USESDL)
59 static char * libraryName = N_("SDL Sound");
60 #elif defined (USEPULSEAUDIO)
61 static char * libraryName = N_("PulseAudio Sound");
63 static char * libraryName = N_("NULL Sound");
66 static char * libraryInfo = N_("P.E.Op.S. Sound Driver V1.7\nCoded by Pete Bernert and the P.E.Op.S. team\n");
74 static int iFMod[NSSIZE];
75 static int RVB[NSSIZE * 2];
78 #define CDDA_BUFFER_SIZE (16384 * sizeof(uint32_t)) // must be power of 2
80 ////////////////////////////////////////////////////////////////////////
82 ////////////////////////////////////////////////////////////////////////
84 // dirty inline func includes
89 ////////////////////////////////////////////////////////////////////////
90 // helpers for simple interpolation
93 // easy interpolation on upsampling, no special filter, just "Pete's common sense" tm
95 // instead of having n equal sample values in a row like:
99 // we compare the current delta change with the next delta change.
101 // if curr_delta is positive,
103 // - and next delta is smaller (or changing direction):
107 // - and next delta significant (at least twice) bigger:
111 // - and next delta is nearly same:
116 // if curr_delta is negative,
118 // - and next delta is smaller (or changing direction):
122 // - and next delta significant (at least twice) bigger:
126 // - and next delta is nearly same:
131 static void InterpolateUp(sample_buf *sb, int sinc)
134 if (sb->sinc_old != sinc)
139 if(SB[32]==1) // flag == 1? calc step and set flag... and don't change the value in this pass
141 const int id1=SB[30]-SB[29]; // curr delta to next val
142 const int id2=SB[31]-SB[30]; // and next delta to next-next val :)
146 if(id1>0) // curr delta positive
149 {SB[28]=id1;SB[32]=2;}
152 SB[28]=(id1*sinc)>>16;
154 SB[28]=(id1*sinc)>>17;
156 else // curr delta negative
159 {SB[28]=id1;SB[32]=2;}
162 SB[28]=(id1*sinc)>>16;
164 SB[28]=(id1*sinc)>>17;
168 if(SB[32]==2) // flag 1: calc step and set flag... and don't change the value in this pass
172 SB[28]=(SB[28]*sinc)>>17;
174 // SB[29]=SB[30]-(SB[28]*((0x10000/sinc)-1));
178 else // no flags? add bigger val (if possible), calc smaller step, set flag1
183 // even easier interpolation on downsampling, also no special filter, again just "Pete's common sense" tm
186 static void InterpolateDown(sample_buf *sb, int sinc)
189 if(sinc>=0x20000L) // we would skip at least one val?
191 SB[29]+=(SB[30]-SB[29])/2; // add easy weight
192 if(sinc>=0x30000L) // we would skip even more vals?
193 SB[29]+=(SB[31]-SB[30])/2; // add additional next weight
197 ////////////////////////////////////////////////////////////////////////
202 static void do_irq(int cycles_after)
204 if (spu.spuStat & STAT_IRQ)
205 log_unhandled("spu: missed irq?\n");
208 spu.spuStat |= STAT_IRQ; // asserted status?
210 spu.irqCallback(cycles_after);
214 static int check_irq(int ch, unsigned char *pos)
216 if((spu.spuCtrl & (CTRL_ON|CTRL_IRQ)) == (CTRL_ON|CTRL_IRQ) && pos == spu.pSpuIrq)
218 //printf("ch%d irq %04zx\n", ch, pos - spu.spuMemC);
225 void check_irq_io(unsigned int addr)
227 unsigned int irq_addr = regAreaGet(H_SPUirqAddr) << 3;
229 if((spu.spuCtrl & (CTRL_ON|CTRL_IRQ)) == (CTRL_ON|CTRL_IRQ) && addr == irq_addr)
231 //printf("io irq %04x\n", irq_addr);
236 void do_irq_io(int cycles_after)
238 if ((spu.spuCtrl & (CTRL_ON|CTRL_IRQ)) == (CTRL_ON|CTRL_IRQ))
240 do_irq(cycles_after);
244 ////////////////////////////////////////////////////////////////////////
245 // START SOUND... called by main thread to setup a new sound on a channel
246 ////////////////////////////////////////////////////////////////////////
248 static void ResetInterpolation(sample_buf *sb)
250 memset(&sb->interp, 0, sizeof(sb->interp));
254 static void StartSoundSB(sample_buf *sb)
256 sb->SB[26] = 0; // init mixing vars
258 ResetInterpolation(sb);
261 static void StartSoundMain(int ch)
263 SPUCHAN *s_chan = &spu.s_chan[ch];
268 s_chan->prevflags = 2;
271 s_chan->bStarting = 1;
273 s_chan->pCurr = spu.spuMemC + ((regAreaGetCh(ch, 6) & ~1) << 3);
275 spu.dwNewChannel&=~(1<<ch); // clear new channel bit
276 spu.dwChannelDead&=~(1<<ch);
277 spu.dwChannelsAudible|=1<<ch;
280 static void StartSound(int ch)
283 StartSoundSB(&spu.sb[ch]);
286 ////////////////////////////////////////////////////////////////////////
287 // ALL KIND OF HELPERS
288 ////////////////////////////////////////////////////////////////////////
290 INLINE int FModChangeFrequency(int pitch, int ns, int *fmod_buf)
292 pitch = (signed short)pitch;
293 pitch = ((32768 + fmod_buf[ns]) * pitch) >> 15;
303 INLINE void StoreInterpolationGaussCubic(sample_buf *sb, int fa)
305 int gpos = sb->interp.gauss.pos & 3;
306 sb->interp.gauss.val[gpos++] = fa;
307 sb->interp.gauss.pos = gpos & 3;
310 #define gval(x) (int)sb->interp.gauss.val[(gpos + x) & 3]
312 INLINE int GetInterpolationCubic(const sample_buf *sb, int spos)
314 int gpos = sb->interp.gauss.pos;
315 int xd = (spos >> 1) + 1;
318 fa = gval(3) - 3*gval(2) + 3*gval(1) - gval(0);
319 fa *= (xd - (2<<15)) / 6;
321 fa += gval(2) - gval(1) - gval(1) + gval(0);
322 fa *= (xd - (1<<15)) >> 1;
324 fa += gval(1) - gval(0);
331 INLINE int GetInterpolationGauss(const sample_buf *sb, int spos)
333 int gpos = sb->interp.gauss.pos;
334 int vl = (spos >> 6) & ~3;
336 vr = (gauss[vl+0] * gval(0)) >> 15;
337 vr += (gauss[vl+1] * gval(1)) >> 15;
338 vr += (gauss[vl+2] * gval(2)) >> 15;
339 vr += (gauss[vl+3] * gval(3)) >> 15;
343 static void decode_block_data(int *dest, const unsigned char *src, int predict_nr, int shift_factor)
345 static const int f[16][2] = {
353 int fa, s_1, s_2, d, s;
358 for (nSample = 0; nSample < 28; src++)
361 s = (int)(signed short)((d & 0x0f) << 12);
363 fa = s >> shift_factor;
364 fa += ((s_1 * f[predict_nr][0])>>6) + ((s_2 * f[predict_nr][1])>>6);
368 dest[nSample++] = fa;
370 s = (int)(signed short)((d & 0xf0) << 8);
371 fa = s >> shift_factor;
372 fa += ((s_1 * f[predict_nr][0])>>6) + ((s_2 * f[predict_nr][1])>>6);
376 dest[nSample++] = fa;
380 static int decode_block(void *unused, int ch, int *SB)
382 SPUCHAN *s_chan = &spu.s_chan[ch];
383 unsigned char *start;
384 int predict_nr, shift_factor, flags;
387 start = s_chan->pCurr; // set up the current pos
388 if (start - spu.spuMemC < 0x1000) { // ?
389 //log_unhandled("ch%02d plays decode bufs @%05lx\n",
390 // ch, (long)(start - spu.spuMemC));
394 if (s_chan->prevflags & 1) // 1: stop/loop
396 if (!(s_chan->prevflags & 2))
399 start = s_chan->pLoop;
402 check_irq(ch, start);
404 predict_nr = start[0];
405 shift_factor = predict_nr & 0xf;
408 decode_block_data(SB, start + 2, predict_nr, shift_factor);
411 if (flags & 4 && !s_chan->bIgnoreLoop)
412 s_chan->pLoop = start; // loop adress
416 s_chan->pCurr = start; // store values for next cycle
417 s_chan->prevflags = flags;
418 s_chan->bStarting = 0;
423 // do block, but ignore sample data
424 static int skip_block(int ch)
426 SPUCHAN *s_chan = &spu.s_chan[ch];
427 unsigned char *start = s_chan->pCurr;
431 if (s_chan->prevflags & 1) {
432 if (!(s_chan->prevflags & 2))
435 start = s_chan->pLoop;
438 check_irq(ch, start);
441 if (flags & 4 && !s_chan->bIgnoreLoop)
442 s_chan->pLoop = start;
446 s_chan->pCurr = start;
447 s_chan->prevflags = flags;
448 s_chan->bStarting = 0;
453 // if irq is going to trigger sooner than in upd_samples, set upd_samples
454 static void scan_for_irq(int ch, unsigned int *upd_samples)
456 SPUCHAN *s_chan = &spu.s_chan[ch];
457 int pos, sinc, sinc_inv, end;
458 unsigned char *block;
461 block = s_chan->pCurr;
464 end = pos + *upd_samples * sinc;
465 if (s_chan->prevflags & 1) // 1: stop/loop
466 block = s_chan->pLoop;
468 pos += (28 - s_chan->iSBPos) << 16;
471 if (block == spu.pSpuIrq)
475 if (flags & 1) { // 1: stop/loop
476 block = s_chan->pLoop;
483 sinc_inv = s_chan->sinc_inv;
485 sinc_inv = s_chan->sinc_inv = (0x80000000u / (uint32_t)sinc) << 1;
488 *upd_samples = (((uint64_t)pos * sinc_inv) >> 32) + 1;
489 //xprintf("ch%02d: irq sched: %3d %03d\n",
490 // ch, *upd_samples, *upd_samples * 60 * 263 / 44100);
494 #define make_do_samples(name, fmod_code, interp_start, interp_store, interp_get, interp_end) \
495 static noinline int name(int *dst, \
496 int (*decode_f)(void *context, int ch, int *SB), void *ctx, \
497 int ch, int ns_to, sample_buf *sb, int sinc, int *spos, int *sbpos) \
503 for (ns = 0; ns < ns_to; ns++) \
508 while (*spos >= 0x10000) \
510 fa = sb->SB[(*sbpos)++]; \
514 d = decode_f(ctx, ch, sb->SB); \
531 // helpers for simple linear interpolation: delay real val for two slots,
532 // and calc the two deltas, for a 'look at the future behaviour'
533 #define simple_interp_store \
535 sb->SB[29] = sb->SB[30]; \
536 sb->SB[30] = sb->SB[31]; \
540 #define simple_interp_get \
541 if(sinc<0x10000) /* -> upsampling? */ \
542 InterpolateUp(sb, sinc); /* --> interpolate up */ \
543 else InterpolateDown(sb, sinc); /* --> else down */ \
546 make_do_samples(do_samples_nointerp, , fa = sb->SB[29],
547 , dst[ns] = fa, sb->SB[29] = fa)
548 make_do_samples(do_samples_simple, , ,
549 simple_interp_store, simple_interp_get, )
550 make_do_samples(do_samples_gauss, , ,
551 StoreInterpolationGaussCubic(sb, fa),
552 dst[ns] = GetInterpolationGauss(sb, *spos), )
553 make_do_samples(do_samples_cubic, , ,
554 StoreInterpolationGaussCubic(sb, fa),
555 dst[ns] = GetInterpolationCubic(sb, *spos), )
556 make_do_samples(do_samples_fmod,
557 sinc = FModChangeFrequency(spu.s_chan[ch].iRawPitch, ns, iFMod), ,
558 StoreInterpolationGaussCubic(sb, fa),
559 dst[ns] = GetInterpolationGauss(sb, *spos), )
561 INLINE int do_samples_adpcm(int *dst,
562 int (*decode_f)(void *context, int ch, int *SB), void *ctx,
563 int ch, int ns_to, int fmod, sample_buf *sb, int sinc, int *spos, int *sbpos)
565 int interp = spu.interpolation;
567 return do_samples_fmod(dst, decode_f, ctx, ch, ns_to, sb, sinc, spos, sbpos);
572 return do_samples_nointerp(dst, decode_f, ctx, ch, ns_to, sb, sinc, spos, sbpos);
574 return do_samples_simple (dst, decode_f, ctx, ch, ns_to, sb, sinc, spos, sbpos);
576 return do_samples_gauss (dst, decode_f, ctx, ch, ns_to, sb, sinc, spos, sbpos);
578 return do_samples_cubic (dst, decode_f, ctx, ch, ns_to, sb, sinc, spos, sbpos);
582 static int do_samples_skip(int ch, int ns_to)
584 SPUCHAN *s_chan = &spu.s_chan[ch];
585 int spos = s_chan->spos;
586 int sinc = s_chan->sinc;
587 int ret = ns_to, ns, d;
589 spos += s_chan->iSBPos << 16;
591 for (ns = 0; ns < ns_to; ns++)
594 while (spos >= 28*0x10000)
603 s_chan->iSBPos = spos >> 16;
604 s_chan->spos = spos & 0xffff;
609 static int do_samples_skip_fmod(int ch, int ns_to, int *fmod_buf)
611 SPUCHAN *s_chan = &spu.s_chan[ch];
612 int spos = s_chan->spos;
613 int ret = ns_to, ns, d;
615 spos += s_chan->iSBPos << 16;
617 for (ns = 0; ns < ns_to; ns++)
619 spos += FModChangeFrequency(s_chan->iRawPitch, ns, fmod_buf);
620 while (spos >= 28*0x10000)
629 s_chan->iSBPos = spos >> 16;
630 s_chan->spos = spos & 0xffff;
635 static void do_lsfr_samples(int *dst, int ns_to, int ctrl,
636 unsigned int *dwNoiseCount, unsigned int *dwNoiseVal)
638 unsigned int counter = *dwNoiseCount;
639 unsigned int val = *dwNoiseVal;
640 unsigned int level, shift, bit;
643 // modified from DrHell/shalma, no fraction
644 level = (ctrl >> 10) & 0x0f;
645 level = 0x8000 >> level;
647 for (ns = 0; ns < ns_to; ns++)
650 if (counter >= level)
653 shift = (val >> 10) & 0x1f;
654 bit = (0x69696969 >> shift) & 1;
655 bit ^= (val >> 15) & 1;
656 val = (val << 1) | bit;
659 dst[ns] = (signed short)val;
662 *dwNoiseCount = counter;
666 static int do_samples_noise(int *dst, int ch, int ns_to)
670 ret = do_samples_skip(ch, ns_to);
672 do_lsfr_samples(dst, ns_to, spu.spuCtrl, &spu.dwNoiseCount, &spu.dwNoiseVal);
678 // asm code; lv and rv must be 0-3fff
679 extern void mix_chan(int *SSumLR, int count, int lv, int rv);
680 extern void mix_chan_rvb(int *SSumLR, int count, int lv, int rv, int *rvb);
682 static void mix_chan(int *SSumLR, int count, int lv, int rv)
684 const int *src = ChanBuf;
691 l = (sval * lv) >> 14;
692 r = (sval * rv) >> 14;
698 static void mix_chan_rvb(int *SSumLR, int count, int lv, int rv, int *rvb)
700 const int *src = ChanBuf;
709 l = (sval * lv) >> 14;
710 r = (sval * rv) >> 14;
719 // 0x0800-0x0bff Voice 1
720 // 0x0c00-0x0fff Voice 3
721 static noinline void do_decode_bufs(unsigned short *mem, int which,
722 int count, int decode_pos)
724 unsigned short *dst = &mem[0x800/2 + which*0x400/2];
725 const int *src = ChanBuf;
726 int cursor = decode_pos;
731 dst[cursor] = *src++;
735 // decode_pos is updated and irqs are checked later, after voice loop
738 static void do_silent_chans(int ns_to, int silentch)
744 mask = silentch & 0xffffff;
745 for (ch = 0; mask != 0; ch++, mask >>= 1)
747 if (!(mask & 1)) continue;
748 if (spu.dwChannelDead & (1<<ch)) continue;
750 s_chan = &spu.s_chan[ch];
751 if (s_chan->pCurr > spu.pSpuIrq && s_chan->pLoop > spu.pSpuIrq)
754 s_chan->spos += s_chan->iSBPos << 16;
757 s_chan->spos += s_chan->sinc * ns_to;
758 while (s_chan->spos >= 28 * 0x10000)
760 unsigned char *start = s_chan->pCurr;
763 if (start == s_chan->pCurr || start - spu.spuMemC < 0x1000)
765 // looping on self or stopped(?)
766 spu.dwChannelDead |= 1<<ch;
771 s_chan->spos -= 28 * 0x10000;
776 static void do_channels(int ns_to)
782 if (unlikely(spu.interpolation != spu_config.iUseInterpolation))
784 spu.interpolation = spu_config.iUseInterpolation;
785 mask = spu.dwChannelsAudible & 0xffffff;
786 for (ch = 0; mask != 0; ch++, mask >>= 1)
788 ResetInterpolation(&spu.sb[ch]);
791 do_rvb = spu.rvb->StartAddr && spu_config.iUseReverb;
793 memset(RVB, 0, ns_to * sizeof(RVB[0]) * 2);
795 mask = spu.dwNewChannel & 0xffffff;
796 for (ch = 0; mask != 0; ch++, mask >>= 1) {
801 mask = spu.dwChannelsAudible & 0xffffff;
802 for (ch = 0; mask != 0; ch++, mask >>= 1) // loop em all...
804 if (!(mask & 1)) continue; // channel not playing? next
806 s_chan = &spu.s_chan[ch];
808 d = do_samples_noise(ChanBuf, ch, ns_to);
810 d = do_samples_adpcm(ChanBuf, decode_block, NULL, ch, ns_to, s_chan->bFMod,
811 &spu.sb[ch], s_chan->sinc, &s_chan->spos, &s_chan->iSBPos);
813 if (!s_chan->bStarting) {
814 d = MixADSR(ChanBuf, &s_chan->ADSRX, d);
816 spu.dwChannelsAudible &= ~(1 << ch);
817 s_chan->ADSRX.State = ADSR_RELEASE;
818 s_chan->ADSRX.EnvelopeVol = 0;
819 memset(&ChanBuf[d], 0, (ns_to - d) * sizeof(ChanBuf[0]));
823 if (ch == 1 || ch == 3)
825 do_decode_bufs(spu.spuMem, ch/2, ns_to, spu.decode_pos);
826 spu.decode_dirty_ch |= 1 << ch;
829 if (s_chan->bFMod == 2) // fmod freq channel
830 memcpy(iFMod, &ChanBuf, ns_to * sizeof(iFMod[0]));
831 if (!(spu.spuCtrl & CTRL_MUTE))
833 else if (s_chan->bRVBActive && do_rvb)
834 mix_chan_rvb(spu.SSumLR, ns_to, s_chan->iLeftVolume, s_chan->iRightVolume, RVB);
836 mix_chan(spu.SSumLR, ns_to, s_chan->iLeftVolume, s_chan->iRightVolume);
839 MixCD(spu.SSumLR, RVB, ns_to, spu.decode_pos);
841 if (spu.rvb->StartAddr) {
843 REVERBDo(spu.SSumLR, RVB, ns_to, spu.rvb->CurrAddr);
845 spu.rvb->CurrAddr += ns_to / 2;
846 while (spu.rvb->CurrAddr >= 0x40000)
847 spu.rvb->CurrAddr -= 0x40000 - spu.rvb->StartAddr;
851 static void do_samples_finish(int *SSumLR, int ns_to,
852 int silentch, int decode_pos);
854 // optional worker thread handling
856 #if P_HAVE_PTHREAD || defined(WANT_THREAD_CODE)
858 // worker thread state
859 static struct spu_worker {
862 unsigned char exit_thread;
863 unsigned char prev_work_in_thread;
864 unsigned char pad[2];
865 unsigned int i_ready;
866 unsigned int i_reaped;
867 unsigned int last_boot_cnt; // dsp
868 unsigned int ram_dirty;
869 unsigned int channels_last;
871 // aligning for C64X_DSP
872 unsigned int _pad0[128/4];
877 unsigned int active; // dsp
878 unsigned int boot_cnt;
880 unsigned int _pad1[128/4];
887 unsigned int channels_new;
888 unsigned int channels_on;
889 unsigned int channels_silent;
898 unsigned short ns_to;
899 unsigned short bNoise:1;
900 unsigned short bFMod:2;
901 unsigned short bRVBActive:1;
902 unsigned short bStarting:1;
905 int SSumLR[NSSIZE * 2];
909 #define WORK_MAXCNT (sizeof(worker->i) / sizeof(worker->i[0]))
910 #define WORK_I_MASK (WORK_MAXCNT - 1)
912 static void thread_work_start(void);
913 static void thread_work_wait_sync(struct work_item *work, int force);
914 static void thread_sync_caches(void);
915 static int thread_get_i_done(void);
917 static int decode_block_work(void *context, int ch, int *SB)
919 const unsigned char *ram = spu.spuMemC;
920 int predict_nr, shift_factor, flags;
921 struct work_item *work = context;
922 int start = work->ch[ch].start;
923 int loop = work->ch[ch].loop;
925 predict_nr = ram[start];
926 shift_factor = predict_nr & 0xf;
929 decode_block_data(SB, ram + start + 2, predict_nr, shift_factor);
931 flags = ram[start + 1];
933 loop = start; // loop adress
937 if (flags & 1) // 1: stop/loop
940 work->ch[ch].start = start & 0x7ffff;
941 work->ch[ch].loop = loop;
946 static void queue_channel_work(int ns_to, unsigned int silentch)
949 struct work_item *work;
954 work = &worker->i[worker->i_ready & WORK_I_MASK];
956 work->ctrl = spu.spuCtrl;
957 work->decode_pos = spu.decode_pos;
958 work->channels_silent = silentch;
960 if (!worker->prev_work_in_thread) {
961 // copy adpcm and interpolation state to sb_thread
962 worker->prev_work_in_thread = 1;
963 mask = spu.dwChannelsAudible & ~spu.dwNewChannel & 0xffffff;
964 for (ch = 0; mask != 0; ch++, mask >>= 1) {
966 memcpy(spu.sb_thread[ch].SB, spu.sb[ch].SB, sizeof(spu.sb_thread[ch].SB));
970 mask = work->channels_new = spu.dwNewChannel & 0xffffff;
971 for (ch = 0; mask != 0; ch++, mask >>= 1) {
976 mask = work->channels_on = spu.dwChannelsAudible & 0xffffff;
977 worker->channels_last = mask;
978 spu.decode_dirty_ch |= mask & 0x0a;
980 for (ch = 0; mask != 0; ch++, mask >>= 1)
982 if (!(mask & 1)) continue;
984 s_chan = &spu.s_chan[ch];
985 work->ch[ch].spos = s_chan->spos;
986 work->ch[ch].sbpos = s_chan->iSBPos;
987 work->ch[ch].sinc = s_chan->sinc;
988 work->ch[ch].adsr = s_chan->ADSRX;
989 work->ch[ch].vol_l = s_chan->iLeftVolume;
990 work->ch[ch].vol_r = s_chan->iRightVolume;
991 work->ch[ch].start = s_chan->pCurr - spu.spuMemC;
992 work->ch[ch].loop = s_chan->pLoop - spu.spuMemC;
993 work->ch[ch].bNoise = s_chan->bNoise;
994 work->ch[ch].bFMod = s_chan->bFMod;
995 work->ch[ch].bRVBActive = s_chan->bRVBActive;
996 work->ch[ch].bStarting = s_chan->bStarting;
997 if (s_chan->prevflags & 1)
998 work->ch[ch].start = work->ch[ch].loop;
1000 if (unlikely(s_chan->bFMod == 2))
1002 // sucks, have to do double work
1004 d = do_samples_noise(tmpFMod, ch, ns_to);
1006 d = do_samples_gauss(tmpFMod, decode_block, NULL, ch, ns_to,
1007 &spu.sb[ch], s_chan->sinc, &s_chan->spos, &s_chan->iSBPos);
1008 if (!s_chan->bStarting) {
1009 d = MixADSR(tmpFMod, &s_chan->ADSRX, d);
1011 spu.dwChannelsAudible &= ~(1 << ch);
1012 s_chan->ADSRX.State = ADSR_RELEASE;
1013 s_chan->ADSRX.EnvelopeVol = 0;
1016 memset(&tmpFMod[d], 0, (ns_to - d) * sizeof(tmpFMod[d]));
1017 work->ch[ch].ns_to = d;
1020 if (unlikely(s_chan->bFMod))
1021 d = do_samples_skip_fmod(ch, ns_to, tmpFMod);
1023 d = do_samples_skip(ch, ns_to);
1024 work->ch[ch].ns_to = d;
1026 if (!s_chan->bStarting) {
1027 // note: d is not accurate on skip
1028 d = SkipADSR(&s_chan->ADSRX, d);
1030 spu.dwChannelsAudible &= ~(1 << ch);
1031 s_chan->ADSRX.State = ADSR_RELEASE;
1032 s_chan->ADSRX.EnvelopeVol = 0;
1038 if (spu.rvb->StartAddr) {
1039 if (spu_config.iUseReverb)
1040 work->rvb_addr = spu.rvb->CurrAddr;
1042 spu.rvb->CurrAddr += ns_to / 2;
1043 while (spu.rvb->CurrAddr >= 0x40000)
1044 spu.rvb->CurrAddr -= 0x40000 - spu.rvb->StartAddr;
1048 thread_work_start();
1051 static void do_channel_work(struct work_item *work)
1057 ns_to = work->ns_to;
1059 if (unlikely(spu.interpolation != spu_config.iUseInterpolation))
1061 spu.interpolation = spu_config.iUseInterpolation;
1062 mask = work->channels_on;
1063 for (ch = 0; mask != 0; ch++, mask >>= 1)
1065 ResetInterpolation(&spu.sb_thread[ch]);
1069 memset(RVB, 0, ns_to * sizeof(RVB[0]) * 2);
1071 mask = work->channels_new;
1072 for (ch = 0; mask != 0; ch++, mask >>= 1) {
1074 StartSoundSB(&spu.sb_thread[ch]);
1077 mask = work->channels_on;
1078 for (ch = 0; mask != 0; ch++, mask >>= 1)
1080 if (!(mask & 1)) continue;
1082 d = work->ch[ch].ns_to;
1083 spos = work->ch[ch].spos;
1084 sbpos = work->ch[ch].sbpos;
1086 if (work->ch[ch].bNoise)
1087 do_lsfr_samples(ChanBuf, d, work->ctrl, &spu.dwNoiseCount, &spu.dwNoiseVal);
1089 do_samples_adpcm(ChanBuf, decode_block_work, work, ch, d, work->ch[ch].bFMod,
1090 &spu.sb_thread[ch], work->ch[ch].sinc, &spos, &sbpos);
1092 d = MixADSR(ChanBuf, &work->ch[ch].adsr, d);
1094 work->ch[ch].adsr.EnvelopeVol = 0;
1095 memset(&ChanBuf[d], 0, (ns_to - d) * sizeof(ChanBuf[0]));
1098 if (ch == 1 || ch == 3)
1099 do_decode_bufs(spu.spuMem, ch/2, ns_to, work->decode_pos);
1101 if (work->ch[ch].bFMod == 2) // fmod freq channel
1102 memcpy(iFMod, &ChanBuf, ns_to * sizeof(iFMod[0]));
1103 if (work->ch[ch].bRVBActive && work->rvb_addr)
1104 mix_chan_rvb(work->SSumLR, ns_to,
1105 work->ch[ch].vol_l, work->ch[ch].vol_r, RVB);
1107 mix_chan(work->SSumLR, ns_to, work->ch[ch].vol_l, work->ch[ch].vol_r);
1111 REVERBDo(work->SSumLR, RVB, ns_to, work->rvb_addr);
1114 static void sync_worker_thread(int force_no_thread)
1116 int force = force_no_thread;
1117 struct work_item *work;
1118 int done, used_space;
1120 // rvb offsets will change, thread may be using them
1121 force |= spu.rvb->dirty && spu.rvb->StartAddr;
1123 done = thread_get_i_done() - worker->i_reaped;
1124 used_space = worker->i_ready - worker->i_reaped;
1126 //printf("done: %d use: %d dsp: %u/%u\n", done, used_space,
1127 // worker->boot_cnt, worker->i_done);
1129 while ((force && used_space > 0) || used_space >= WORK_MAXCNT || done > 0) {
1130 work = &worker->i[worker->i_reaped & WORK_I_MASK];
1131 thread_work_wait_sync(work, force);
1133 MixCD(work->SSumLR, RVB, work->ns_to, work->decode_pos);
1134 do_samples_finish(work->SSumLR, work->ns_to,
1135 work->channels_silent, work->decode_pos);
1138 done = thread_get_i_done() - worker->i_reaped;
1139 used_space = worker->i_ready - worker->i_reaped;
1141 if (force_no_thread && worker->prev_work_in_thread) {
1142 unsigned int ch, mask = worker->channels_last;
1143 worker->prev_work_in_thread = 0;
1144 thread_sync_caches();
1145 for (ch = 0; mask != 0; ch++, mask >>= 1) {
1147 memcpy(spu.sb[ch].SB, spu.sb_thread[ch].SB, sizeof(spu.sb_thread[ch].SB));
1154 static void queue_channel_work(int ns_to, int silentch) {}
1155 static void sync_worker_thread(int force_no_thread) {}
1157 static const void * const worker = NULL;
1159 #endif // P_HAVE_PTHREAD || defined(WANT_THREAD_CODE)
1161 ////////////////////////////////////////////////////////////////////////
1162 // MAIN SPU FUNCTION
1163 // here is the main job handler...
1164 ////////////////////////////////////////////////////////////////////////
1166 void do_samples(unsigned int cycles_to, int force_no_thread)
1168 unsigned int silentch;
1172 cycle_diff = cycles_to - spu.cycles_played;
1173 if (cycle_diff < -2*1048576 || cycle_diff > 2*1048576)
1175 log_unhandled("desync %u %d\n", cycles_to, cycle_diff);
1176 spu.cycles_played = cycles_to;
1180 silentch = ~(spu.dwChannelsAudible | spu.dwNewChannel) & 0xffffff;
1182 force_no_thread |= (silentch == 0xffffff);
1184 sync_worker_thread(force_no_thread);
1186 if (cycle_diff < 2 * 768)
1189 ns_to = (cycle_diff / 768 + 1) & ~1;
1190 if (ns_to > NSSIZE) {
1191 // should never happen
1192 log_unhandled("ns_to oflow %d %d\n", ns_to, NSSIZE);
1196 //////////////////////////////////////////////////////
1197 // special irq handling in the decode buffers (0x0000-0x1000)
1199 // the decode buffers are located in spu memory in the following way:
1200 // 0x0000-0x03ff CD audio left
1201 // 0x0400-0x07ff CD audio right
1202 // 0x0800-0x0bff Voice 1
1203 // 0x0c00-0x0fff Voice 3
1204 // and decoded data is 16 bit for one sample
1206 // even if voices 1/3 are off or no cd audio is playing, the internal
1207 // play positions will move on and wrap after 0x400 bytes.
1208 // Therefore: we just need a pointer from spumem+0 to spumem+3ff, and
1209 // increase this pointer on each sample by 2 bytes. If this pointer
1210 // (or 0x400 offsets of this pointer) hits the spuirq address, we generate
1213 if (unlikely((spu.spuCtrl & CTRL_IRQ)
1214 && spu.pSpuIrq < spu.spuMemC+0x1000))
1216 int irq_pos = (spu.pSpuIrq - spu.spuMemC) / 2 & 0x1ff;
1217 int left = (irq_pos - spu.decode_pos) & 0x1ff;
1218 if (0 < left && left <= ns_to)
1220 //xprintf("decoder irq %x\n", spu.decode_pos);
1224 if (!spu.cycles_dma_end || (int)(spu.cycles_dma_end - cycles_to) < 0) {
1225 spu.cycles_dma_end = 0;
1226 check_irq_io(spu.spuAddr);
1229 if (unlikely(spu.rvb->dirty))
1232 if (force_no_thread || worker == NULL || !spu_config.iUseThread) {
1234 do_samples_finish(spu.SSumLR, ns_to, silentch, spu.decode_pos);
1237 queue_channel_work(ns_to, silentch);
1238 //sync_worker_thread(1); // uncomment for debug
1241 // advance "stopped" channels that can cause irqs
1242 // (all chans are always playing on the real thing..)
1243 if (spu.spuCtrl & CTRL_IRQ)
1244 do_silent_chans(ns_to, silentch);
1246 spu.cycles_played += ns_to * 768;
1247 spu.decode_pos = (spu.decode_pos + ns_to) & 0x1ff;
1248 spu.spuStat = (spu.spuStat & ~0x800) | ((spu.decode_pos << 3) & 0x800);
1250 static int ccount; static time_t ctime; ccount++;
1251 if (time(NULL) != ctime)
1252 { printf("%d\n", ccount); ccount = 0; ctime = time(NULL); }
1256 static void do_samples_finish(int *SSumLR, int ns_to,
1257 int silentch, int decode_pos)
1259 int vol_l = ((int)regAreaGet(H_SPUmvolL) << 17) >> 17;
1260 int vol_r = ((int)regAreaGet(H_SPUmvolR) << 17) >> 17;
1264 // must clear silent channel decode buffers
1265 if(unlikely(silentch & spu.decode_dirty_ch & (1<<1)))
1267 memset(&spu.spuMem[0x800/2], 0, 0x400);
1268 spu.decode_dirty_ch &= ~(1<<1);
1270 if(unlikely(silentch & spu.decode_dirty_ch & (1<<3)))
1272 memset(&spu.spuMem[0xc00/2], 0, 0x400);
1273 spu.decode_dirty_ch &= ~(1<<3);
1276 vol_l = vol_l * spu_config.iVolume >> 10;
1277 vol_r = vol_r * spu_config.iVolume >> 10;
1279 if (!(vol_l | vol_r))
1282 memset(spu.pS, 0, ns_to * 2 * sizeof(spu.pS[0]));
1283 memset(SSumLR, 0, ns_to * 2 * sizeof(SSumLR[0]));
1284 spu.pS += ns_to * 2;
1287 for (ns = 0; ns < ns_to * 2; )
1289 d = SSumLR[ns]; SSumLR[ns] = 0;
1290 d = d * vol_l >> 14;
1295 d = SSumLR[ns]; SSumLR[ns] = 0;
1296 d = d * vol_r >> 14;
1303 void schedule_next_irq(void)
1305 unsigned int upd_samples;
1308 if (spu.scheduleCallback == NULL)
1311 upd_samples = 44100 / 50;
1313 for (ch = 0; ch < MAXCHAN; ch++)
1315 if (spu.dwChannelDead & (1 << ch))
1317 if ((unsigned long)(spu.pSpuIrq - spu.s_chan[ch].pCurr) > IRQ_NEAR_BLOCKS * 16
1318 && (unsigned long)(spu.pSpuIrq - spu.s_chan[ch].pLoop) > IRQ_NEAR_BLOCKS * 16)
1320 if (spu.s_chan[ch].sinc == 0)
1323 scan_for_irq(ch, &upd_samples);
1326 if (unlikely(spu.pSpuIrq < spu.spuMemC + 0x1000))
1328 int irq_pos = (spu.pSpuIrq - spu.spuMemC) / 2 & 0x1ff;
1329 int left = (irq_pos - spu.decode_pos) & 0x1ff;
1330 if (0 < left && left < upd_samples) {
1331 //xprintf("decode: %3d (%3d/%3d)\n", left, spu.decode_pos, irq_pos);
1336 if (upd_samples < 44100 / 50)
1337 spu.scheduleCallback(upd_samples * 768);
1340 // SPU ASYNC... even newer epsxe func
1341 // 1 time every 'cycle' cycles... harhar
1343 // rearmed: called dynamically now
1345 void CALLBACK SPUasync(unsigned int cycle, unsigned int flags)
1347 do_samples(cycle, 0);
1349 if (spu.spuCtrl & CTRL_IRQ)
1350 schedule_next_irq();
1353 out_current->feed(spu.pSpuBuffer, (unsigned char *)spu.pS - spu.pSpuBuffer);
1354 spu.pS = (short *)spu.pSpuBuffer;
1356 if (spu_config.iTempo) {
1357 if (!out_current->busy())
1358 // cause more samples to be generated
1359 // (and break some games because of bad sync)
1360 spu.cycles_played -= 44100 / 60 / 2 * 768;
1365 // SPU UPDATE... new epsxe func
1366 // 1 time every 32 hsync lines
1367 // (312/32)x50 in pal
1368 // (262/32)x60 in ntsc
1370 // since epsxe 1.5.2 (linux) uses SPUupdate, not SPUasync, I will
1371 // leave that func in the linux port, until epsxe linux is using
1372 // the async function as well
1374 void CALLBACK SPUupdate(void)
1380 void CALLBACK SPUplayADPCMchannel(xa_decode_t *xap, unsigned int cycle, int is_start)
1383 if(!xap->freq) return; // no xa freq ? bye
1386 spu.XAPlay = spu.XAFeed = spu.XAStart;
1387 if (spu.XAPlay == spu.XAFeed)
1388 do_samples(cycle, 1); // catch up to prevent source underflows later
1390 FeedXA(xap); // call main XA feeder
1391 spu.xapGlobal = xap; // store info for save states
1392 spu.cdClearSamples = 512;
1396 int CALLBACK SPUplayCDDAchannel(short *pcm, int nbytes, unsigned int cycle, int unused)
1398 if (!pcm) return -1;
1399 if (nbytes<=0) return -1;
1401 if (spu.CDDAPlay == spu.CDDAFeed)
1402 do_samples(cycle, 1); // catch up to prevent source underflows later
1404 FeedCDDA((unsigned char *)pcm, nbytes);
1405 spu.cdClearSamples = 512;
1409 void CALLBACK SPUsetCDvol(unsigned char ll, unsigned char lr,
1410 unsigned char rl, unsigned char rr, unsigned int cycle)
1412 if (spu.XAPlay != spu.XAFeed || spu.CDDAPlay != spu.CDDAFeed)
1413 do_samples(cycle, 1);
1420 // to be called after state load
1421 void ClearWorkingState(void)
1423 memset(iFMod, 0, sizeof(iFMod));
1424 spu.pS=(short *)spu.pSpuBuffer; // setup soundbuffer pointer
1427 // SETUPSTREAMS: init most of the spu buffers
1428 static void SetupStreams(void)
1430 spu.pSpuBuffer = (unsigned char *)malloc(32768); // alloc mixing buffer
1431 spu.SSumLR = calloc(NSSIZE * 2, sizeof(spu.SSumLR[0]));
1433 spu.XAStart = malloc(44100 * sizeof(uint32_t)); // alloc xa buffer
1434 spu.XAEnd = spu.XAStart + 44100;
1435 spu.XAPlay = spu.XAStart;
1436 spu.XAFeed = spu.XAStart;
1438 spu.CDDAStart = malloc(CDDA_BUFFER_SIZE); // alloc cdda buffer
1439 spu.CDDAEnd = spu.CDDAStart + CDDA_BUFFER_SIZE / sizeof(uint32_t);
1440 spu.CDDAPlay = spu.CDDAStart;
1441 spu.CDDAFeed = spu.CDDAStart;
1443 ClearWorkingState();
1446 // REMOVESTREAMS: free most buffer
1447 static void RemoveStreams(void)
1449 free(spu.pSpuBuffer); // free mixing buffer
1450 spu.pSpuBuffer = NULL;
1453 free(spu.XAStart); // free XA buffer
1455 free(spu.CDDAStart); // free CDDA buffer
1456 spu.CDDAStart = NULL;
1459 #if defined(C64X_DSP)
1461 /* special code for TI C64x DSP */
1462 #include "spu_c64x.c"
1464 #elif P_HAVE_PTHREAD
1466 #include <pthread.h>
1467 #include <semaphore.h>
1476 /* generic pthread implementation */
1478 static void thread_work_start(void)
1480 sem_post(&t.sem_avail);
1483 static void thread_work_wait_sync(struct work_item *work, int force)
1485 sem_wait(&t.sem_done);
1488 static int thread_get_i_done(void)
1490 return worker->i_done;
1493 static void thread_sync_caches(void)
1497 static void *spu_worker_thread(void *unused)
1499 struct work_item *work;
1502 sem_wait(&t.sem_avail);
1503 if (worker->exit_thread)
1506 work = &worker->i[worker->i_done & WORK_I_MASK];
1507 do_channel_work(work);
1510 sem_post(&t.sem_done);
1516 static void init_spu_thread(void)
1520 spu.sb_thread = spu.sb_thread_;
1522 if (sysconf(_SC_NPROCESSORS_ONLN) <= 1)
1525 worker = calloc(1, sizeof(*worker));
1528 ret = sem_init(&t.sem_avail, 0, 0);
1530 goto fail_sem_avail;
1531 ret = sem_init(&t.sem_done, 0, 0);
1535 ret = pthread_create(&t.thread, NULL, spu_worker_thread, NULL);
1539 spu_config.iThreadAvail = 1;
1543 sem_destroy(&t.sem_done);
1545 sem_destroy(&t.sem_avail);
1549 spu_config.iThreadAvail = 0;
1552 static void exit_spu_thread(void)
1556 worker->exit_thread = 1;
1557 sem_post(&t.sem_avail);
1558 pthread_join(t.thread, NULL);
1559 sem_destroy(&t.sem_done);
1560 sem_destroy(&t.sem_avail);
1565 #else // if !P_HAVE_PTHREAD
1567 static void init_spu_thread(void)
1571 static void exit_spu_thread(void)
1577 // SPUINIT: this func will be called first by the main emu
1578 long CALLBACK SPUinit(void)
1582 memset(&spu, 0, sizeof(spu));
1583 spu.spuMemC = calloc(1, 512 * 1024 + 16);
1584 // a guard for runaway channels - End+Mute
1585 spu.spuMemC[512 * 1024 + 1] = 1;
1589 spu.s_chan = calloc(MAXCHAN+1, sizeof(spu.s_chan[0])); // channel + 1 infos (1 is security for fmod handling)
1590 spu.rvb = calloc(1, sizeof(REVERBInfo));
1594 spu.pSpuIrq = spu.spuMemC;
1596 SetupStreams(); // prepare streaming
1598 if (spu_config.iVolume == 0)
1599 spu_config.iVolume = 768; // 1024 is 1.0
1603 for (i = 0; i < MAXCHAN; i++) // loop sound channels
1605 spu.s_chan[i].ADSRX.SustainLevel = 0xf; // -> init sustain
1606 spu.s_chan[i].ADSRX.SustainIncrease = 1;
1607 spu.s_chan[i].pLoop = spu.spuMemC;
1608 spu.s_chan[i].pCurr = spu.spuMemC;
1609 spu.s_chan[i].bIgnoreLoop = 0;
1612 spu.bSpuInit=1; // flag: we are inited
1617 // SPUOPEN: called by main emu after init
1618 long CALLBACK SPUopen(void)
1620 if (spu.bSPUIsOpen) return 0; // security for some stupid main emus
1622 SetupSound(); // setup sound (before init!)
1626 return PSE_SPU_ERR_SUCCESS;
1629 // SPUCLOSE: called before shutdown
1630 long CALLBACK SPUclose(void)
1632 if (!spu.bSPUIsOpen) return 0; // some security
1634 spu.bSPUIsOpen = 0; // no more open
1636 out_current->finish(); // no more sound handling
1641 // SPUSHUTDOWN: called by main emu on final exit
1642 long CALLBACK SPUshutdown(void)
1655 RemoveStreams(); // no more streaming
1662 // this functions will be called once,
1663 // passes a callback that should be called on SPU-IRQ/cdda volume change
1664 void CALLBACK SPUregisterCallback(void (CALLBACK *callback)(int))
1666 spu.irqCallback = callback;
1669 void CALLBACK SPUregisterCDDAVolume(void (CALLBACK *CDDAVcallback)(short, short))
1671 //spu.cddavCallback = CDDAVcallback;
1674 void CALLBACK SPUregisterScheduleCb(void (CALLBACK *callback)(unsigned int))
1676 spu.scheduleCallback = callback;
1679 // COMMON PLUGIN INFO FUNCS
1681 char * CALLBACK PSEgetLibName(void)
1683 return _(libraryName);
1686 unsigned long CALLBACK PSEgetLibType(void)
1691 unsigned long CALLBACK PSEgetLibVersion(void)
1693 return (1 << 16) | (6 << 8);
1696 char * SPUgetLibInfos(void)
1698 return _(libraryInfo);
1703 void spu_get_debug_info(int *chans_out, int *run_chans, int *fmod_chans_out, int *noise_chans_out)
1705 int ch = 0, fmod_chans = 0, noise_chans = 0, irq_chans = 0;
1707 if (spu.s_chan == NULL)
1710 for(;ch<MAXCHAN;ch++)
1712 if (!(spu.dwChannelsAudible & (1<<ch)))
1714 if (spu.s_chan[ch].bFMod == 2)
1715 fmod_chans |= 1 << ch;
1716 if (spu.s_chan[ch].bNoise)
1717 noise_chans |= 1 << ch;
1718 if((spu.spuCtrl&CTRL_IRQ) && spu.s_chan[ch].pCurr <= spu.pSpuIrq && spu.s_chan[ch].pLoop <= spu.pSpuIrq)
1719 irq_chans |= 1 << ch;
1722 *chans_out = spu.dwChannelsAudible;
1723 *run_chans = ~spu.dwChannelsAudible & ~spu.dwChannelDead & irq_chans;
1724 *fmod_chans_out = fmod_chans;
1725 *noise_chans_out = noise_chans;
1728 // vim:shiftwidth=1:expandtab