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(int cycles_after)
203 if (spu.spuStat & STAT_IRQ)
204 log_unhandled("spu: missed irq?\n");
207 spu.spuStat |= STAT_IRQ; // asserted status?
209 spu.irqCallback(cycles_after);
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 %04zx\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 void do_irq_io(int cycles_after)
237 if ((spu.spuCtrl & (CTRL_ON|CTRL_IRQ)) == (CTRL_ON|CTRL_IRQ))
239 do_irq(cycles_after);
243 ////////////////////////////////////////////////////////////////////////
244 // START SOUND... called by main thread to setup a new sound on a channel
245 ////////////////////////////////////////////////////////////////////////
247 static void ResetInterpolation(sample_buf *sb)
249 memset(&sb->interp, 0, sizeof(sb->interp));
253 static void StartSoundSB(sample_buf *sb)
255 sb->SB[26] = 0; // init mixing vars
257 ResetInterpolation(sb);
260 static void StartSoundMain(int ch)
262 SPUCHAN *s_chan = &spu.s_chan[ch];
267 s_chan->prevflags = 2;
270 s_chan->bStarting = 1;
272 s_chan->pCurr = spu.spuMemC + ((regAreaGetCh(ch, 6) & ~1) << 3);
274 spu.dwNewChannel&=~(1<<ch); // clear new channel bit
275 spu.dwChannelDead&=~(1<<ch);
276 spu.dwChannelsAudible|=1<<ch;
279 static void StartSound(int ch)
282 StartSoundSB(&spu.sb[ch]);
285 ////////////////////////////////////////////////////////////////////////
286 // ALL KIND OF HELPERS
287 ////////////////////////////////////////////////////////////////////////
289 INLINE int FModChangeFrequency(int pitch, int ns, int *fmod_buf)
291 pitch = (signed short)pitch;
292 pitch = ((32768 + fmod_buf[ns]) * pitch) >> 15;
302 INLINE void StoreInterpolationGaussCubic(sample_buf *sb, int fa)
304 int gpos = sb->interp.gauss.pos & 3;
305 sb->interp.gauss.val[gpos++] = fa;
306 sb->interp.gauss.pos = gpos & 3;
309 #define gval(x) (int)sb->interp.gauss.val[(gpos + x) & 3]
311 INLINE int GetInterpolationCubic(const sample_buf *sb, int spos)
313 int gpos = sb->interp.gauss.pos;
314 int xd = (spos >> 1) + 1;
317 fa = gval(3) - 3*gval(2) + 3*gval(1) - gval(0);
318 fa *= (xd - (2<<15)) / 6;
320 fa += gval(2) - gval(1) - gval(1) + gval(0);
321 fa *= (xd - (1<<15)) >> 1;
323 fa += gval(1) - gval(0);
330 INLINE int GetInterpolationGauss(const sample_buf *sb, int spos)
332 int gpos = sb->interp.gauss.pos;
333 int vl = (spos >> 6) & ~3;
335 vr = (gauss[vl+0] * gval(0)) >> 15;
336 vr += (gauss[vl+1] * gval(1)) >> 15;
337 vr += (gauss[vl+2] * gval(2)) >> 15;
338 vr += (gauss[vl+3] * gval(3)) >> 15;
342 static void decode_block_data(int *dest, const unsigned char *src, int predict_nr, int shift_factor)
344 static const int f[16][2] = {
352 int fa, s_1, s_2, d, s;
357 for (nSample = 0; nSample < 28; src++)
360 s = (int)(signed short)((d & 0x0f) << 12);
362 fa = s >> shift_factor;
363 fa += ((s_1 * f[predict_nr][0])>>6) + ((s_2 * f[predict_nr][1])>>6);
367 dest[nSample++] = fa;
369 s = (int)(signed short)((d & 0xf0) << 8);
370 fa = s >> shift_factor;
371 fa += ((s_1 * f[predict_nr][0])>>6) + ((s_2 * f[predict_nr][1])>>6);
375 dest[nSample++] = fa;
379 static int decode_block(void *unused, int ch, int *SB)
381 SPUCHAN *s_chan = &spu.s_chan[ch];
382 unsigned char *start;
383 int predict_nr, shift_factor, flags;
386 start = s_chan->pCurr; // set up the current pos
387 if (start - spu.spuMemC < 0x1000) { // ?
388 //log_unhandled("ch%02d plays decode bufs @%05lx\n",
389 // ch, (long)(start - spu.spuMemC));
393 if (s_chan->prevflags & 1) // 1: stop/loop
395 if (!(s_chan->prevflags & 2))
398 start = s_chan->pLoop;
401 check_irq(ch, start);
403 predict_nr = start[0];
404 shift_factor = predict_nr & 0xf;
407 decode_block_data(SB, start + 2, predict_nr, shift_factor);
410 if (flags & 4 && !s_chan->bIgnoreLoop)
411 s_chan->pLoop = start; // loop adress
415 s_chan->pCurr = start; // store values for next cycle
416 s_chan->prevflags = flags;
417 s_chan->bStarting = 0;
422 // do block, but ignore sample data
423 static int skip_block(int ch)
425 SPUCHAN *s_chan = &spu.s_chan[ch];
426 unsigned char *start = s_chan->pCurr;
430 if (s_chan->prevflags & 1) {
431 if (!(s_chan->prevflags & 2))
434 start = s_chan->pLoop;
437 check_irq(ch, start);
440 if (flags & 4 && !s_chan->bIgnoreLoop)
441 s_chan->pLoop = start;
445 s_chan->pCurr = start;
446 s_chan->prevflags = flags;
447 s_chan->bStarting = 0;
452 // if irq is going to trigger sooner than in upd_samples, set upd_samples
453 static void scan_for_irq(int ch, unsigned int *upd_samples)
455 SPUCHAN *s_chan = &spu.s_chan[ch];
456 int pos, sinc, sinc_inv, end;
457 unsigned char *block;
460 block = s_chan->pCurr;
463 end = pos + *upd_samples * sinc;
464 if (s_chan->prevflags & 1) // 1: stop/loop
465 block = s_chan->pLoop;
467 pos += (28 - s_chan->iSBPos) << 16;
470 if (block == spu.pSpuIrq)
474 if (flags & 1) { // 1: stop/loop
475 block = s_chan->pLoop;
482 sinc_inv = s_chan->sinc_inv;
484 sinc_inv = s_chan->sinc_inv = (0x80000000u / (uint32_t)sinc) << 1;
487 *upd_samples = (((uint64_t)pos * sinc_inv) >> 32) + 1;
488 //xprintf("ch%02d: irq sched: %3d %03d\n",
489 // ch, *upd_samples, *upd_samples * 60 * 263 / 44100);
493 #define make_do_samples(name, fmod_code, interp_start, interp_store, interp_get, interp_end) \
494 static noinline int name(int *dst, \
495 int (*decode_f)(void *context, int ch, int *SB), void *ctx, \
496 int ch, int ns_to, sample_buf *sb, int sinc, int *spos, int *sbpos) \
502 for (ns = 0; ns < ns_to; ns++) \
507 while (*spos >= 0x10000) \
509 fa = sb->SB[(*sbpos)++]; \
513 d = decode_f(ctx, ch, sb->SB); \
530 // helpers for simple linear interpolation: delay real val for two slots,
531 // and calc the two deltas, for a 'look at the future behaviour'
532 #define simple_interp_store \
534 sb->SB[29] = sb->SB[30]; \
535 sb->SB[30] = sb->SB[31]; \
539 #define simple_interp_get \
540 if(sinc<0x10000) /* -> upsampling? */ \
541 InterpolateUp(sb, sinc); /* --> interpolate up */ \
542 else InterpolateDown(sb, sinc); /* --> else down */ \
545 make_do_samples(do_samples_nointerp, , fa = sb->SB[29],
546 , dst[ns] = fa, sb->SB[29] = fa)
547 make_do_samples(do_samples_simple, , ,
548 simple_interp_store, simple_interp_get, )
549 make_do_samples(do_samples_gauss, , ,
550 StoreInterpolationGaussCubic(sb, fa),
551 dst[ns] = GetInterpolationGauss(sb, *spos), )
552 make_do_samples(do_samples_cubic, , ,
553 StoreInterpolationGaussCubic(sb, fa),
554 dst[ns] = GetInterpolationCubic(sb, *spos), )
555 make_do_samples(do_samples_fmod,
556 sinc = FModChangeFrequency(spu.s_chan[ch].iRawPitch, ns, iFMod), ,
557 StoreInterpolationGaussCubic(sb, fa),
558 dst[ns] = GetInterpolationGauss(sb, *spos), )
560 INLINE int do_samples_adpcm(int *dst,
561 int (*decode_f)(void *context, int ch, int *SB), void *ctx,
562 int ch, int ns_to, int fmod, sample_buf *sb, int sinc, int *spos, int *sbpos)
564 int interp = spu.interpolation;
566 return do_samples_fmod(dst, decode_f, ctx, ch, ns_to, sb, sinc, spos, sbpos);
571 return do_samples_nointerp(dst, decode_f, ctx, ch, ns_to, sb, sinc, spos, sbpos);
573 return do_samples_simple (dst, decode_f, ctx, ch, ns_to, sb, sinc, spos, sbpos);
575 return do_samples_gauss (dst, decode_f, ctx, ch, ns_to, sb, sinc, spos, sbpos);
577 return do_samples_cubic (dst, decode_f, ctx, ch, ns_to, sb, sinc, spos, sbpos);
581 static int do_samples_skip(int ch, int ns_to)
583 SPUCHAN *s_chan = &spu.s_chan[ch];
584 int spos = s_chan->spos;
585 int sinc = s_chan->sinc;
586 int ret = ns_to, ns, d;
588 spos += s_chan->iSBPos << 16;
590 for (ns = 0; ns < ns_to; ns++)
593 while (spos >= 28*0x10000)
602 s_chan->iSBPos = spos >> 16;
603 s_chan->spos = spos & 0xffff;
608 static int do_samples_skip_fmod(int ch, int ns_to, int *fmod_buf)
610 SPUCHAN *s_chan = &spu.s_chan[ch];
611 int spos = s_chan->spos;
612 int ret = ns_to, ns, d;
614 spos += s_chan->iSBPos << 16;
616 for (ns = 0; ns < ns_to; ns++)
618 spos += FModChangeFrequency(s_chan->iRawPitch, ns, fmod_buf);
619 while (spos >= 28*0x10000)
628 s_chan->iSBPos = spos >> 16;
629 s_chan->spos = spos & 0xffff;
634 static void do_lsfr_samples(int *dst, int ns_to, int ctrl,
635 unsigned int *dwNoiseCount, unsigned int *dwNoiseVal)
637 unsigned int counter = *dwNoiseCount;
638 unsigned int val = *dwNoiseVal;
639 unsigned int level, shift, bit;
642 // modified from DrHell/shalma, no fraction
643 level = (ctrl >> 10) & 0x0f;
644 level = 0x8000 >> level;
646 for (ns = 0; ns < ns_to; ns++)
649 if (counter >= level)
652 shift = (val >> 10) & 0x1f;
653 bit = (0x69696969 >> shift) & 1;
654 bit ^= (val >> 15) & 1;
655 val = (val << 1) | bit;
658 dst[ns] = (signed short)val;
661 *dwNoiseCount = counter;
665 static int do_samples_noise(int *dst, int ch, int ns_to)
669 ret = do_samples_skip(ch, ns_to);
671 do_lsfr_samples(dst, ns_to, spu.spuCtrl, &spu.dwNoiseCount, &spu.dwNoiseVal);
677 // asm code; lv and rv must be 0-3fff
678 extern void mix_chan(int *SSumLR, int count, int lv, int rv);
679 extern void mix_chan_rvb(int *SSumLR, int count, int lv, int rv, int *rvb);
681 static void mix_chan(int *SSumLR, int count, int lv, int rv)
683 const int *src = ChanBuf;
690 l = (sval * lv) >> 14;
691 r = (sval * rv) >> 14;
697 static void mix_chan_rvb(int *SSumLR, int count, int lv, int rv, int *rvb)
699 const int *src = ChanBuf;
708 l = (sval * lv) >> 14;
709 r = (sval * rv) >> 14;
718 // 0x0800-0x0bff Voice 1
719 // 0x0c00-0x0fff Voice 3
720 static noinline void do_decode_bufs(unsigned short *mem, int which,
721 int count, int decode_pos)
723 unsigned short *dst = &mem[0x800/2 + which*0x400/2];
724 const int *src = ChanBuf;
725 int cursor = decode_pos;
730 dst[cursor] = *src++;
734 // decode_pos is updated and irqs are checked later, after voice loop
737 static void do_silent_chans(int ns_to, int silentch)
743 mask = silentch & 0xffffff;
744 for (ch = 0; mask != 0; ch++, mask >>= 1)
746 if (!(mask & 1)) continue;
747 if (spu.dwChannelDead & (1<<ch)) continue;
749 s_chan = &spu.s_chan[ch];
750 if (s_chan->pCurr > spu.pSpuIrq && s_chan->pLoop > spu.pSpuIrq)
753 s_chan->spos += s_chan->iSBPos << 16;
756 s_chan->spos += s_chan->sinc * ns_to;
757 while (s_chan->spos >= 28 * 0x10000)
759 unsigned char *start = s_chan->pCurr;
762 if (start == s_chan->pCurr || start - spu.spuMemC < 0x1000)
764 // looping on self or stopped(?)
765 spu.dwChannelDead |= 1<<ch;
770 s_chan->spos -= 28 * 0x10000;
775 static void do_channels(int ns_to)
781 if (unlikely(spu.interpolation != spu_config.iUseInterpolation))
783 spu.interpolation = spu_config.iUseInterpolation;
784 mask = spu.dwChannelsAudible & 0xffffff;
785 for (ch = 0; mask != 0; ch++, mask >>= 1)
787 ResetInterpolation(&spu.sb[ch]);
790 do_rvb = spu.rvb->StartAddr && spu_config.iUseReverb;
792 memset(RVB, 0, ns_to * sizeof(RVB[0]) * 2);
794 mask = spu.dwNewChannel & 0xffffff;
795 for (ch = 0; mask != 0; ch++, mask >>= 1) {
800 mask = spu.dwChannelsAudible & 0xffffff;
801 for (ch = 0; mask != 0; ch++, mask >>= 1) // loop em all...
803 if (!(mask & 1)) continue; // channel not playing? next
805 s_chan = &spu.s_chan[ch];
807 d = do_samples_noise(ChanBuf, ch, ns_to);
809 d = do_samples_adpcm(ChanBuf, decode_block, NULL, ch, ns_to, s_chan->bFMod,
810 &spu.sb[ch], s_chan->sinc, &s_chan->spos, &s_chan->iSBPos);
812 if (!s_chan->bStarting) {
813 d = MixADSR(ChanBuf, &s_chan->ADSRX, d);
815 spu.dwChannelsAudible &= ~(1 << ch);
816 s_chan->ADSRX.State = ADSR_RELEASE;
817 s_chan->ADSRX.EnvelopeVol = 0;
818 memset(&ChanBuf[d], 0, (ns_to - d) * sizeof(ChanBuf[0]));
822 if (ch == 1 || ch == 3)
824 do_decode_bufs(spu.spuMem, ch/2, ns_to, spu.decode_pos);
825 spu.decode_dirty_ch |= 1 << ch;
828 if (s_chan->bFMod == 2) // fmod freq channel
829 memcpy(iFMod, &ChanBuf, ns_to * sizeof(iFMod[0]));
830 if (!(spu.spuCtrl & CTRL_MUTE))
832 else if (s_chan->bRVBActive && do_rvb)
833 mix_chan_rvb(spu.SSumLR, ns_to, s_chan->iLeftVolume, s_chan->iRightVolume, RVB);
835 mix_chan(spu.SSumLR, ns_to, s_chan->iLeftVolume, s_chan->iRightVolume);
838 MixXA(spu.SSumLR, RVB, ns_to, spu.decode_pos);
840 if (spu.rvb->StartAddr) {
842 REVERBDo(spu.SSumLR, RVB, ns_to, spu.rvb->CurrAddr);
844 spu.rvb->CurrAddr += ns_to / 2;
845 while (spu.rvb->CurrAddr >= 0x40000)
846 spu.rvb->CurrAddr -= 0x40000 - spu.rvb->StartAddr;
850 static void do_samples_finish(int *SSumLR, int ns_to,
851 int silentch, int decode_pos);
853 // optional worker thread handling
855 #if P_HAVE_PTHREAD || defined(WANT_THREAD_CODE)
857 // worker thread state
858 static struct spu_worker {
861 unsigned int exit_thread;
862 unsigned int i_ready;
863 unsigned int i_reaped;
864 unsigned int last_boot_cnt; // dsp
865 unsigned int ram_dirty;
867 // aligning for C64X_DSP
868 unsigned int _pad0[128/4];
873 unsigned int active; // dsp
874 unsigned int boot_cnt;
876 unsigned int _pad1[128/4];
883 unsigned int channels_new;
884 unsigned int channels_on;
885 unsigned int channels_silent;
894 unsigned short ns_to;
895 unsigned short bNoise:1;
896 unsigned short bFMod:2;
897 unsigned short bRVBActive:1;
898 unsigned short bStarting:1;
901 int SSumLR[NSSIZE * 2];
905 #define WORK_MAXCNT (sizeof(worker->i) / sizeof(worker->i[0]))
906 #define WORK_I_MASK (WORK_MAXCNT - 1)
908 static void thread_work_start(void);
909 static void thread_work_wait_sync(struct work_item *work, int force);
910 static void thread_sync_caches(void);
911 static int thread_get_i_done(void);
913 static int decode_block_work(void *context, int ch, int *SB)
915 const unsigned char *ram = spu.spuMemC;
916 int predict_nr, shift_factor, flags;
917 struct work_item *work = context;
918 int start = work->ch[ch].start;
919 int loop = work->ch[ch].loop;
921 predict_nr = ram[start];
922 shift_factor = predict_nr & 0xf;
925 decode_block_data(SB, ram + start + 2, predict_nr, shift_factor);
927 flags = ram[start + 1];
929 loop = start; // loop adress
933 if (flags & 1) // 1: stop/loop
936 work->ch[ch].start = start & 0x7ffff;
937 work->ch[ch].loop = loop;
942 static void queue_channel_work(int ns_to, unsigned int silentch)
945 struct work_item *work;
950 work = &worker->i[worker->i_ready & WORK_I_MASK];
952 work->ctrl = spu.spuCtrl;
953 work->decode_pos = spu.decode_pos;
954 work->channels_silent = silentch;
956 mask = work->channels_new = spu.dwNewChannel & 0xffffff;
957 for (ch = 0; mask != 0; ch++, mask >>= 1) {
962 mask = work->channels_on = spu.dwChannelsAudible & 0xffffff;
963 spu.decode_dirty_ch |= mask & 0x0a;
965 for (ch = 0; mask != 0; ch++, mask >>= 1)
967 if (!(mask & 1)) continue;
969 s_chan = &spu.s_chan[ch];
970 work->ch[ch].spos = s_chan->spos;
971 work->ch[ch].sbpos = s_chan->iSBPos;
972 work->ch[ch].sinc = s_chan->sinc;
973 work->ch[ch].adsr = s_chan->ADSRX;
974 work->ch[ch].vol_l = s_chan->iLeftVolume;
975 work->ch[ch].vol_r = s_chan->iRightVolume;
976 work->ch[ch].start = s_chan->pCurr - spu.spuMemC;
977 work->ch[ch].loop = s_chan->pLoop - spu.spuMemC;
978 work->ch[ch].bNoise = s_chan->bNoise;
979 work->ch[ch].bFMod = s_chan->bFMod;
980 work->ch[ch].bRVBActive = s_chan->bRVBActive;
981 work->ch[ch].bStarting = s_chan->bStarting;
982 if (s_chan->prevflags & 1)
983 work->ch[ch].start = work->ch[ch].loop;
985 if (unlikely(s_chan->bFMod == 2))
987 // sucks, have to do double work
988 assert(!s_chan->bNoise);
989 d = do_samples_gauss(tmpFMod, decode_block, NULL, ch, ns_to,
990 &spu.sb[ch], s_chan->sinc, &s_chan->spos, &s_chan->iSBPos);
991 if (!s_chan->bStarting) {
992 d = MixADSR(tmpFMod, &s_chan->ADSRX, d);
994 spu.dwChannelsAudible &= ~(1 << ch);
995 s_chan->ADSRX.State = ADSR_RELEASE;
996 s_chan->ADSRX.EnvelopeVol = 0;
999 memset(&tmpFMod[d], 0, (ns_to - d) * sizeof(tmpFMod[d]));
1000 work->ch[ch].ns_to = d;
1003 if (unlikely(s_chan->bFMod))
1004 d = do_samples_skip_fmod(ch, ns_to, tmpFMod);
1006 d = do_samples_skip(ch, ns_to);
1007 work->ch[ch].ns_to = d;
1009 if (!s_chan->bStarting) {
1010 // note: d is not accurate on skip
1011 d = SkipADSR(&s_chan->ADSRX, d);
1013 spu.dwChannelsAudible &= ~(1 << ch);
1014 s_chan->ADSRX.State = ADSR_RELEASE;
1015 s_chan->ADSRX.EnvelopeVol = 0;
1021 if (spu.rvb->StartAddr) {
1022 if (spu_config.iUseReverb)
1023 work->rvb_addr = spu.rvb->CurrAddr;
1025 spu.rvb->CurrAddr += ns_to / 2;
1026 while (spu.rvb->CurrAddr >= 0x40000)
1027 spu.rvb->CurrAddr -= 0x40000 - spu.rvb->StartAddr;
1031 thread_work_start();
1034 static void do_channel_work(struct work_item *work)
1040 ns_to = work->ns_to;
1042 if (unlikely(spu.interpolation != spu_config.iUseInterpolation))
1044 spu.interpolation = spu_config.iUseInterpolation;
1045 mask = work->channels_on;
1046 for (ch = 0; mask != 0; ch++, mask >>= 1)
1048 ResetInterpolation(&spu.sb_thread[ch]);
1052 memset(RVB, 0, ns_to * sizeof(RVB[0]) * 2);
1054 mask = work->channels_new;
1055 for (ch = 0; mask != 0; ch++, mask >>= 1) {
1057 StartSoundSB(&spu.sb_thread[ch]);
1060 mask = work->channels_on;
1061 for (ch = 0; mask != 0; ch++, mask >>= 1)
1063 if (!(mask & 1)) continue;
1065 d = work->ch[ch].ns_to;
1066 spos = work->ch[ch].spos;
1067 sbpos = work->ch[ch].sbpos;
1069 if (work->ch[ch].bNoise)
1070 do_lsfr_samples(ChanBuf, d, work->ctrl, &spu.dwNoiseCount, &spu.dwNoiseVal);
1072 do_samples_adpcm(ChanBuf, decode_block_work, work, ch, d, work->ch[ch].bFMod,
1073 &spu.sb_thread[ch], work->ch[ch].sinc, &spos, &sbpos);
1075 d = MixADSR(ChanBuf, &work->ch[ch].adsr, d);
1077 work->ch[ch].adsr.EnvelopeVol = 0;
1078 memset(&ChanBuf[d], 0, (ns_to - d) * sizeof(ChanBuf[0]));
1081 if (ch == 1 || ch == 3)
1082 do_decode_bufs(spu.spuMem, ch/2, ns_to, work->decode_pos);
1084 if (work->ch[ch].bFMod == 2) // fmod freq channel
1085 memcpy(iFMod, &ChanBuf, ns_to * sizeof(iFMod[0]));
1086 if (work->ch[ch].bRVBActive && work->rvb_addr)
1087 mix_chan_rvb(work->SSumLR, ns_to,
1088 work->ch[ch].vol_l, work->ch[ch].vol_r, RVB);
1090 mix_chan(work->SSumLR, ns_to, work->ch[ch].vol_l, work->ch[ch].vol_r);
1094 REVERBDo(work->SSumLR, RVB, ns_to, work->rvb_addr);
1097 static void sync_worker_thread(int force)
1099 struct work_item *work;
1100 int done, used_space;
1102 // rvb offsets will change, thread may be using them
1103 force |= spu.rvb->dirty && spu.rvb->StartAddr;
1105 done = thread_get_i_done() - worker->i_reaped;
1106 used_space = worker->i_ready - worker->i_reaped;
1108 //printf("done: %d use: %d dsp: %u/%u\n", done, used_space,
1109 // worker->boot_cnt, worker->i_done);
1111 while ((force && used_space > 0) || used_space >= WORK_MAXCNT || done > 0) {
1112 work = &worker->i[worker->i_reaped & WORK_I_MASK];
1113 thread_work_wait_sync(work, force);
1115 MixXA(work->SSumLR, RVB, work->ns_to, work->decode_pos);
1116 do_samples_finish(work->SSumLR, work->ns_to,
1117 work->channels_silent, work->decode_pos);
1120 done = thread_get_i_done() - worker->i_reaped;
1121 used_space = worker->i_ready - worker->i_reaped;
1124 thread_sync_caches();
1129 static void queue_channel_work(int ns_to, int silentch) {}
1130 static void sync_worker_thread(int force) {}
1132 static const void * const worker = NULL;
1134 #endif // P_HAVE_PTHREAD || defined(WANT_THREAD_CODE)
1136 ////////////////////////////////////////////////////////////////////////
1137 // MAIN SPU FUNCTION
1138 // here is the main job handler...
1139 ////////////////////////////////////////////////////////////////////////
1141 void do_samples(unsigned int cycles_to, int do_direct)
1143 unsigned int silentch;
1147 cycle_diff = cycles_to - spu.cycles_played;
1148 if (cycle_diff < -2*1048576 || cycle_diff > 2*1048576)
1150 //xprintf("desync %u %d\n", cycles_to, cycle_diff);
1151 spu.cycles_played = cycles_to;
1155 silentch = ~(spu.dwChannelsAudible | spu.dwNewChannel) & 0xffffff;
1157 do_direct |= (silentch == 0xffffff);
1159 sync_worker_thread(do_direct);
1161 if (cycle_diff < 2 * 768)
1164 ns_to = (cycle_diff / 768 + 1) & ~1;
1165 if (ns_to > NSSIZE) {
1166 // should never happen
1167 //xprintf("ns_to oflow %d %d\n", ns_to, NSSIZE);
1171 //////////////////////////////////////////////////////
1172 // special irq handling in the decode buffers (0x0000-0x1000)
1174 // the decode buffers are located in spu memory in the following way:
1175 // 0x0000-0x03ff CD audio left
1176 // 0x0400-0x07ff CD audio right
1177 // 0x0800-0x0bff Voice 1
1178 // 0x0c00-0x0fff Voice 3
1179 // and decoded data is 16 bit for one sample
1181 // even if voices 1/3 are off or no cd audio is playing, the internal
1182 // play positions will move on and wrap after 0x400 bytes.
1183 // Therefore: we just need a pointer from spumem+0 to spumem+3ff, and
1184 // increase this pointer on each sample by 2 bytes. If this pointer
1185 // (or 0x400 offsets of this pointer) hits the spuirq address, we generate
1188 if (unlikely((spu.spuCtrl & CTRL_IRQ)
1189 && spu.pSpuIrq < spu.spuMemC+0x1000))
1191 int irq_pos = (spu.pSpuIrq - spu.spuMemC) / 2 & 0x1ff;
1192 int left = (irq_pos - spu.decode_pos) & 0x1ff;
1193 if (0 < left && left <= ns_to)
1195 //xprintf("decoder irq %x\n", spu.decode_pos);
1199 if (!spu.cycles_dma_end || (int)(spu.cycles_dma_end - cycles_to) < 0) {
1200 spu.cycles_dma_end = 0;
1201 check_irq_io(spu.spuAddr);
1204 if (unlikely(spu.rvb->dirty))
1207 if (do_direct || worker == NULL || !spu_config.iUseThread) {
1209 do_samples_finish(spu.SSumLR, ns_to, silentch, spu.decode_pos);
1212 queue_channel_work(ns_to, silentch);
1213 //sync_worker_thread(1); // uncomment for debug
1216 // advance "stopped" channels that can cause irqs
1217 // (all chans are always playing on the real thing..)
1218 if (spu.spuCtrl & CTRL_IRQ)
1219 do_silent_chans(ns_to, silentch);
1221 spu.cycles_played += ns_to * 768;
1222 spu.decode_pos = (spu.decode_pos + ns_to) & 0x1ff;
1224 static int ccount; static time_t ctime; ccount++;
1225 if (time(NULL) != ctime)
1226 { printf("%d\n", ccount); ccount = 0; ctime = time(NULL); }
1230 static void do_samples_finish(int *SSumLR, int ns_to,
1231 int silentch, int decode_pos)
1233 int vol_l = ((int)regAreaGet(H_SPUmvolL) << 17) >> 17;
1234 int vol_r = ((int)regAreaGet(H_SPUmvolR) << 17) >> 17;
1238 // must clear silent channel decode buffers
1239 if(unlikely(silentch & spu.decode_dirty_ch & (1<<1)))
1241 memset(&spu.spuMem[0x800/2], 0, 0x400);
1242 spu.decode_dirty_ch &= ~(1<<1);
1244 if(unlikely(silentch & spu.decode_dirty_ch & (1<<3)))
1246 memset(&spu.spuMem[0xc00/2], 0, 0x400);
1247 spu.decode_dirty_ch &= ~(1<<3);
1250 vol_l = vol_l * spu_config.iVolume >> 10;
1251 vol_r = vol_r * spu_config.iVolume >> 10;
1253 if (!(vol_l | vol_r))
1256 memset(spu.pS, 0, ns_to * 2 * sizeof(spu.pS[0]));
1257 memset(SSumLR, 0, ns_to * 2 * sizeof(SSumLR[0]));
1258 spu.pS += ns_to * 2;
1261 for (ns = 0; ns < ns_to * 2; )
1263 d = SSumLR[ns]; SSumLR[ns] = 0;
1264 d = d * vol_l >> 14;
1269 d = SSumLR[ns]; SSumLR[ns] = 0;
1270 d = d * vol_r >> 14;
1277 void schedule_next_irq(void)
1279 unsigned int upd_samples;
1282 if (spu.scheduleCallback == NULL)
1285 upd_samples = 44100 / 50;
1287 for (ch = 0; ch < MAXCHAN; ch++)
1289 if (spu.dwChannelDead & (1 << ch))
1291 if ((unsigned long)(spu.pSpuIrq - spu.s_chan[ch].pCurr) > IRQ_NEAR_BLOCKS * 16
1292 && (unsigned long)(spu.pSpuIrq - spu.s_chan[ch].pLoop) > IRQ_NEAR_BLOCKS * 16)
1294 if (spu.s_chan[ch].sinc == 0)
1297 scan_for_irq(ch, &upd_samples);
1300 if (unlikely(spu.pSpuIrq < spu.spuMemC + 0x1000))
1302 int irq_pos = (spu.pSpuIrq - spu.spuMemC) / 2 & 0x1ff;
1303 int left = (irq_pos - spu.decode_pos) & 0x1ff;
1304 if (0 < left && left < upd_samples) {
1305 //xprintf("decode: %3d (%3d/%3d)\n", left, spu.decode_pos, irq_pos);
1310 if (upd_samples < 44100 / 50)
1311 spu.scheduleCallback(upd_samples * 768);
1314 // SPU ASYNC... even newer epsxe func
1315 // 1 time every 'cycle' cycles... harhar
1317 // rearmed: called dynamically now
1319 void CALLBACK SPUasync(unsigned int cycle, unsigned int flags)
1321 do_samples(cycle, 0);
1323 if (spu.spuCtrl & CTRL_IRQ)
1324 schedule_next_irq();
1327 out_current->feed(spu.pSpuBuffer, (unsigned char *)spu.pS - spu.pSpuBuffer);
1328 spu.pS = (short *)spu.pSpuBuffer;
1330 if (spu_config.iTempo) {
1331 if (!out_current->busy())
1332 // cause more samples to be generated
1333 // (and break some games because of bad sync)
1334 spu.cycles_played -= 44100 / 60 / 2 * 768;
1339 // SPU UPDATE... new epsxe func
1340 // 1 time every 32 hsync lines
1341 // (312/32)x50 in pal
1342 // (262/32)x60 in ntsc
1344 // since epsxe 1.5.2 (linux) uses SPUupdate, not SPUasync, I will
1345 // leave that func in the linux port, until epsxe linux is using
1346 // the async function as well
1348 void CALLBACK SPUupdate(void)
1354 void CALLBACK SPUplayADPCMchannel(xa_decode_t *xap, unsigned int cycle, int unused)
1357 if(!xap->freq) return; // no xa freq ? bye
1359 if (spu.XAPlay == spu.XAFeed)
1360 do_samples(cycle, 1); // catch up to prevent source underflows later
1362 FeedXA(xap); // call main XA feeder
1363 spu.xapGlobal = xap; // store info for save states
1367 int CALLBACK SPUplayCDDAchannel(short *pcm, int nbytes, unsigned int cycle, int unused)
1369 if (!pcm) return -1;
1370 if (nbytes<=0) return -1;
1372 if (spu.CDDAPlay == spu.CDDAFeed)
1373 do_samples(cycle, 1); // catch up to prevent source underflows later
1375 FeedCDDA((unsigned char *)pcm, nbytes);
1379 // to be called after state load
1380 void ClearWorkingState(void)
1382 memset(iFMod, 0, sizeof(iFMod));
1383 spu.pS=(short *)spu.pSpuBuffer; // setup soundbuffer pointer
1386 // SETUPSTREAMS: init most of the spu buffers
1387 static void SetupStreams(void)
1389 spu.pSpuBuffer = (unsigned char *)malloc(32768); // alloc mixing buffer
1390 spu.SSumLR = calloc(NSSIZE * 2, sizeof(spu.SSumLR[0]));
1392 spu.XAStart = malloc(44100 * sizeof(uint32_t)); // alloc xa buffer
1393 spu.XAEnd = spu.XAStart + 44100;
1394 spu.XAPlay = spu.XAStart;
1395 spu.XAFeed = spu.XAStart;
1397 spu.CDDAStart = malloc(CDDA_BUFFER_SIZE); // alloc cdda buffer
1398 spu.CDDAEnd = spu.CDDAStart + CDDA_BUFFER_SIZE / sizeof(uint32_t);
1399 spu.CDDAPlay = spu.CDDAStart;
1400 spu.CDDAFeed = spu.CDDAStart;
1402 ClearWorkingState();
1405 // REMOVESTREAMS: free most buffer
1406 static void RemoveStreams(void)
1408 free(spu.pSpuBuffer); // free mixing buffer
1409 spu.pSpuBuffer = NULL;
1412 free(spu.XAStart); // free XA buffer
1414 free(spu.CDDAStart); // free CDDA buffer
1415 spu.CDDAStart = NULL;
1418 #if defined(C64X_DSP)
1420 /* special code for TI C64x DSP */
1421 #include "spu_c64x.c"
1423 #elif P_HAVE_PTHREAD
1425 #include <pthread.h>
1426 #include <semaphore.h>
1435 /* generic pthread implementation */
1437 static void thread_work_start(void)
1439 sem_post(&t.sem_avail);
1442 static void thread_work_wait_sync(struct work_item *work, int force)
1444 sem_wait(&t.sem_done);
1447 static int thread_get_i_done(void)
1449 return worker->i_done;
1452 static void thread_sync_caches(void)
1456 static void *spu_worker_thread(void *unused)
1458 struct work_item *work;
1461 sem_wait(&t.sem_avail);
1462 if (worker->exit_thread)
1465 work = &worker->i[worker->i_done & WORK_I_MASK];
1466 do_channel_work(work);
1469 sem_post(&t.sem_done);
1475 static void init_spu_thread(void)
1479 if (sysconf(_SC_NPROCESSORS_ONLN) <= 1)
1482 worker = calloc(1, sizeof(*worker));
1485 ret = sem_init(&t.sem_avail, 0, 0);
1487 goto fail_sem_avail;
1488 ret = sem_init(&t.sem_done, 0, 0);
1492 ret = pthread_create(&t.thread, NULL, spu_worker_thread, NULL);
1496 spu_config.iThreadAvail = 1;
1500 sem_destroy(&t.sem_done);
1502 sem_destroy(&t.sem_avail);
1506 spu_config.iThreadAvail = 0;
1509 static void exit_spu_thread(void)
1513 worker->exit_thread = 1;
1514 sem_post(&t.sem_avail);
1515 pthread_join(t.thread, NULL);
1516 sem_destroy(&t.sem_done);
1517 sem_destroy(&t.sem_avail);
1522 #else // if !P_HAVE_PTHREAD
1524 static void init_spu_thread(void)
1528 static void exit_spu_thread(void)
1534 // SPUINIT: this func will be called first by the main emu
1535 long CALLBACK SPUinit(void)
1539 memset(&spu, 0, sizeof(spu));
1540 spu.spuMemC = calloc(1, 512 * 1024);
1543 spu.s_chan = calloc(MAXCHAN+1, sizeof(spu.s_chan[0])); // channel + 1 infos (1 is security for fmod handling)
1544 spu.rvb = calloc(1, sizeof(REVERBInfo));
1548 spu.pSpuIrq = spu.spuMemC;
1550 SetupStreams(); // prepare streaming
1552 if (spu_config.iVolume == 0)
1553 spu_config.iVolume = 768; // 1024 is 1.0
1557 for (i = 0; i < MAXCHAN; i++) // loop sound channels
1559 spu.s_chan[i].ADSRX.SustainLevel = 0xf; // -> init sustain
1560 spu.s_chan[i].ADSRX.SustainIncrease = 1;
1561 spu.s_chan[i].pLoop = spu.spuMemC;
1562 spu.s_chan[i].pCurr = spu.spuMemC;
1563 spu.s_chan[i].bIgnoreLoop = 0;
1566 spu.bSpuInit=1; // flag: we are inited
1571 // SPUOPEN: called by main emu after init
1572 long CALLBACK SPUopen(void)
1574 if (spu.bSPUIsOpen) return 0; // security for some stupid main emus
1576 SetupSound(); // setup sound (before init!)
1580 return PSE_SPU_ERR_SUCCESS;
1583 // SPUCLOSE: called before shutdown
1584 long CALLBACK SPUclose(void)
1586 if (!spu.bSPUIsOpen) return 0; // some security
1588 spu.bSPUIsOpen = 0; // no more open
1590 out_current->finish(); // no more sound handling
1595 // SPUSHUTDOWN: called by main emu on final exit
1596 long CALLBACK SPUshutdown(void)
1609 RemoveStreams(); // no more streaming
1616 // this functions will be called once,
1617 // passes a callback that should be called on SPU-IRQ/cdda volume change
1618 void CALLBACK SPUregisterCallback(void (CALLBACK *callback)(int))
1620 spu.irqCallback = callback;
1623 void CALLBACK SPUregisterCDDAVolume(void (CALLBACK *CDDAVcallback)(short, short))
1625 //spu.cddavCallback = CDDAVcallback;
1628 void CALLBACK SPUregisterScheduleCb(void (CALLBACK *callback)(unsigned int))
1630 spu.scheduleCallback = callback;
1633 // COMMON PLUGIN INFO FUNCS
1635 char * CALLBACK PSEgetLibName(void)
1637 return _(libraryName);
1640 unsigned long CALLBACK PSEgetLibType(void)
1645 unsigned long CALLBACK PSEgetLibVersion(void)
1647 return (1 << 16) | (6 << 8);
1650 char * SPUgetLibInfos(void)
1652 return _(libraryInfo);
1657 void spu_get_debug_info(int *chans_out, int *run_chans, int *fmod_chans_out, int *noise_chans_out)
1659 int ch = 0, fmod_chans = 0, noise_chans = 0, irq_chans = 0;
1661 if (spu.s_chan == NULL)
1664 for(;ch<MAXCHAN;ch++)
1666 if (!(spu.dwChannelsAudible & (1<<ch)))
1668 if (spu.s_chan[ch].bFMod == 2)
1669 fmod_chans |= 1 << ch;
1670 if (spu.s_chan[ch].bNoise)
1671 noise_chans |= 1 << ch;
1672 if((spu.spuCtrl&CTRL_IRQ) && spu.s_chan[ch].pCurr <= spu.pSpuIrq && spu.s_chan[ch].pLoop <= spu.pSpuIrq)
1673 irq_chans |= 1 << ch;
1676 *chans_out = spu.dwChannelsAudible;
1677 *run_chans = ~spu.dwChannelsAudible & ~spu.dwChannelDead & irq_chans;
1678 *fmod_chans_out = fmod_chans;
1679 *noise_chans_out = noise_chans;
1682 // vim:shiftwidth=1:expandtab