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 ***************************************************************************/
25 #include "externals.h"
26 #include "registers.h"
28 #include "spu_config.h"
31 #include "arm_features.h"
35 #define ssat32_to_16(v) \
36 asm("ssat %0,#16,%1" : "=r" (v) : "r" (v))
38 #define ssat32_to_16(v) do { \
39 if (v < -32768) v = -32768; \
40 else if (v > 32767) v = 32767; \
44 #define PSXCLK 33868800 /* 33.8688 MHz */
46 // intended to be ~1 frame
47 #define IRQ_NEAR_BLOCKS 32
50 #if defined (USEMACOSX)
51 static char * libraryName = N_("Mac OS X Sound");
52 #elif defined (USEALSA)
53 static char * libraryName = N_("ALSA Sound");
54 #elif defined (USEOSS)
55 static char * libraryName = N_("OSS Sound");
56 #elif defined (USESDL)
57 static char * libraryName = N_("SDL Sound");
58 #elif defined (USEPULSEAUDIO)
59 static char * libraryName = N_("PulseAudio Sound");
61 static char * libraryName = N_("NULL Sound");
64 static char * libraryInfo = N_("P.E.Op.S. Sound Driver V1.7\nCoded by Pete Bernert and the P.E.Op.S. team\n");
72 static int iFMod[NSSIZE];
73 static int RVB[NSSIZE * 2];
76 #define CDDA_BUFFER_SIZE (16384 * sizeof(uint32_t)) // must be power of 2
78 ////////////////////////////////////////////////////////////////////////
80 ////////////////////////////////////////////////////////////////////////
82 // dirty inline func includes
87 ////////////////////////////////////////////////////////////////////////
88 // helpers for simple interpolation
91 // easy interpolation on upsampling, no special filter, just "Pete's common sense" tm
93 // instead of having n equal sample values in a row like:
97 // we compare the current delta change with the next delta change.
99 // if curr_delta is positive,
101 // - and next delta is smaller (or changing direction):
105 // - and next delta significant (at least twice) bigger:
109 // - and next delta is nearly same:
114 // if curr_delta is negative,
116 // - and next delta is smaller (or changing direction):
120 // - and next delta significant (at least twice) bigger:
124 // - and next delta is nearly same:
129 static void InterpolateUp(sample_buf *sb, int sinc)
132 if (sb->sinc_old != sinc)
137 if(SB[32]==1) // flag == 1? calc step and set flag... and don't change the value in this pass
139 const int id1=SB[30]-SB[29]; // curr delta to next val
140 const int id2=SB[31]-SB[30]; // and next delta to next-next val :)
144 if(id1>0) // curr delta positive
147 {SB[28]=id1;SB[32]=2;}
150 SB[28]=(id1*sinc)>>16;
152 SB[28]=(id1*sinc)>>17;
154 else // curr delta negative
157 {SB[28]=id1;SB[32]=2;}
160 SB[28]=(id1*sinc)>>16;
162 SB[28]=(id1*sinc)>>17;
166 if(SB[32]==2) // flag 1: calc step and set flag... and don't change the value in this pass
170 SB[28]=(SB[28]*sinc)>>17;
172 // SB[29]=SB[30]-(SB[28]*((0x10000/sinc)-1));
176 else // no flags? add bigger val (if possible), calc smaller step, set flag1
181 // even easier interpolation on downsampling, also no special filter, again just "Pete's common sense" tm
184 static void InterpolateDown(sample_buf *sb, int sinc)
187 if(sinc>=0x20000L) // we would skip at least one val?
189 SB[29]+=(SB[30]-SB[29])/2; // add easy weight
190 if(sinc>=0x30000L) // we would skip even more vals?
191 SB[29]+=(SB[31]-SB[30])/2; // add additional next weight
195 ////////////////////////////////////////////////////////////////////////
200 static void do_irq(void)
202 //if(!(spu.spuStat & STAT_IRQ))
204 spu.spuStat |= STAT_IRQ; // asserted status?
205 if(spu.irqCallback) spu.irqCallback();
209 static int check_irq(int ch, unsigned char *pos)
211 if((spu.spuCtrl & (CTRL_ON|CTRL_IRQ)) == (CTRL_ON|CTRL_IRQ) && pos == spu.pSpuIrq)
213 //printf("ch%d irq %04x\n", ch, pos - spu.spuMemC);
220 void check_irq_io(unsigned int addr)
222 unsigned int irq_addr = regAreaGet(H_SPUirqAddr) << 3;
224 if((spu.spuCtrl & (CTRL_ON|CTRL_IRQ)) == (CTRL_ON|CTRL_IRQ) && addr == irq_addr)
226 //printf("io irq %04x\n", irq_addr);
231 ////////////////////////////////////////////////////////////////////////
232 // START SOUND... called by main thread to setup a new sound on a channel
233 ////////////////////////////////////////////////////////////////////////
235 static void ResetInterpolation(sample_buf *sb)
237 memset(&sb->interp, 0, sizeof(sb->interp));
241 static void StartSoundSB(sample_buf *sb)
243 sb->SB[26] = 0; // init mixing vars
245 ResetInterpolation(sb);
248 static void StartSoundMain(int ch)
250 SPUCHAN *s_chan = &spu.s_chan[ch];
255 s_chan->prevflags = 2;
258 s_chan->bStarting = 1;
260 s_chan->pCurr = spu.spuMemC + ((regAreaGetCh(ch, 6) & ~1) << 3);
262 spu.dwNewChannel&=~(1<<ch); // clear new channel bit
263 spu.dwChannelDead&=~(1<<ch);
264 spu.dwChannelsAudible|=1<<ch;
267 static void StartSound(int ch)
270 StartSoundSB(&spu.sb[ch]);
273 ////////////////////////////////////////////////////////////////////////
274 // ALL KIND OF HELPERS
275 ////////////////////////////////////////////////////////////////////////
277 INLINE int FModChangeFrequency(int pitch, int ns)
279 pitch = (signed short)pitch;
280 pitch = ((32768 + iFMod[ns]) * pitch) >> 15;
290 INLINE void StoreInterpolationGaussCubic(sample_buf *sb, int fa)
292 int gpos = sb->interp.gauss.pos & 3;
293 sb->interp.gauss.val[gpos++] = fa;
294 sb->interp.gauss.pos = gpos & 3;
297 #define gval(x) (int)sb->interp.gauss.val[(gpos + x) & 3]
299 INLINE int GetInterpolationCubic(const sample_buf *sb, int spos)
301 int gpos = sb->interp.gauss.pos;
302 int xd = (spos >> 1) + 1;
305 fa = gval(3) - 3*gval(2) + 3*gval(1) - gval(0);
306 fa *= (xd - (2<<15)) / 6;
308 fa += gval(2) - gval(1) - gval(1) + gval(0);
309 fa *= (xd - (1<<15)) >> 1;
311 fa += gval(1) - gval(0);
318 INLINE int GetInterpolationGauss(const sample_buf *sb, int spos)
320 int gpos = sb->interp.gauss.pos;
321 int vl = (spos >> 6) & ~3;
323 vr = (gauss[vl+0] * gval(0)) >> 15;
324 vr += (gauss[vl+1] * gval(1)) >> 15;
325 vr += (gauss[vl+2] * gval(2)) >> 15;
326 vr += (gauss[vl+3] * gval(3)) >> 15;
330 static void decode_block_data(int *dest, const unsigned char *src, int predict_nr, int shift_factor)
332 static const int f[16][2] = {
340 int fa, s_1, s_2, d, s;
345 for (nSample = 0; nSample < 28; src++)
348 s = (int)(signed short)((d & 0x0f) << 12);
350 fa = s >> shift_factor;
351 fa += ((s_1 * f[predict_nr][0])>>6) + ((s_2 * f[predict_nr][1])>>6);
355 dest[nSample++] = fa;
357 s = (int)(signed short)((d & 0xf0) << 8);
358 fa = s >> shift_factor;
359 fa += ((s_1 * f[predict_nr][0])>>6) + ((s_2 * f[predict_nr][1])>>6);
363 dest[nSample++] = fa;
367 static int decode_block(void *unused, int ch, int *SB)
369 SPUCHAN *s_chan = &spu.s_chan[ch];
370 unsigned char *start;
371 int predict_nr, shift_factor, flags;
374 start = s_chan->pCurr; // set up the current pos
375 if (start - spu.spuMemC < 0x1000) { // ?
376 //log_unhandled("ch%02d plays decode bufs @%05lx\n",
377 // ch, (long)(start - spu.spuMemC));
381 if (s_chan->prevflags & 1) // 1: stop/loop
383 if (!(s_chan->prevflags & 2))
386 start = s_chan->pLoop;
389 check_irq(ch, start);
391 predict_nr = start[0];
392 shift_factor = predict_nr & 0xf;
395 decode_block_data(SB, start + 2, predict_nr, shift_factor);
398 if (flags & 4 && !s_chan->bIgnoreLoop)
399 s_chan->pLoop = start; // loop adress
403 s_chan->pCurr = start; // store values for next cycle
404 s_chan->prevflags = flags;
405 s_chan->bStarting = 0;
410 // do block, but ignore sample data
411 static int skip_block(int ch)
413 SPUCHAN *s_chan = &spu.s_chan[ch];
414 unsigned char *start = s_chan->pCurr;
418 if (s_chan->prevflags & 1) {
419 if (!(s_chan->prevflags & 2))
422 start = s_chan->pLoop;
425 check_irq(ch, start);
428 if (flags & 4 && !s_chan->bIgnoreLoop)
429 s_chan->pLoop = start;
433 s_chan->pCurr = start;
434 s_chan->prevflags = flags;
435 s_chan->bStarting = 0;
440 // if irq is going to trigger sooner than in upd_samples, set upd_samples
441 static void scan_for_irq(int ch, unsigned int *upd_samples)
443 SPUCHAN *s_chan = &spu.s_chan[ch];
444 int pos, sinc, sinc_inv, end;
445 unsigned char *block;
448 block = s_chan->pCurr;
451 end = pos + *upd_samples * sinc;
452 if (s_chan->prevflags & 1) // 1: stop/loop
453 block = s_chan->pLoop;
455 pos += (28 - s_chan->iSBPos) << 16;
458 if (block == spu.pSpuIrq)
462 if (flags & 1) { // 1: stop/loop
463 block = s_chan->pLoop;
470 sinc_inv = s_chan->sinc_inv;
472 sinc_inv = s_chan->sinc_inv = (0x80000000u / (uint32_t)sinc) << 1;
475 *upd_samples = (((uint64_t)pos * sinc_inv) >> 32) + 1;
476 //xprintf("ch%02d: irq sched: %3d %03d\n",
477 // ch, *upd_samples, *upd_samples * 60 * 263 / 44100);
481 #define make_do_samples(name, fmod_code, interp_start, interp_store, interp_get, interp_end) \
482 static noinline int name( \
483 int (*decode_f)(void *context, int ch, int *SB), void *ctx, \
484 int ch, int ns_to, sample_buf *sb, int sinc, int *spos, int *sbpos) \
490 for (ns = 0; ns < ns_to; ns++) \
495 while (*spos >= 0x10000) \
497 fa = sb->SB[(*sbpos)++]; \
501 d = decode_f(ctx, ch, sb->SB); \
518 // helpers for simple linear interpolation: delay real val for two slots,
519 // and calc the two deltas, for a 'look at the future behaviour'
520 #define simple_interp_store \
522 sb->SB[29] = sb->SB[30]; \
523 sb->SB[30] = sb->SB[31]; \
527 #define simple_interp_get \
528 if(sinc<0x10000) /* -> upsampling? */ \
529 InterpolateUp(sb, sinc); /* --> interpolate up */ \
530 else InterpolateDown(sb, sinc); /* --> else down */ \
531 ChanBuf[ns] = sb->SB[29]
533 make_do_samples(do_samples_nointerp, , fa = sb->SB[29],
534 , ChanBuf[ns] = fa, sb->SB[29] = fa)
535 make_do_samples(do_samples_simple, , ,
536 simple_interp_store, simple_interp_get, )
537 make_do_samples(do_samples_gauss, , ,
538 StoreInterpolationGaussCubic(sb, fa),
539 ChanBuf[ns] = GetInterpolationGauss(sb, *spos), )
540 make_do_samples(do_samples_cubic, , ,
541 StoreInterpolationGaussCubic(sb, fa),
542 ChanBuf[ns] = GetInterpolationCubic(sb, *spos), )
543 make_do_samples(do_samples_fmod,
544 sinc = FModChangeFrequency(spu.s_chan[ch].iRawPitch, ns), ,
545 StoreInterpolationGaussCubic(sb, fa),
546 ChanBuf[ns] = GetInterpolationGauss(sb, *spos), )
548 INLINE int do_samples_adpcm(
549 int (*decode_f)(void *context, int ch, int *SB), void *ctx,
550 int ch, int ns_to, int fmod, sample_buf *sb, int sinc, int *spos, int *sbpos)
552 int interp = spu.interpolation;
554 return do_samples_fmod(decode_f, ctx, ch, ns_to, sb, sinc, spos, sbpos);
559 return do_samples_nointerp(decode_f, ctx, ch, ns_to, sb, sinc, spos, sbpos);
561 return do_samples_simple (decode_f, ctx, ch, ns_to, sb, sinc, spos, sbpos);
563 return do_samples_gauss (decode_f, ctx, ch, ns_to, sb, sinc, spos, sbpos);
565 return do_samples_cubic (decode_f, ctx, ch, ns_to, sb, sinc, spos, sbpos);
569 static int do_samples_skip(int ch, int ns_to)
571 SPUCHAN *s_chan = &spu.s_chan[ch];
572 int spos = s_chan->spos;
573 int sinc = s_chan->sinc;
574 int ret = ns_to, ns, d;
576 spos += s_chan->iSBPos << 16;
578 for (ns = 0; ns < ns_to; ns++)
581 while (spos >= 28*0x10000)
590 s_chan->iSBPos = spos >> 16;
591 s_chan->spos = spos & 0xffff;
596 static void do_lsfr_samples(int ns_to, int ctrl,
597 unsigned int *dwNoiseCount, unsigned int *dwNoiseVal)
599 unsigned int counter = *dwNoiseCount;
600 unsigned int val = *dwNoiseVal;
601 unsigned int level, shift, bit;
604 // modified from DrHell/shalma, no fraction
605 level = (ctrl >> 10) & 0x0f;
606 level = 0x8000 >> level;
608 for (ns = 0; ns < ns_to; ns++)
611 if (counter >= level)
614 shift = (val >> 10) & 0x1f;
615 bit = (0x69696969 >> shift) & 1;
616 bit ^= (val >> 15) & 1;
617 val = (val << 1) | bit;
620 ChanBuf[ns] = (signed short)val;
623 *dwNoiseCount = counter;
627 static int do_samples_noise(int ch, int ns_to)
631 ret = do_samples_skip(ch, ns_to);
633 do_lsfr_samples(ns_to, spu.spuCtrl, &spu.dwNoiseCount, &spu.dwNoiseVal);
639 // asm code; lv and rv must be 0-3fff
640 extern void mix_chan(int *SSumLR, int count, int lv, int rv);
641 extern void mix_chan_rvb(int *SSumLR, int count, int lv, int rv, int *rvb);
643 static void mix_chan(int *SSumLR, int count, int lv, int rv)
645 const int *src = ChanBuf;
652 l = (sval * lv) >> 14;
653 r = (sval * rv) >> 14;
659 static void mix_chan_rvb(int *SSumLR, int count, int lv, int rv, int *rvb)
661 const int *src = ChanBuf;
670 l = (sval * lv) >> 14;
671 r = (sval * rv) >> 14;
680 // 0x0800-0x0bff Voice 1
681 // 0x0c00-0x0fff Voice 3
682 static noinline void do_decode_bufs(unsigned short *mem, int which,
683 int count, int decode_pos)
685 unsigned short *dst = &mem[0x800/2 + which*0x400/2];
686 const int *src = ChanBuf;
687 int cursor = decode_pos;
692 dst[cursor] = *src++;
696 // decode_pos is updated and irqs are checked later, after voice loop
699 static void do_silent_chans(int ns_to, int silentch)
705 mask = silentch & 0xffffff;
706 for (ch = 0; mask != 0; ch++, mask >>= 1)
708 if (!(mask & 1)) continue;
709 if (spu.dwChannelDead & (1<<ch)) continue;
711 s_chan = &spu.s_chan[ch];
712 if (s_chan->pCurr > spu.pSpuIrq && s_chan->pLoop > spu.pSpuIrq)
715 s_chan->spos += s_chan->iSBPos << 16;
718 s_chan->spos += s_chan->sinc * ns_to;
719 while (s_chan->spos >= 28 * 0x10000)
721 unsigned char *start = s_chan->pCurr;
724 if (start == s_chan->pCurr || start - spu.spuMemC < 0x1000)
726 // looping on self or stopped(?)
727 spu.dwChannelDead |= 1<<ch;
732 s_chan->spos -= 28 * 0x10000;
737 static void do_channels(int ns_to)
743 if (unlikely(spu.interpolation != spu_config.iUseInterpolation))
745 spu.interpolation = spu_config.iUseInterpolation;
746 mask = spu.dwChannelsAudible & 0xffffff;
747 for (ch = 0; mask != 0; ch++, mask >>= 1)
749 ResetInterpolation(&spu.sb[ch]);
752 do_rvb = spu.rvb->StartAddr && spu_config.iUseReverb;
754 memset(RVB, 0, ns_to * sizeof(RVB[0]) * 2);
756 mask = spu.dwNewChannel & 0xffffff;
757 for (ch = 0; mask != 0; ch++, mask >>= 1) {
762 mask = spu.dwChannelsAudible & 0xffffff;
763 for (ch = 0; mask != 0; ch++, mask >>= 1) // loop em all...
765 if (!(mask & 1)) continue; // channel not playing? next
767 s_chan = &spu.s_chan[ch];
769 d = do_samples_noise(ch, ns_to);
771 d = do_samples_adpcm(decode_block, NULL, ch, ns_to, s_chan->bFMod,
772 &spu.sb[ch], s_chan->sinc, &s_chan->spos, &s_chan->iSBPos);
774 if (!s_chan->bStarting) {
775 d = MixADSR(&s_chan->ADSRX, d);
777 spu.dwChannelsAudible &= ~(1 << ch);
778 s_chan->ADSRX.State = ADSR_RELEASE;
779 s_chan->ADSRX.EnvelopeVol = 0;
780 memset(&ChanBuf[d], 0, (ns_to - d) * sizeof(ChanBuf[0]));
784 if (ch == 1 || ch == 3)
786 do_decode_bufs(spu.spuMem, ch/2, ns_to, spu.decode_pos);
787 spu.decode_dirty_ch |= 1 << ch;
790 if (s_chan->bFMod == 2) // fmod freq channel
791 memcpy(iFMod, &ChanBuf, ns_to * sizeof(iFMod[0]));
792 if (s_chan->bRVBActive && do_rvb)
793 mix_chan_rvb(spu.SSumLR, ns_to, s_chan->iLeftVolume, s_chan->iRightVolume, RVB);
795 mix_chan(spu.SSumLR, ns_to, s_chan->iLeftVolume, s_chan->iRightVolume);
798 MixXA(spu.SSumLR, RVB, ns_to, spu.decode_pos);
800 if (spu.rvb->StartAddr) {
802 REVERBDo(spu.SSumLR, RVB, ns_to, spu.rvb->CurrAddr);
804 spu.rvb->CurrAddr += ns_to / 2;
805 while (spu.rvb->CurrAddr >= 0x40000)
806 spu.rvb->CurrAddr -= 0x40000 - spu.rvb->StartAddr;
810 static void do_samples_finish(int *SSumLR, int ns_to,
811 int silentch, int decode_pos);
813 // optional worker thread handling
815 #if P_HAVE_PTHREAD || defined(WANT_THREAD_CODE)
817 // worker thread state
818 static struct spu_worker {
821 unsigned int exit_thread;
822 unsigned int i_ready;
823 unsigned int i_reaped;
824 unsigned int last_boot_cnt; // dsp
825 unsigned int ram_dirty;
827 // aligning for C64X_DSP
828 unsigned int _pad0[128/4];
833 unsigned int active; // dsp
834 unsigned int boot_cnt;
836 unsigned int _pad1[128/4];
843 unsigned int channels_new;
844 unsigned int channels_on;
845 unsigned int channels_silent;
854 unsigned short ns_to;
855 unsigned short bNoise:1;
856 unsigned short bFMod:2;
857 unsigned short bRVBActive:1;
860 int SSumLR[NSSIZE * 2];
864 #define WORK_MAXCNT (sizeof(worker->i) / sizeof(worker->i[0]))
865 #define WORK_I_MASK (WORK_MAXCNT - 1)
867 static void thread_work_start(void);
868 static void thread_work_wait_sync(struct work_item *work, int force);
869 static void thread_sync_caches(void);
870 static int thread_get_i_done(void);
872 static int decode_block_work(void *context, int ch, int *SB)
874 const unsigned char *ram = spu.spuMemC;
875 int predict_nr, shift_factor, flags;
876 struct work_item *work = context;
877 int start = work->ch[ch].start;
878 int loop = work->ch[ch].loop;
880 predict_nr = ram[start];
881 shift_factor = predict_nr & 0xf;
884 decode_block_data(SB, ram + start + 2, predict_nr, shift_factor);
886 flags = ram[start + 1];
888 loop = start; // loop adress
892 if (flags & 1) // 1: stop/loop
895 work->ch[ch].start = start & 0x7ffff;
896 work->ch[ch].loop = loop;
901 static void queue_channel_work(int ns_to, unsigned int silentch)
903 struct work_item *work;
908 work = &worker->i[worker->i_ready & WORK_I_MASK];
910 work->ctrl = spu.spuCtrl;
911 work->decode_pos = spu.decode_pos;
912 work->channels_silent = silentch;
914 mask = work->channels_new = spu.dwNewChannel & 0xffffff;
915 for (ch = 0; mask != 0; ch++, mask >>= 1) {
920 mask = work->channels_on = spu.dwChannelsAudible & 0xffffff;
921 spu.decode_dirty_ch |= mask & 0x0a;
923 for (ch = 0; mask != 0; ch++, mask >>= 1)
925 if (!(mask & 1)) continue;
927 s_chan = &spu.s_chan[ch];
928 work->ch[ch].spos = s_chan->spos;
929 work->ch[ch].sbpos = s_chan->iSBPos;
930 work->ch[ch].sinc = s_chan->sinc;
931 work->ch[ch].adsr = s_chan->ADSRX;
932 work->ch[ch].vol_l = s_chan->iLeftVolume;
933 work->ch[ch].vol_r = s_chan->iRightVolume;
934 work->ch[ch].start = s_chan->pCurr - spu.spuMemC;
935 work->ch[ch].loop = s_chan->pLoop - spu.spuMemC;
936 work->ch[ch].bNoise = s_chan->bNoise;
937 work->ch[ch].bFMod = s_chan->bFMod;
938 work->ch[ch].bRVBActive = s_chan->bRVBActive;
939 if (s_chan->prevflags & 1)
940 work->ch[ch].start = work->ch[ch].loop;
942 d = do_samples_skip(ch, ns_to);
943 work->ch[ch].ns_to = d;
945 if (!s_chan->bStarting) {
946 // note: d is not accurate on skip
947 d = SkipADSR(&s_chan->ADSRX, d);
949 spu.dwChannelsAudible &= ~(1 << ch);
950 s_chan->ADSRX.State = ADSR_RELEASE;
951 s_chan->ADSRX.EnvelopeVol = 0;
957 if (spu.rvb->StartAddr) {
958 if (spu_config.iUseReverb)
959 work->rvb_addr = spu.rvb->CurrAddr;
961 spu.rvb->CurrAddr += ns_to / 2;
962 while (spu.rvb->CurrAddr >= 0x40000)
963 spu.rvb->CurrAddr -= 0x40000 - spu.rvb->StartAddr;
970 static void do_channel_work(struct work_item *work)
978 if (unlikely(spu.interpolation != spu_config.iUseInterpolation))
980 spu.interpolation = spu_config.iUseInterpolation;
981 mask = spu.dwChannelsAudible & 0xffffff;
982 for (ch = 0; mask != 0; ch++, mask >>= 1)
984 ResetInterpolation(&spu.sb[ch]);
988 memset(RVB, 0, ns_to * sizeof(RVB[0]) * 2);
990 mask = work->channels_new;
991 for (ch = 0; mask != 0; ch++, mask >>= 1) {
993 StartSoundSB(&spu.sb[ch]);
996 mask = work->channels_on;
997 for (ch = 0; mask != 0; ch++, mask >>= 1)
999 if (!(mask & 1)) continue;
1001 d = work->ch[ch].ns_to;
1002 spos = work->ch[ch].spos;
1003 sbpos = work->ch[ch].sbpos;
1005 if (work->ch[ch].bNoise)
1006 do_lsfr_samples(d, work->ctrl, &spu.dwNoiseCount, &spu.dwNoiseVal);
1008 do_samples_adpcm(decode_block_work, work, ch, d, work->ch[ch].bFMod,
1009 &spu.sb[ch], work->ch[ch].sinc, &spos, &sbpos);
1011 d = MixADSR(&work->ch[ch].adsr, d);
1013 work->ch[ch].adsr.EnvelopeVol = 0;
1014 memset(&ChanBuf[d], 0, (ns_to - d) * sizeof(ChanBuf[0]));
1017 if (ch == 1 || ch == 3)
1018 do_decode_bufs(spu.spuMem, ch/2, ns_to, work->decode_pos);
1020 if (work->ch[ch].bFMod == 2) // fmod freq channel
1021 memcpy(iFMod, &ChanBuf, ns_to * sizeof(iFMod[0]));
1022 if (work->ch[ch].bRVBActive && work->rvb_addr)
1023 mix_chan_rvb(work->SSumLR, ns_to,
1024 work->ch[ch].vol_l, work->ch[ch].vol_r, RVB);
1026 mix_chan(work->SSumLR, ns_to, work->ch[ch].vol_l, work->ch[ch].vol_r);
1030 REVERBDo(work->SSumLR, RVB, ns_to, work->rvb_addr);
1033 static void sync_worker_thread(int force)
1035 struct work_item *work;
1036 int done, used_space;
1038 // rvb offsets will change, thread may be using them
1039 force |= spu.rvb->dirty && spu.rvb->StartAddr;
1041 done = thread_get_i_done() - worker->i_reaped;
1042 used_space = worker->i_ready - worker->i_reaped;
1044 //printf("done: %d use: %d dsp: %u/%u\n", done, used_space,
1045 // worker->boot_cnt, worker->i_done);
1047 while ((force && used_space > 0) || used_space >= WORK_MAXCNT || done > 0) {
1048 work = &worker->i[worker->i_reaped & WORK_I_MASK];
1049 thread_work_wait_sync(work, force);
1051 MixXA(work->SSumLR, RVB, work->ns_to, work->decode_pos);
1052 do_samples_finish(work->SSumLR, work->ns_to,
1053 work->channels_silent, work->decode_pos);
1056 done = thread_get_i_done() - worker->i_reaped;
1057 used_space = worker->i_ready - worker->i_reaped;
1060 thread_sync_caches();
1065 static void queue_channel_work(int ns_to, int silentch) {}
1066 static void sync_worker_thread(int force) {}
1068 static const void * const worker = NULL;
1070 #endif // P_HAVE_PTHREAD || defined(WANT_THREAD_CODE)
1072 ////////////////////////////////////////////////////////////////////////
1073 // MAIN SPU FUNCTION
1074 // here is the main job handler...
1075 ////////////////////////////////////////////////////////////////////////
1077 void do_samples(unsigned int cycles_to, int do_direct)
1079 unsigned int silentch;
1083 cycle_diff = cycles_to - spu.cycles_played;
1084 if (cycle_diff < -2*1048576 || cycle_diff > 2*1048576)
1086 //xprintf("desync %u %d\n", cycles_to, cycle_diff);
1087 spu.cycles_played = cycles_to;
1091 silentch = ~(spu.dwChannelsAudible | spu.dwNewChannel) & 0xffffff;
1093 do_direct |= (silentch == 0xffffff);
1095 sync_worker_thread(do_direct);
1097 if (cycle_diff < 2 * 768)
1100 ns_to = (cycle_diff / 768 + 1) & ~1;
1101 if (ns_to > NSSIZE) {
1102 // should never happen
1103 //xprintf("ns_to oflow %d %d\n", ns_to, NSSIZE);
1107 //////////////////////////////////////////////////////
1108 // special irq handling in the decode buffers (0x0000-0x1000)
1110 // the decode buffers are located in spu memory in the following way:
1111 // 0x0000-0x03ff CD audio left
1112 // 0x0400-0x07ff CD audio right
1113 // 0x0800-0x0bff Voice 1
1114 // 0x0c00-0x0fff Voice 3
1115 // and decoded data is 16 bit for one sample
1117 // even if voices 1/3 are off or no cd audio is playing, the internal
1118 // play positions will move on and wrap after 0x400 bytes.
1119 // Therefore: we just need a pointer from spumem+0 to spumem+3ff, and
1120 // increase this pointer on each sample by 2 bytes. If this pointer
1121 // (or 0x400 offsets of this pointer) hits the spuirq address, we generate
1124 if (unlikely((spu.spuCtrl & CTRL_IRQ)
1125 && spu.pSpuIrq < spu.spuMemC+0x1000))
1127 int irq_pos = (spu.pSpuIrq - spu.spuMemC) / 2 & 0x1ff;
1128 int left = (irq_pos - spu.decode_pos) & 0x1ff;
1129 if (0 < left && left <= ns_to)
1131 //xprintf("decoder irq %x\n", spu.decode_pos);
1135 if (!spu.cycles_dma_end || (int)(spu.cycles_dma_end - cycles_to) < 0) {
1136 spu.cycles_dma_end = 0;
1137 check_irq_io(spu.spuAddr);
1140 if (unlikely(spu.rvb->dirty))
1143 if (do_direct || worker == NULL || !spu_config.iUseThread) {
1145 do_samples_finish(spu.SSumLR, ns_to, silentch, spu.decode_pos);
1148 queue_channel_work(ns_to, silentch);
1149 //sync_worker_thread(1); // uncomment for debug
1152 // advance "stopped" channels that can cause irqs
1153 // (all chans are always playing on the real thing..)
1154 if (spu.spuCtrl & CTRL_IRQ)
1155 do_silent_chans(ns_to, silentch);
1157 spu.cycles_played += ns_to * 768;
1158 spu.decode_pos = (spu.decode_pos + ns_to) & 0x1ff;
1160 static int ccount; static time_t ctime; ccount++;
1161 if (time(NULL) != ctime)
1162 { printf("%d\n", ccount); ccount = 0; ctime = time(NULL); }
1166 static void do_samples_finish(int *SSumLR, int ns_to,
1167 int silentch, int decode_pos)
1169 int vol_l = ((int)regAreaGet(H_SPUmvolL) << 17) >> 17;
1170 int vol_r = ((int)regAreaGet(H_SPUmvolR) << 17) >> 17;
1174 // must clear silent channel decode buffers
1175 if(unlikely(silentch & spu.decode_dirty_ch & (1<<1)))
1177 memset(&spu.spuMem[0x800/2], 0, 0x400);
1178 spu.decode_dirty_ch &= ~(1<<1);
1180 if(unlikely(silentch & spu.decode_dirty_ch & (1<<3)))
1182 memset(&spu.spuMem[0xc00/2], 0, 0x400);
1183 spu.decode_dirty_ch &= ~(1<<3);
1186 vol_l = vol_l * spu_config.iVolume >> 10;
1187 vol_r = vol_r * spu_config.iVolume >> 10;
1189 if (!(spu.spuCtrl & CTRL_MUTE) || !(vol_l | vol_r))
1192 memset(spu.pS, 0, ns_to * 2 * sizeof(spu.pS[0]));
1193 memset(SSumLR, 0, ns_to * 2 * sizeof(SSumLR[0]));
1194 spu.pS += ns_to * 2;
1197 for (ns = 0; ns < ns_to * 2; )
1199 d = SSumLR[ns]; SSumLR[ns] = 0;
1200 d = d * vol_l >> 14;
1205 d = SSumLR[ns]; SSumLR[ns] = 0;
1206 d = d * vol_r >> 14;
1213 void schedule_next_irq(void)
1215 unsigned int upd_samples;
1218 if (spu.scheduleCallback == NULL)
1221 upd_samples = 44100 / 50;
1223 for (ch = 0; ch < MAXCHAN; ch++)
1225 if (spu.dwChannelDead & (1 << ch))
1227 if ((unsigned long)(spu.pSpuIrq - spu.s_chan[ch].pCurr) > IRQ_NEAR_BLOCKS * 16
1228 && (unsigned long)(spu.pSpuIrq - spu.s_chan[ch].pLoop) > IRQ_NEAR_BLOCKS * 16)
1230 if (spu.s_chan[ch].sinc == 0)
1233 scan_for_irq(ch, &upd_samples);
1236 if (unlikely(spu.pSpuIrq < spu.spuMemC + 0x1000))
1238 int irq_pos = (spu.pSpuIrq - spu.spuMemC) / 2 & 0x1ff;
1239 int left = (irq_pos - spu.decode_pos) & 0x1ff;
1240 if (0 < left && left < upd_samples) {
1241 //xprintf("decode: %3d (%3d/%3d)\n", left, spu.decode_pos, irq_pos);
1246 if (upd_samples < 44100 / 50)
1247 spu.scheduleCallback(upd_samples * 768);
1250 // SPU ASYNC... even newer epsxe func
1251 // 1 time every 'cycle' cycles... harhar
1253 // rearmed: called dynamically now
1255 void CALLBACK SPUasync(unsigned int cycle, unsigned int flags)
1257 do_samples(cycle, 0);
1259 if (spu.spuCtrl & CTRL_IRQ)
1260 schedule_next_irq();
1263 out_current->feed(spu.pSpuBuffer, (unsigned char *)spu.pS - spu.pSpuBuffer);
1264 spu.pS = (short *)spu.pSpuBuffer;
1266 if (spu_config.iTempo) {
1267 if (!out_current->busy())
1268 // cause more samples to be generated
1269 // (and break some games because of bad sync)
1270 spu.cycles_played -= 44100 / 60 / 2 * 768;
1275 // SPU UPDATE... new epsxe func
1276 // 1 time every 32 hsync lines
1277 // (312/32)x50 in pal
1278 // (262/32)x60 in ntsc
1280 // since epsxe 1.5.2 (linux) uses SPUupdate, not SPUasync, I will
1281 // leave that func in the linux port, until epsxe linux is using
1282 // the async function as well
1284 void CALLBACK SPUupdate(void)
1290 void CALLBACK SPUplayADPCMchannel(xa_decode_t *xap, unsigned int cycle, int is_start)
1293 if(!xap->freq) return; // no xa freq ? bye
1296 do_samples(cycle, 1); // catch up to prevent source underflows later
1298 FeedXA(xap); // call main XA feeder
1299 spu.xapGlobal = xap; // store info for save states
1303 int CALLBACK SPUplayCDDAchannel(short *pcm, int nbytes, unsigned int cycle, int is_start)
1305 if (!pcm) return -1;
1306 if (nbytes<=0) return -1;
1309 do_samples(cycle, 1); // catch up to prevent source underflows later
1311 FeedCDDA((unsigned char *)pcm, nbytes);
1315 // to be called after state load
1316 void ClearWorkingState(void)
1318 memset(iFMod, 0, sizeof(iFMod));
1319 spu.pS=(short *)spu.pSpuBuffer; // setup soundbuffer pointer
1322 // SETUPSTREAMS: init most of the spu buffers
1323 static void SetupStreams(void)
1325 spu.pSpuBuffer = (unsigned char *)malloc(32768); // alloc mixing buffer
1326 spu.SSumLR = calloc(NSSIZE * 2, sizeof(spu.SSumLR[0]));
1328 spu.XAStart = malloc(44100 * sizeof(uint32_t)); // alloc xa buffer
1329 spu.XAEnd = spu.XAStart + 44100;
1330 spu.XAPlay = spu.XAStart;
1331 spu.XAFeed = spu.XAStart;
1333 spu.CDDAStart = malloc(CDDA_BUFFER_SIZE); // alloc cdda buffer
1334 spu.CDDAEnd = spu.CDDAStart + CDDA_BUFFER_SIZE / sizeof(uint32_t);
1335 spu.CDDAPlay = spu.CDDAStart;
1336 spu.CDDAFeed = spu.CDDAStart;
1338 ClearWorkingState();
1341 // REMOVESTREAMS: free most buffer
1342 static void RemoveStreams(void)
1344 free(spu.pSpuBuffer); // free mixing buffer
1345 spu.pSpuBuffer = NULL;
1348 free(spu.XAStart); // free XA buffer
1350 free(spu.CDDAStart); // free CDDA buffer
1351 spu.CDDAStart = NULL;
1354 #if defined(C64X_DSP)
1356 /* special code for TI C64x DSP */
1357 #include "spu_c64x.c"
1359 #elif P_HAVE_PTHREAD
1361 #include <pthread.h>
1362 #include <semaphore.h>
1371 /* generic pthread implementation */
1373 static void thread_work_start(void)
1375 sem_post(&t.sem_avail);
1378 static void thread_work_wait_sync(struct work_item *work, int force)
1380 sem_wait(&t.sem_done);
1383 static int thread_get_i_done(void)
1385 return worker->i_done;
1388 static void thread_sync_caches(void)
1392 static void *spu_worker_thread(void *unused)
1394 struct work_item *work;
1397 sem_wait(&t.sem_avail);
1398 if (worker->exit_thread)
1401 work = &worker->i[worker->i_done & WORK_I_MASK];
1402 do_channel_work(work);
1405 sem_post(&t.sem_done);
1411 static void init_spu_thread(void)
1415 if (sysconf(_SC_NPROCESSORS_ONLN) <= 1)
1418 worker = calloc(1, sizeof(*worker));
1421 ret = sem_init(&t.sem_avail, 0, 0);
1423 goto fail_sem_avail;
1424 ret = sem_init(&t.sem_done, 0, 0);
1428 ret = pthread_create(&t.thread, NULL, spu_worker_thread, NULL);
1432 spu_config.iThreadAvail = 1;
1436 sem_destroy(&t.sem_done);
1438 sem_destroy(&t.sem_avail);
1442 spu_config.iThreadAvail = 0;
1445 static void exit_spu_thread(void)
1449 worker->exit_thread = 1;
1450 sem_post(&t.sem_avail);
1451 pthread_join(t.thread, NULL);
1452 sem_destroy(&t.sem_done);
1453 sem_destroy(&t.sem_avail);
1458 #else // if !P_HAVE_PTHREAD
1460 static void init_spu_thread(void)
1464 static void exit_spu_thread(void)
1470 // SPUINIT: this func will be called first by the main emu
1471 long CALLBACK SPUinit(void)
1475 memset(&spu, 0, sizeof(spu));
1476 spu.spuMemC = calloc(1, 512 * 1024);
1479 spu.s_chan = calloc(MAXCHAN+1, sizeof(spu.s_chan[0])); // channel + 1 infos (1 is security for fmod handling)
1480 spu.rvb = calloc(1, sizeof(REVERBInfo));
1484 spu.pSpuIrq = spu.spuMemC;
1486 SetupStreams(); // prepare streaming
1488 if (spu_config.iVolume == 0)
1489 spu_config.iVolume = 768; // 1024 is 1.0
1493 for (i = 0; i < MAXCHAN; i++) // loop sound channels
1495 spu.s_chan[i].ADSRX.SustainLevel = 0xf; // -> init sustain
1496 spu.s_chan[i].ADSRX.SustainIncrease = 1;
1497 spu.s_chan[i].pLoop = spu.spuMemC;
1498 spu.s_chan[i].pCurr = spu.spuMemC;
1499 spu.s_chan[i].bIgnoreLoop = 0;
1502 spu.bSpuInit=1; // flag: we are inited
1507 // SPUOPEN: called by main emu after init
1508 long CALLBACK SPUopen(void)
1510 if (spu.bSPUIsOpen) return 0; // security for some stupid main emus
1512 SetupSound(); // setup sound (before init!)
1516 return PSE_SPU_ERR_SUCCESS;
1519 // SPUCLOSE: called before shutdown
1520 long CALLBACK SPUclose(void)
1522 if (!spu.bSPUIsOpen) return 0; // some security
1524 spu.bSPUIsOpen = 0; // no more open
1526 out_current->finish(); // no more sound handling
1531 // SPUSHUTDOWN: called by main emu on final exit
1532 long CALLBACK SPUshutdown(void)
1545 RemoveStreams(); // no more streaming
1552 // this functions will be called once,
1553 // passes a callback that should be called on SPU-IRQ/cdda volume change
1554 void CALLBACK SPUregisterCallback(void (CALLBACK *callback)(void))
1556 spu.irqCallback = callback;
1559 void CALLBACK SPUregisterCDDAVolume(void (CALLBACK *CDDAVcallback)(short, short))
1561 spu.cddavCallback = CDDAVcallback;
1564 void CALLBACK SPUregisterScheduleCb(void (CALLBACK *callback)(unsigned int))
1566 spu.scheduleCallback = callback;
1569 // COMMON PLUGIN INFO FUNCS
1571 char * CALLBACK PSEgetLibName(void)
1573 return _(libraryName);
1576 unsigned long CALLBACK PSEgetLibType(void)
1581 unsigned long CALLBACK PSEgetLibVersion(void)
1583 return (1 << 16) | (6 << 8);
1586 char * SPUgetLibInfos(void)
1588 return _(libraryInfo);
1593 void spu_get_debug_info(int *chans_out, int *run_chans, int *fmod_chans_out, int *noise_chans_out)
1595 int ch = 0, fmod_chans = 0, noise_chans = 0, irq_chans = 0;
1597 if (spu.s_chan == NULL)
1600 for(;ch<MAXCHAN;ch++)
1602 if (!(spu.dwChannelsAudible & (1<<ch)))
1604 if (spu.s_chan[ch].bFMod == 2)
1605 fmod_chans |= 1 << ch;
1606 if (spu.s_chan[ch].bNoise)
1607 noise_chans |= 1 << ch;
1608 if((spu.spuCtrl&CTRL_IRQ) && spu.s_chan[ch].pCurr <= spu.pSpuIrq && spu.s_chan[ch].pLoop <= spu.pSpuIrq)
1609 irq_chans |= 1 << ch;
1612 *chans_out = spu.dwChannelsAudible;
1613 *run_chans = ~spu.dwChannelsAudible & ~spu.dwChannelDead & irq_chans;
1614 *fmod_chans_out = fmod_chans;
1615 *noise_chans_out = noise_chans;
1618 // vim:shiftwidth=1:expandtab