don't use a stack var out of scope
[pcsx_rearmed.git] / plugins / dfsound / spu.c
... / ...
CommitLineData
1/***************************************************************************
2 spu.c - description
3 -------------------
4 begin : Wed May 15 2002
5 copyright : (C) 2002 by Pete Bernert
6 email : BlackDove@addcom.de
7
8 Portions (C) GraÅžvydas "notaz" Ignotas, 2010-2012,2014,2015
9
10 ***************************************************************************/
11/***************************************************************************
12 * *
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. *
18 * *
19 ***************************************************************************/
20
21#include <assert.h>
22#include "stdafx.h"
23
24#define _IN_SPU
25
26#include "externals.h"
27#include "registers.h"
28#include "out.h"
29#include "spu_config.h"
30#include "spu.h"
31
32#ifdef __arm__
33#include "arm_features.h"
34#endif
35
36#ifdef HAVE_ARMV7
37 #define ssat32_to_16(v) \
38 asm("ssat %0,#16,%1" : "=r" (v) : "r" (v))
39#else
40 #define ssat32_to_16(v) do { \
41 if (v < -32768) v = -32768; \
42 else if (v > 32767) v = 32767; \
43 } while (0)
44#endif
45
46#define PSXCLK 33868800 /* 33.8688 MHz */
47
48// intended to be ~1 frame
49#define IRQ_NEAR_BLOCKS 32
50
51/*
52#if defined (USEMACOSX)
53static char * libraryName = N_("Mac OS X Sound");
54#elif defined (USEALSA)
55static char * libraryName = N_("ALSA Sound");
56#elif defined (USEOSS)
57static char * libraryName = N_("OSS Sound");
58#elif defined (USESDL)
59static char * libraryName = N_("SDL Sound");
60#elif defined (USEPULSEAUDIO)
61static char * libraryName = N_("PulseAudio Sound");
62#else
63static char * libraryName = N_("NULL Sound");
64#endif
65
66static char * libraryInfo = N_("P.E.Op.S. Sound Driver V1.7\nCoded by Pete Bernert and the P.E.Op.S. team\n");
67*/
68
69// globals
70
71SPUInfo spu;
72SPUConfig spu_config;
73
74static int iFMod[NSSIZE];
75static int RVB[NSSIZE * 2];
76int ChanBuf[NSSIZE];
77
78#define CDDA_BUFFER_SIZE (16384 * sizeof(uint32_t)) // must be power of 2
79
80////////////////////////////////////////////////////////////////////////
81// CODE AREA
82////////////////////////////////////////////////////////////////////////
83
84// dirty inline func includes
85
86#include "reverb.c"
87#include "adsr.c"
88
89////////////////////////////////////////////////////////////////////////
90// helpers for simple interpolation
91
92//
93// easy interpolation on upsampling, no special filter, just "Pete's common sense" tm
94//
95// instead of having n equal sample values in a row like:
96// ____
97// |____
98//
99// we compare the current delta change with the next delta change.
100//
101// if curr_delta is positive,
102//
103// - and next delta is smaller (or changing direction):
104// \.
105// -__
106//
107// - and next delta significant (at least twice) bigger:
108// --_
109// \.
110//
111// - and next delta is nearly same:
112// \.
113// \.
114//
115//
116// if curr_delta is negative,
117//
118// - and next delta is smaller (or changing direction):
119// _--
120// /
121//
122// - and next delta significant (at least twice) bigger:
123// /
124// __-
125//
126// - and next delta is nearly same:
127// /
128// /
129//
130
131static void InterpolateUp(sample_buf *sb, int sinc)
132{
133 int *SB = sb->SB;
134 if (sb->sinc_old != sinc)
135 {
136 sb->sinc_old = sinc;
137 SB[32] = 1;
138 }
139 if(SB[32]==1) // flag == 1? calc step and set flag... and don't change the value in this pass
140 {
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 :)
143
144 SB[32]=0;
145
146 if(id1>0) // curr delta positive
147 {
148 if(id2<id1)
149 {SB[28]=id1;SB[32]=2;}
150 else
151 if(id2<(id1<<1))
152 SB[28]=(id1*sinc)>>16;
153 else
154 SB[28]=(id1*sinc)>>17;
155 }
156 else // curr delta negative
157 {
158 if(id2>id1)
159 {SB[28]=id1;SB[32]=2;}
160 else
161 if(id2>(id1<<1))
162 SB[28]=(id1*sinc)>>16;
163 else
164 SB[28]=(id1*sinc)>>17;
165 }
166 }
167 else
168 if(SB[32]==2) // flag 1: calc step and set flag... and don't change the value in this pass
169 {
170 SB[32]=0;
171
172 SB[28]=(SB[28]*sinc)>>17;
173 //if(sinc<=0x8000)
174 // SB[29]=SB[30]-(SB[28]*((0x10000/sinc)-1));
175 //else
176 SB[29]+=SB[28];
177 }
178 else // no flags? add bigger val (if possible), calc smaller step, set flag1
179 SB[29]+=SB[28];
180}
181
182//
183// even easier interpolation on downsampling, also no special filter, again just "Pete's common sense" tm
184//
185
186static void InterpolateDown(sample_buf *sb, int sinc)
187{
188 int *SB = sb->SB;
189 if(sinc>=0x20000L) // we would skip at least one val?
190 {
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
194 }
195}
196
197////////////////////////////////////////////////////////////////////////
198
199#include "gauss_i.h"
200#include "xa.c"
201
202static void do_irq(int cycles_after)
203{
204 if (spu.spuStat & STAT_IRQ)
205 log_unhandled("spu: missed irq?\n");
206 else
207 {
208 spu.spuStat |= STAT_IRQ; // asserted status?
209 if (spu.irqCallback)
210 spu.irqCallback(cycles_after);
211 }
212}
213
214static int check_irq(int ch, unsigned char *pos)
215{
216 if((spu.spuCtrl & (CTRL_ON|CTRL_IRQ)) == (CTRL_ON|CTRL_IRQ) && pos == spu.pSpuIrq)
217 {
218 //printf("ch%d irq %04zx\n", ch, pos - spu.spuMemC);
219 do_irq(0);
220 return 1;
221 }
222 return 0;
223}
224
225void check_irq_io(unsigned int addr)
226{
227 unsigned int irq_addr = regAreaGet(H_SPUirqAddr) << 3;
228 //addr &= ~7; // ?
229 if((spu.spuCtrl & (CTRL_ON|CTRL_IRQ)) == (CTRL_ON|CTRL_IRQ) && addr == irq_addr)
230 {
231 //printf("io irq %04x\n", irq_addr);
232 do_irq(0);
233 }
234}
235
236void do_irq_io(int cycles_after)
237{
238 if ((spu.spuCtrl & (CTRL_ON|CTRL_IRQ)) == (CTRL_ON|CTRL_IRQ))
239 {
240 do_irq(cycles_after);
241 }
242}
243
244////////////////////////////////////////////////////////////////////////
245// START SOUND... called by main thread to setup a new sound on a channel
246////////////////////////////////////////////////////////////////////////
247
248static void ResetInterpolation(sample_buf *sb)
249{
250 memset(&sb->interp, 0, sizeof(sb->interp));
251 sb->sinc_old = -1;
252}
253
254static void StartSoundSB(sample_buf *sb)
255{
256 sb->SB[26] = 0; // init mixing vars
257 sb->SB[27] = 0;
258 ResetInterpolation(sb);
259}
260
261static void StartSoundMain(int ch)
262{
263 SPUCHAN *s_chan = &spu.s_chan[ch];
264
265 StartADSR(ch);
266 StartREVERB(ch);
267
268 s_chan->prevflags = 2;
269 s_chan->iSBPos = 27;
270 s_chan->spos = 0;
271 s_chan->bStarting = 1;
272
273 s_chan->pCurr = spu.spuMemC + ((regAreaGetCh(ch, 6) & ~1) << 3);
274
275 spu.dwNewChannel&=~(1<<ch); // clear new channel bit
276 spu.dwChannelDead&=~(1<<ch);
277 spu.dwChannelsAudible|=1<<ch;
278}
279
280static void StartSound(int ch)
281{
282 StartSoundMain(ch);
283 StartSoundSB(&spu.sb[ch]);
284}
285
286////////////////////////////////////////////////////////////////////////
287// ALL KIND OF HELPERS
288////////////////////////////////////////////////////////////////////////
289
290INLINE int FModChangeFrequency(int pitch, int ns, int *fmod_buf)
291{
292 pitch = (signed short)pitch;
293 pitch = ((32768 + fmod_buf[ns]) * pitch) >> 15;
294 pitch &= 0xffff;
295 if (pitch > 0x3fff)
296 pitch = 0x3fff;
297
298 fmod_buf[ns] = 0;
299
300 return pitch << 4;
301}
302
303INLINE void StoreInterpolationGaussCubic(sample_buf *sb, int fa)
304{
305 int gpos = sb->interp.gauss.pos & 3;
306 sb->interp.gauss.val[gpos++] = fa;
307 sb->interp.gauss.pos = gpos & 3;
308}
309
310#define gval(x) (int)sb->interp.gauss.val[(gpos + x) & 3]
311
312INLINE int GetInterpolationCubic(const sample_buf *sb, int spos)
313{
314 int gpos = sb->interp.gauss.pos;
315 int xd = (spos >> 1) + 1;
316 int fa;
317
318 fa = gval(3) - 3*gval(2) + 3*gval(1) - gval(0);
319 fa *= (xd - (2<<15)) / 6;
320 fa >>= 15;
321 fa += gval(2) - gval(1) - gval(1) + gval(0);
322 fa *= (xd - (1<<15)) >> 1;
323 fa >>= 15;
324 fa += gval(1) - gval(0);
325 fa *= xd;
326 fa >>= 15;
327 fa = fa + gval(0);
328 return fa;
329}
330
331INLINE int GetInterpolationGauss(const sample_buf *sb, int spos)
332{
333 int gpos = sb->interp.gauss.pos;
334 int vl = (spos >> 6) & ~3;
335 int vr;
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;
340 return vr;
341}
342
343static void decode_block_data(int *dest, const unsigned char *src, int predict_nr, int shift_factor)
344{
345 static const int f[16][2] = {
346 { 0, 0 },
347 { 60, 0 },
348 { 115, -52 },
349 { 98, -55 },
350 { 122, -60 }
351 };
352 int nSample;
353 int fa, s_1, s_2, d, s;
354
355 s_1 = dest[27];
356 s_2 = dest[26];
357
358 for (nSample = 0; nSample < 28; src++)
359 {
360 d = (int)*src;
361 s = (int)(signed short)((d & 0x0f) << 12);
362
363 fa = s >> shift_factor;
364 fa += ((s_1 * f[predict_nr][0])>>6) + ((s_2 * f[predict_nr][1])>>6);
365 ssat32_to_16(fa);
366 s_2 = s_1; s_1 = fa;
367
368 dest[nSample++] = fa;
369
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);
373 ssat32_to_16(fa);
374 s_2 = s_1; s_1 = fa;
375
376 dest[nSample++] = fa;
377 }
378}
379
380static int decode_block(void *unused, int ch, int *SB)
381{
382 SPUCHAN *s_chan = &spu.s_chan[ch];
383 unsigned char *start;
384 int predict_nr, shift_factor, flags;
385 int ret = 0;
386
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));
391 ret = 1;
392 }
393
394 if (s_chan->prevflags & 1) // 1: stop/loop
395 {
396 if (!(s_chan->prevflags & 2))
397 ret = 1;
398
399 start = s_chan->pLoop;
400 }
401
402 check_irq(ch, start);
403
404 predict_nr = start[0];
405 shift_factor = predict_nr & 0xf;
406 predict_nr >>= 4;
407
408 decode_block_data(SB, start + 2, predict_nr, shift_factor);
409
410 flags = start[1];
411 if (flags & 4 && !s_chan->bIgnoreLoop)
412 s_chan->pLoop = start; // loop adress
413
414 start += 16;
415
416 s_chan->pCurr = start; // store values for next cycle
417 s_chan->prevflags = flags;
418 s_chan->bStarting = 0;
419
420 return ret;
421}
422
423// do block, but ignore sample data
424static int skip_block(int ch)
425{
426 SPUCHAN *s_chan = &spu.s_chan[ch];
427 unsigned char *start = s_chan->pCurr;
428 int flags;
429 int ret = 0;
430
431 if (s_chan->prevflags & 1) {
432 if (!(s_chan->prevflags & 2))
433 ret = 1;
434
435 start = s_chan->pLoop;
436 }
437
438 check_irq(ch, start);
439
440 flags = start[1];
441 if (flags & 4 && !s_chan->bIgnoreLoop)
442 s_chan->pLoop = start;
443
444 start += 16;
445
446 s_chan->pCurr = start;
447 s_chan->prevflags = flags;
448 s_chan->bStarting = 0;
449
450 return ret;
451}
452
453// if irq is going to trigger sooner than in upd_samples, set upd_samples
454static void scan_for_irq(int ch, unsigned int *upd_samples)
455{
456 SPUCHAN *s_chan = &spu.s_chan[ch];
457 int pos, sinc, sinc_inv, end;
458 unsigned char *block;
459 int flags;
460
461 block = s_chan->pCurr;
462 pos = s_chan->spos;
463 sinc = s_chan->sinc;
464 end = pos + *upd_samples * sinc;
465 if (s_chan->prevflags & 1) // 1: stop/loop
466 block = s_chan->pLoop;
467
468 pos += (28 - s_chan->iSBPos) << 16;
469 while (pos < end)
470 {
471 if (block == spu.pSpuIrq)
472 break;
473 flags = block[1];
474 block += 16;
475 if (flags & 1) { // 1: stop/loop
476 block = s_chan->pLoop;
477 }
478 pos += 28 << 16;
479 }
480
481 if (pos < end)
482 {
483 sinc_inv = s_chan->sinc_inv;
484 if (sinc_inv == 0)
485 sinc_inv = s_chan->sinc_inv = (0x80000000u / (uint32_t)sinc) << 1;
486
487 pos -= s_chan->spos;
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);
491 }
492}
493
494#define make_do_samples(name, fmod_code, interp_start, interp_store, interp_get, interp_end) \
495static 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) \
498{ \
499 int ns, d, fa; \
500 int ret = ns_to; \
501 interp_start; \
502 \
503 for (ns = 0; ns < ns_to; ns++) \
504 { \
505 fmod_code; \
506 \
507 *spos += sinc; \
508 while (*spos >= 0x10000) \
509 { \
510 fa = sb->SB[(*sbpos)++]; \
511 if (*sbpos >= 28) \
512 { \
513 *sbpos = 0; \
514 d = decode_f(ctx, ch, sb->SB); \
515 if (d && ns < ret) \
516 ret = ns; \
517 } \
518 \
519 interp_store; \
520 *spos -= 0x10000; \
521 } \
522 \
523 interp_get; \
524 } \
525 \
526 interp_end; \
527 \
528 return ret; \
529}
530
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 \
534 sb->SB[28] = 0; \
535 sb->SB[29] = sb->SB[30]; \
536 sb->SB[30] = sb->SB[31]; \
537 sb->SB[31] = fa; \
538 sb->SB[32] = 1
539
540#define simple_interp_get \
541 if(sinc<0x10000) /* -> upsampling? */ \
542 InterpolateUp(sb, sinc); /* --> interpolate up */ \
543 else InterpolateDown(sb, sinc); /* --> else down */ \
544 dst[ns] = sb->SB[29]
545
546make_do_samples(do_samples_nointerp, , fa = sb->SB[29],
547 , dst[ns] = fa, sb->SB[29] = fa)
548make_do_samples(do_samples_simple, , ,
549 simple_interp_store, simple_interp_get, )
550make_do_samples(do_samples_gauss, , ,
551 StoreInterpolationGaussCubic(sb, fa),
552 dst[ns] = GetInterpolationGauss(sb, *spos), )
553make_do_samples(do_samples_cubic, , ,
554 StoreInterpolationGaussCubic(sb, fa),
555 dst[ns] = GetInterpolationCubic(sb, *spos), )
556make_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), )
560
561INLINE 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)
564{
565 int interp = spu.interpolation;
566 if (fmod == 1)
567 return do_samples_fmod(dst, decode_f, ctx, ch, ns_to, sb, sinc, spos, sbpos);
568 if (fmod)
569 interp = 2;
570 switch (interp) {
571 case 0:
572 return do_samples_nointerp(dst, decode_f, ctx, ch, ns_to, sb, sinc, spos, sbpos);
573 case 1:
574 return do_samples_simple (dst, decode_f, ctx, ch, ns_to, sb, sinc, spos, sbpos);
575 default:
576 return do_samples_gauss (dst, decode_f, ctx, ch, ns_to, sb, sinc, spos, sbpos);
577 case 3:
578 return do_samples_cubic (dst, decode_f, ctx, ch, ns_to, sb, sinc, spos, sbpos);
579 }
580}
581
582static int do_samples_skip(int ch, int ns_to)
583{
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;
588
589 spos += s_chan->iSBPos << 16;
590
591 for (ns = 0; ns < ns_to; ns++)
592 {
593 spos += sinc;
594 while (spos >= 28*0x10000)
595 {
596 d = skip_block(ch);
597 if (d && ns < ret)
598 ret = ns;
599 spos -= 28*0x10000;
600 }
601 }
602
603 s_chan->iSBPos = spos >> 16;
604 s_chan->spos = spos & 0xffff;
605
606 return ret;
607}
608
609static int do_samples_skip_fmod(int ch, int ns_to, int *fmod_buf)
610{
611 SPUCHAN *s_chan = &spu.s_chan[ch];
612 int spos = s_chan->spos;
613 int ret = ns_to, ns, d;
614
615 spos += s_chan->iSBPos << 16;
616
617 for (ns = 0; ns < ns_to; ns++)
618 {
619 spos += FModChangeFrequency(s_chan->iRawPitch, ns, fmod_buf);
620 while (spos >= 28*0x10000)
621 {
622 d = skip_block(ch);
623 if (d && ns < ret)
624 ret = ns;
625 spos -= 28*0x10000;
626 }
627 }
628
629 s_chan->iSBPos = spos >> 16;
630 s_chan->spos = spos & 0xffff;
631
632 return ret;
633}
634
635static void do_lsfr_samples(int *dst, int ns_to, int ctrl,
636 unsigned int *dwNoiseCount, unsigned int *dwNoiseVal)
637{
638 unsigned int counter = *dwNoiseCount;
639 unsigned int val = *dwNoiseVal;
640 unsigned int level, shift, bit;
641 int ns;
642
643 // modified from DrHell/shalma, no fraction
644 level = (ctrl >> 10) & 0x0f;
645 level = 0x8000 >> level;
646
647 for (ns = 0; ns < ns_to; ns++)
648 {
649 counter += 2;
650 if (counter >= level)
651 {
652 counter -= level;
653 shift = (val >> 10) & 0x1f;
654 bit = (0x69696969 >> shift) & 1;
655 bit ^= (val >> 15) & 1;
656 val = (val << 1) | bit;
657 }
658
659 dst[ns] = (signed short)val;
660 }
661
662 *dwNoiseCount = counter;
663 *dwNoiseVal = val;
664}
665
666static int do_samples_noise(int *dst, int ch, int ns_to)
667{
668 int ret;
669
670 ret = do_samples_skip(ch, ns_to);
671
672 do_lsfr_samples(dst, ns_to, spu.spuCtrl, &spu.dwNoiseCount, &spu.dwNoiseVal);
673
674 return ret;
675}
676
677#ifdef HAVE_ARMV5
678// asm code; lv and rv must be 0-3fff
679extern void mix_chan(int *SSumLR, int count, int lv, int rv);
680extern void mix_chan_rvb(int *SSumLR, int count, int lv, int rv, int *rvb);
681#else
682static void mix_chan(int *SSumLR, int count, int lv, int rv)
683{
684 const int *src = ChanBuf;
685 int l, r;
686
687 while (count--)
688 {
689 int sval = *src++;
690
691 l = (sval * lv) >> 14;
692 r = (sval * rv) >> 14;
693 *SSumLR++ += l;
694 *SSumLR++ += r;
695 }
696}
697
698static void mix_chan_rvb(int *SSumLR, int count, int lv, int rv, int *rvb)
699{
700 const int *src = ChanBuf;
701 int *dst = SSumLR;
702 int *drvb = rvb;
703 int l, r;
704
705 while (count--)
706 {
707 int sval = *src++;
708
709 l = (sval * lv) >> 14;
710 r = (sval * rv) >> 14;
711 *dst++ += l;
712 *dst++ += r;
713 *drvb++ += l;
714 *drvb++ += r;
715 }
716}
717#endif
718
719// 0x0800-0x0bff Voice 1
720// 0x0c00-0x0fff Voice 3
721static noinline void do_decode_bufs(unsigned short *mem, int which,
722 int count, int decode_pos)
723{
724 unsigned short *dst = &mem[0x800/2 + which*0x400/2];
725 const int *src = ChanBuf;
726 int cursor = decode_pos;
727
728 while (count-- > 0)
729 {
730 cursor &= 0x1ff;
731 dst[cursor] = *src++;
732 cursor++;
733 }
734
735 // decode_pos is updated and irqs are checked later, after voice loop
736}
737
738static void do_silent_chans(int ns_to, int silentch)
739{
740 unsigned int mask;
741 SPUCHAN *s_chan;
742 int ch;
743
744 mask = silentch & 0xffffff;
745 for (ch = 0; mask != 0; ch++, mask >>= 1)
746 {
747 if (!(mask & 1)) continue;
748 if (spu.dwChannelDead & (1<<ch)) continue;
749
750 s_chan = &spu.s_chan[ch];
751 if (s_chan->pCurr > spu.pSpuIrq && s_chan->pLoop > spu.pSpuIrq)
752 continue;
753
754 s_chan->spos += s_chan->iSBPos << 16;
755 s_chan->iSBPos = 0;
756
757 s_chan->spos += s_chan->sinc * ns_to;
758 while (s_chan->spos >= 28 * 0x10000)
759 {
760 unsigned char *start = s_chan->pCurr;
761
762 skip_block(ch);
763 if (start == s_chan->pCurr || start - spu.spuMemC < 0x1000)
764 {
765 // looping on self or stopped(?)
766 spu.dwChannelDead |= 1<<ch;
767 s_chan->spos = 0;
768 break;
769 }
770
771 s_chan->spos -= 28 * 0x10000;
772 }
773 }
774}
775
776static void do_channels(int ns_to)
777{
778 unsigned int mask;
779 int do_rvb, ch, d;
780 SPUCHAN *s_chan;
781
782 if (unlikely(spu.interpolation != spu_config.iUseInterpolation))
783 {
784 spu.interpolation = spu_config.iUseInterpolation;
785 mask = spu.dwChannelsAudible & 0xffffff;
786 for (ch = 0; mask != 0; ch++, mask >>= 1)
787 if (mask & 1)
788 ResetInterpolation(&spu.sb[ch]);
789 }
790
791 do_rvb = spu.rvb->StartAddr && spu_config.iUseReverb;
792 if (do_rvb)
793 memset(RVB, 0, ns_to * sizeof(RVB[0]) * 2);
794
795 mask = spu.dwNewChannel & 0xffffff;
796 for (ch = 0; mask != 0; ch++, mask >>= 1) {
797 if (mask & 1)
798 StartSound(ch);
799 }
800
801 mask = spu.dwChannelsAudible & 0xffffff;
802 for (ch = 0; mask != 0; ch++, mask >>= 1) // loop em all...
803 {
804 if (!(mask & 1)) continue; // channel not playing? next
805
806 s_chan = &spu.s_chan[ch];
807 if (s_chan->bNoise)
808 d = do_samples_noise(ChanBuf, ch, ns_to);
809 else
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);
812
813 if (!s_chan->bStarting) {
814 d = MixADSR(ChanBuf, &s_chan->ADSRX, d);
815 if (d < ns_to) {
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]));
820 }
821 }
822
823 if (ch == 1 || ch == 3)
824 {
825 do_decode_bufs(spu.spuMem, ch/2, ns_to, spu.decode_pos);
826 spu.decode_dirty_ch |= 1 << ch;
827 }
828
829 if (s_chan->bFMod == 2) // fmod freq channel
830 memcpy(iFMod, &ChanBuf, ns_to * sizeof(iFMod[0]));
831 if (!(spu.spuCtrl & CTRL_MUTE))
832 ;
833 else if (s_chan->bRVBActive && do_rvb)
834 mix_chan_rvb(spu.SSumLR, ns_to, s_chan->iLeftVolume, s_chan->iRightVolume, RVB);
835 else
836 mix_chan(spu.SSumLR, ns_to, s_chan->iLeftVolume, s_chan->iRightVolume);
837 }
838
839 MixCD(spu.SSumLR, RVB, ns_to, spu.decode_pos);
840
841 if (spu.rvb->StartAddr) {
842 if (do_rvb)
843 REVERBDo(spu.SSumLR, RVB, ns_to, spu.rvb->CurrAddr);
844
845 spu.rvb->CurrAddr += ns_to / 2;
846 while (spu.rvb->CurrAddr >= 0x40000)
847 spu.rvb->CurrAddr -= 0x40000 - spu.rvb->StartAddr;
848 }
849}
850
851static void do_samples_finish(int *SSumLR, int ns_to,
852 int silentch, int decode_pos);
853
854// optional worker thread handling
855
856#if P_HAVE_PTHREAD || defined(WANT_THREAD_CODE)
857
858// worker thread state
859static struct spu_worker {
860 union {
861 struct {
862 unsigned int exit_thread;
863 unsigned int i_ready;
864 unsigned int i_reaped;
865 unsigned int last_boot_cnt; // dsp
866 unsigned int ram_dirty;
867 };
868 // aligning for C64X_DSP
869 unsigned int _pad0[128/4];
870 };
871 union {
872 struct {
873 unsigned int i_done;
874 unsigned int active; // dsp
875 unsigned int boot_cnt;
876 };
877 unsigned int _pad1[128/4];
878 };
879 struct work_item {
880 int ns_to;
881 int ctrl;
882 int decode_pos;
883 int rvb_addr;
884 unsigned int channels_new;
885 unsigned int channels_on;
886 unsigned int channels_silent;
887 struct {
888 int spos;
889 int sbpos;
890 int sinc;
891 int start;
892 int loop;
893 short vol_l;
894 short vol_r;
895 unsigned short ns_to;
896 unsigned short bNoise:1;
897 unsigned short bFMod:2;
898 unsigned short bRVBActive:1;
899 unsigned short bStarting:1;
900 ADSRInfoEx adsr;
901 } ch[24];
902 int SSumLR[NSSIZE * 2];
903 } i[4];
904} *worker;
905
906#define WORK_MAXCNT (sizeof(worker->i) / sizeof(worker->i[0]))
907#define WORK_I_MASK (WORK_MAXCNT - 1)
908
909static void thread_work_start(void);
910static void thread_work_wait_sync(struct work_item *work, int force);
911static void thread_sync_caches(void);
912static int thread_get_i_done(void);
913
914static int decode_block_work(void *context, int ch, int *SB)
915{
916 const unsigned char *ram = spu.spuMemC;
917 int predict_nr, shift_factor, flags;
918 struct work_item *work = context;
919 int start = work->ch[ch].start;
920 int loop = work->ch[ch].loop;
921
922 predict_nr = ram[start];
923 shift_factor = predict_nr & 0xf;
924 predict_nr >>= 4;
925
926 decode_block_data(SB, ram + start + 2, predict_nr, shift_factor);
927
928 flags = ram[start + 1];
929 if (flags & 4)
930 loop = start; // loop adress
931
932 start += 16;
933
934 if (flags & 1) // 1: stop/loop
935 start = loop;
936
937 work->ch[ch].start = start & 0x7ffff;
938 work->ch[ch].loop = loop;
939
940 return 0;
941}
942
943static void queue_channel_work(int ns_to, unsigned int silentch)
944{
945 int tmpFMod[NSSIZE];
946 struct work_item *work;
947 SPUCHAN *s_chan;
948 unsigned int mask;
949 int ch, d;
950
951 work = &worker->i[worker->i_ready & WORK_I_MASK];
952 work->ns_to = ns_to;
953 work->ctrl = spu.spuCtrl;
954 work->decode_pos = spu.decode_pos;
955 work->channels_silent = silentch;
956
957 mask = work->channels_new = spu.dwNewChannel & 0xffffff;
958 for (ch = 0; mask != 0; ch++, mask >>= 1) {
959 if (mask & 1)
960 StartSound(ch);
961 }
962
963 mask = work->channels_on = spu.dwChannelsAudible & 0xffffff;
964 spu.decode_dirty_ch |= mask & 0x0a;
965
966 for (ch = 0; mask != 0; ch++, mask >>= 1)
967 {
968 if (!(mask & 1)) continue;
969
970 s_chan = &spu.s_chan[ch];
971 work->ch[ch].spos = s_chan->spos;
972 work->ch[ch].sbpos = s_chan->iSBPos;
973 work->ch[ch].sinc = s_chan->sinc;
974 work->ch[ch].adsr = s_chan->ADSRX;
975 work->ch[ch].vol_l = s_chan->iLeftVolume;
976 work->ch[ch].vol_r = s_chan->iRightVolume;
977 work->ch[ch].start = s_chan->pCurr - spu.spuMemC;
978 work->ch[ch].loop = s_chan->pLoop - spu.spuMemC;
979 work->ch[ch].bNoise = s_chan->bNoise;
980 work->ch[ch].bFMod = s_chan->bFMod;
981 work->ch[ch].bRVBActive = s_chan->bRVBActive;
982 work->ch[ch].bStarting = s_chan->bStarting;
983 if (s_chan->prevflags & 1)
984 work->ch[ch].start = work->ch[ch].loop;
985
986 if (unlikely(s_chan->bFMod == 2))
987 {
988 // sucks, have to do double work
989 assert(!s_chan->bNoise);
990 d = do_samples_gauss(tmpFMod, decode_block, NULL, ch, ns_to,
991 &spu.sb[ch], s_chan->sinc, &s_chan->spos, &s_chan->iSBPos);
992 if (!s_chan->bStarting) {
993 d = MixADSR(tmpFMod, &s_chan->ADSRX, d);
994 if (d < ns_to) {
995 spu.dwChannelsAudible &= ~(1 << ch);
996 s_chan->ADSRX.State = ADSR_RELEASE;
997 s_chan->ADSRX.EnvelopeVol = 0;
998 }
999 }
1000 memset(&tmpFMod[d], 0, (ns_to - d) * sizeof(tmpFMod[d]));
1001 work->ch[ch].ns_to = d;
1002 continue;
1003 }
1004 if (unlikely(s_chan->bFMod))
1005 d = do_samples_skip_fmod(ch, ns_to, tmpFMod);
1006 else
1007 d = do_samples_skip(ch, ns_to);
1008 work->ch[ch].ns_to = d;
1009
1010 if (!s_chan->bStarting) {
1011 // note: d is not accurate on skip
1012 d = SkipADSR(&s_chan->ADSRX, d);
1013 if (d < ns_to) {
1014 spu.dwChannelsAudible &= ~(1 << ch);
1015 s_chan->ADSRX.State = ADSR_RELEASE;
1016 s_chan->ADSRX.EnvelopeVol = 0;
1017 }
1018 }
1019 } // for (ch;;)
1020
1021 work->rvb_addr = 0;
1022 if (spu.rvb->StartAddr) {
1023 if (spu_config.iUseReverb)
1024 work->rvb_addr = spu.rvb->CurrAddr;
1025
1026 spu.rvb->CurrAddr += ns_to / 2;
1027 while (spu.rvb->CurrAddr >= 0x40000)
1028 spu.rvb->CurrAddr -= 0x40000 - spu.rvb->StartAddr;
1029 }
1030
1031 worker->i_ready++;
1032 thread_work_start();
1033}
1034
1035static void do_channel_work(struct work_item *work)
1036{
1037 unsigned int mask;
1038 int spos, sbpos;
1039 int d, ch, ns_to;
1040
1041 ns_to = work->ns_to;
1042
1043 if (unlikely(spu.interpolation != spu_config.iUseInterpolation))
1044 {
1045 spu.interpolation = spu_config.iUseInterpolation;
1046 mask = work->channels_on;
1047 for (ch = 0; mask != 0; ch++, mask >>= 1)
1048 if (mask & 1)
1049 ResetInterpolation(&spu.sb_thread[ch]);
1050 }
1051
1052 if (work->rvb_addr)
1053 memset(RVB, 0, ns_to * sizeof(RVB[0]) * 2);
1054
1055 mask = work->channels_new;
1056 for (ch = 0; mask != 0; ch++, mask >>= 1) {
1057 if (mask & 1)
1058 StartSoundSB(&spu.sb_thread[ch]);
1059 }
1060
1061 mask = work->channels_on;
1062 for (ch = 0; mask != 0; ch++, mask >>= 1)
1063 {
1064 if (!(mask & 1)) continue;
1065
1066 d = work->ch[ch].ns_to;
1067 spos = work->ch[ch].spos;
1068 sbpos = work->ch[ch].sbpos;
1069
1070 if (work->ch[ch].bNoise)
1071 do_lsfr_samples(ChanBuf, d, work->ctrl, &spu.dwNoiseCount, &spu.dwNoiseVal);
1072 else
1073 do_samples_adpcm(ChanBuf, decode_block_work, work, ch, d, work->ch[ch].bFMod,
1074 &spu.sb_thread[ch], work->ch[ch].sinc, &spos, &sbpos);
1075
1076 d = MixADSR(ChanBuf, &work->ch[ch].adsr, d);
1077 if (d < ns_to) {
1078 work->ch[ch].adsr.EnvelopeVol = 0;
1079 memset(&ChanBuf[d], 0, (ns_to - d) * sizeof(ChanBuf[0]));
1080 }
1081
1082 if (ch == 1 || ch == 3)
1083 do_decode_bufs(spu.spuMem, ch/2, ns_to, work->decode_pos);
1084
1085 if (work->ch[ch].bFMod == 2) // fmod freq channel
1086 memcpy(iFMod, &ChanBuf, ns_to * sizeof(iFMod[0]));
1087 if (work->ch[ch].bRVBActive && work->rvb_addr)
1088 mix_chan_rvb(work->SSumLR, ns_to,
1089 work->ch[ch].vol_l, work->ch[ch].vol_r, RVB);
1090 else
1091 mix_chan(work->SSumLR, ns_to, work->ch[ch].vol_l, work->ch[ch].vol_r);
1092 }
1093
1094 if (work->rvb_addr)
1095 REVERBDo(work->SSumLR, RVB, ns_to, work->rvb_addr);
1096}
1097
1098static void sync_worker_thread(int force)
1099{
1100 struct work_item *work;
1101 int done, used_space;
1102
1103 // rvb offsets will change, thread may be using them
1104 force |= spu.rvb->dirty && spu.rvb->StartAddr;
1105
1106 done = thread_get_i_done() - worker->i_reaped;
1107 used_space = worker->i_ready - worker->i_reaped;
1108
1109 //printf("done: %d use: %d dsp: %u/%u\n", done, used_space,
1110 // worker->boot_cnt, worker->i_done);
1111
1112 while ((force && used_space > 0) || used_space >= WORK_MAXCNT || done > 0) {
1113 work = &worker->i[worker->i_reaped & WORK_I_MASK];
1114 thread_work_wait_sync(work, force);
1115
1116 MixCD(work->SSumLR, RVB, work->ns_to, work->decode_pos);
1117 do_samples_finish(work->SSumLR, work->ns_to,
1118 work->channels_silent, work->decode_pos);
1119
1120 worker->i_reaped++;
1121 done = thread_get_i_done() - worker->i_reaped;
1122 used_space = worker->i_ready - worker->i_reaped;
1123 }
1124 if (force)
1125 thread_sync_caches();
1126}
1127
1128#else
1129
1130static void queue_channel_work(int ns_to, int silentch) {}
1131static void sync_worker_thread(int force) {}
1132
1133static const void * const worker = NULL;
1134
1135#endif // P_HAVE_PTHREAD || defined(WANT_THREAD_CODE)
1136
1137////////////////////////////////////////////////////////////////////////
1138// MAIN SPU FUNCTION
1139// here is the main job handler...
1140////////////////////////////////////////////////////////////////////////
1141
1142void do_samples(unsigned int cycles_to, int do_direct)
1143{
1144 unsigned int silentch;
1145 int cycle_diff;
1146 int ns_to;
1147
1148 cycle_diff = cycles_to - spu.cycles_played;
1149 if (cycle_diff < -2*1048576 || cycle_diff > 2*1048576)
1150 {
1151 log_unhandled("desync %u %d\n", cycles_to, cycle_diff);
1152 spu.cycles_played = cycles_to;
1153 return;
1154 }
1155
1156 silentch = ~(spu.dwChannelsAudible | spu.dwNewChannel) & 0xffffff;
1157
1158 do_direct |= (silentch == 0xffffff);
1159 if (worker != NULL)
1160 sync_worker_thread(do_direct);
1161
1162 if (cycle_diff < 2 * 768)
1163 return;
1164
1165 ns_to = (cycle_diff / 768 + 1) & ~1;
1166 if (ns_to > NSSIZE) {
1167 // should never happen
1168 log_unhandled("ns_to oflow %d %d\n", ns_to, NSSIZE);
1169 ns_to = NSSIZE;
1170 }
1171
1172 //////////////////////////////////////////////////////
1173 // special irq handling in the decode buffers (0x0000-0x1000)
1174 // we know:
1175 // the decode buffers are located in spu memory in the following way:
1176 // 0x0000-0x03ff CD audio left
1177 // 0x0400-0x07ff CD audio right
1178 // 0x0800-0x0bff Voice 1
1179 // 0x0c00-0x0fff Voice 3
1180 // and decoded data is 16 bit for one sample
1181 // we assume:
1182 // even if voices 1/3 are off or no cd audio is playing, the internal
1183 // play positions will move on and wrap after 0x400 bytes.
1184 // Therefore: we just need a pointer from spumem+0 to spumem+3ff, and
1185 // increase this pointer on each sample by 2 bytes. If this pointer
1186 // (or 0x400 offsets of this pointer) hits the spuirq address, we generate
1187 // an IRQ.
1188
1189 if (unlikely((spu.spuCtrl & CTRL_IRQ)
1190 && spu.pSpuIrq < spu.spuMemC+0x1000))
1191 {
1192 int irq_pos = (spu.pSpuIrq - spu.spuMemC) / 2 & 0x1ff;
1193 int left = (irq_pos - spu.decode_pos) & 0x1ff;
1194 if (0 < left && left <= ns_to)
1195 {
1196 //xprintf("decoder irq %x\n", spu.decode_pos);
1197 do_irq(0);
1198 }
1199 }
1200 if (!spu.cycles_dma_end || (int)(spu.cycles_dma_end - cycles_to) < 0) {
1201 spu.cycles_dma_end = 0;
1202 check_irq_io(spu.spuAddr);
1203 }
1204
1205 if (unlikely(spu.rvb->dirty))
1206 REVERBPrep();
1207
1208 if (do_direct || worker == NULL || !spu_config.iUseThread) {
1209 do_channels(ns_to);
1210 do_samples_finish(spu.SSumLR, ns_to, silentch, spu.decode_pos);
1211 }
1212 else {
1213 queue_channel_work(ns_to, silentch);
1214 //sync_worker_thread(1); // uncomment for debug
1215 }
1216
1217 // advance "stopped" channels that can cause irqs
1218 // (all chans are always playing on the real thing..)
1219 if (spu.spuCtrl & CTRL_IRQ)
1220 do_silent_chans(ns_to, silentch);
1221
1222 spu.cycles_played += ns_to * 768;
1223 spu.decode_pos = (spu.decode_pos + ns_to) & 0x1ff;
1224#if 0
1225 static int ccount; static time_t ctime; ccount++;
1226 if (time(NULL) != ctime)
1227 { printf("%d\n", ccount); ccount = 0; ctime = time(NULL); }
1228#endif
1229}
1230
1231static void do_samples_finish(int *SSumLR, int ns_to,
1232 int silentch, int decode_pos)
1233{
1234 int vol_l = ((int)regAreaGet(H_SPUmvolL) << 17) >> 17;
1235 int vol_r = ((int)regAreaGet(H_SPUmvolR) << 17) >> 17;
1236 int ns;
1237 int d;
1238
1239 // must clear silent channel decode buffers
1240 if(unlikely(silentch & spu.decode_dirty_ch & (1<<1)))
1241 {
1242 memset(&spu.spuMem[0x800/2], 0, 0x400);
1243 spu.decode_dirty_ch &= ~(1<<1);
1244 }
1245 if(unlikely(silentch & spu.decode_dirty_ch & (1<<3)))
1246 {
1247 memset(&spu.spuMem[0xc00/2], 0, 0x400);
1248 spu.decode_dirty_ch &= ~(1<<3);
1249 }
1250
1251 vol_l = vol_l * spu_config.iVolume >> 10;
1252 vol_r = vol_r * spu_config.iVolume >> 10;
1253
1254 if (!(vol_l | vol_r))
1255 {
1256 // muted? (rare)
1257 memset(spu.pS, 0, ns_to * 2 * sizeof(spu.pS[0]));
1258 memset(SSumLR, 0, ns_to * 2 * sizeof(SSumLR[0]));
1259 spu.pS += ns_to * 2;
1260 }
1261 else
1262 for (ns = 0; ns < ns_to * 2; )
1263 {
1264 d = SSumLR[ns]; SSumLR[ns] = 0;
1265 d = d * vol_l >> 14;
1266 ssat32_to_16(d);
1267 *spu.pS++ = d;
1268 ns++;
1269
1270 d = SSumLR[ns]; SSumLR[ns] = 0;
1271 d = d * vol_r >> 14;
1272 ssat32_to_16(d);
1273 *spu.pS++ = d;
1274 ns++;
1275 }
1276}
1277
1278void schedule_next_irq(void)
1279{
1280 unsigned int upd_samples;
1281 int ch;
1282
1283 if (spu.scheduleCallback == NULL)
1284 return;
1285
1286 upd_samples = 44100 / 50;
1287
1288 for (ch = 0; ch < MAXCHAN; ch++)
1289 {
1290 if (spu.dwChannelDead & (1 << ch))
1291 continue;
1292 if ((unsigned long)(spu.pSpuIrq - spu.s_chan[ch].pCurr) > IRQ_NEAR_BLOCKS * 16
1293 && (unsigned long)(spu.pSpuIrq - spu.s_chan[ch].pLoop) > IRQ_NEAR_BLOCKS * 16)
1294 continue;
1295 if (spu.s_chan[ch].sinc == 0)
1296 continue;
1297
1298 scan_for_irq(ch, &upd_samples);
1299 }
1300
1301 if (unlikely(spu.pSpuIrq < spu.spuMemC + 0x1000))
1302 {
1303 int irq_pos = (spu.pSpuIrq - spu.spuMemC) / 2 & 0x1ff;
1304 int left = (irq_pos - spu.decode_pos) & 0x1ff;
1305 if (0 < left && left < upd_samples) {
1306 //xprintf("decode: %3d (%3d/%3d)\n", left, spu.decode_pos, irq_pos);
1307 upd_samples = left;
1308 }
1309 }
1310
1311 if (upd_samples < 44100 / 50)
1312 spu.scheduleCallback(upd_samples * 768);
1313}
1314
1315// SPU ASYNC... even newer epsxe func
1316// 1 time every 'cycle' cycles... harhar
1317
1318// rearmed: called dynamically now
1319
1320void CALLBACK SPUasync(unsigned int cycle, unsigned int flags)
1321{
1322 do_samples(cycle, 0);
1323
1324 if (spu.spuCtrl & CTRL_IRQ)
1325 schedule_next_irq();
1326
1327 if (flags & 1) {
1328 out_current->feed(spu.pSpuBuffer, (unsigned char *)spu.pS - spu.pSpuBuffer);
1329 spu.pS = (short *)spu.pSpuBuffer;
1330
1331 if (spu_config.iTempo) {
1332 if (!out_current->busy())
1333 // cause more samples to be generated
1334 // (and break some games because of bad sync)
1335 spu.cycles_played -= 44100 / 60 / 2 * 768;
1336 }
1337 }
1338}
1339
1340// SPU UPDATE... new epsxe func
1341// 1 time every 32 hsync lines
1342// (312/32)x50 in pal
1343// (262/32)x60 in ntsc
1344
1345// since epsxe 1.5.2 (linux) uses SPUupdate, not SPUasync, I will
1346// leave that func in the linux port, until epsxe linux is using
1347// the async function as well
1348
1349void CALLBACK SPUupdate(void)
1350{
1351}
1352
1353// XA AUDIO
1354
1355void CALLBACK SPUplayADPCMchannel(xa_decode_t *xap, unsigned int cycle, int is_start)
1356{
1357 if(!xap) return;
1358 if(!xap->freq) return; // no xa freq ? bye
1359
1360 if (is_start)
1361 spu.XAPlay = spu.XAFeed = spu.XAStart;
1362 if (spu.XAPlay == spu.XAFeed)
1363 do_samples(cycle, 1); // catch up to prevent source underflows later
1364
1365 FeedXA(xap); // call main XA feeder
1366 spu.xapGlobal = xap; // store info for save states
1367}
1368
1369// CDDA AUDIO
1370int CALLBACK SPUplayCDDAchannel(short *pcm, int nbytes, unsigned int cycle, int unused)
1371{
1372 if (!pcm) return -1;
1373 if (nbytes<=0) return -1;
1374
1375 if (spu.CDDAPlay == spu.CDDAFeed)
1376 do_samples(cycle, 1); // catch up to prevent source underflows later
1377
1378 FeedCDDA((unsigned char *)pcm, nbytes);
1379 return 0;
1380}
1381
1382void CALLBACK SPUsetCDvol(unsigned char ll, unsigned char lr,
1383 unsigned char rl, unsigned char rr, unsigned int cycle)
1384{
1385 if (spu.XAPlay != spu.XAFeed || spu.CDDAPlay != spu.CDDAFeed)
1386 do_samples(cycle, 1);
1387 spu.cdv.ll = ll;
1388 spu.cdv.lr = lr;
1389 spu.cdv.rl = rl;
1390 spu.cdv.rr = rr;
1391}
1392
1393// to be called after state load
1394void ClearWorkingState(void)
1395{
1396 memset(iFMod, 0, sizeof(iFMod));
1397 spu.pS=(short *)spu.pSpuBuffer; // setup soundbuffer pointer
1398}
1399
1400// SETUPSTREAMS: init most of the spu buffers
1401static void SetupStreams(void)
1402{
1403 spu.pSpuBuffer = (unsigned char *)malloc(32768); // alloc mixing buffer
1404 spu.SSumLR = calloc(NSSIZE * 2, sizeof(spu.SSumLR[0]));
1405
1406 spu.XAStart = malloc(44100 * sizeof(uint32_t)); // alloc xa buffer
1407 spu.XAEnd = spu.XAStart + 44100;
1408 spu.XAPlay = spu.XAStart;
1409 spu.XAFeed = spu.XAStart;
1410
1411 spu.CDDAStart = malloc(CDDA_BUFFER_SIZE); // alloc cdda buffer
1412 spu.CDDAEnd = spu.CDDAStart + CDDA_BUFFER_SIZE / sizeof(uint32_t);
1413 spu.CDDAPlay = spu.CDDAStart;
1414 spu.CDDAFeed = spu.CDDAStart;
1415
1416 ClearWorkingState();
1417}
1418
1419// REMOVESTREAMS: free most buffer
1420static void RemoveStreams(void)
1421{
1422 free(spu.pSpuBuffer); // free mixing buffer
1423 spu.pSpuBuffer = NULL;
1424 free(spu.SSumLR);
1425 spu.SSumLR = NULL;
1426 free(spu.XAStart); // free XA buffer
1427 spu.XAStart = NULL;
1428 free(spu.CDDAStart); // free CDDA buffer
1429 spu.CDDAStart = NULL;
1430}
1431
1432#if defined(C64X_DSP)
1433
1434/* special code for TI C64x DSP */
1435#include "spu_c64x.c"
1436
1437#elif P_HAVE_PTHREAD
1438
1439#include <pthread.h>
1440#include <semaphore.h>
1441#include <unistd.h>
1442
1443static struct {
1444 pthread_t thread;
1445 sem_t sem_avail;
1446 sem_t sem_done;
1447} t;
1448
1449/* generic pthread implementation */
1450
1451static void thread_work_start(void)
1452{
1453 sem_post(&t.sem_avail);
1454}
1455
1456static void thread_work_wait_sync(struct work_item *work, int force)
1457{
1458 sem_wait(&t.sem_done);
1459}
1460
1461static int thread_get_i_done(void)
1462{
1463 return worker->i_done;
1464}
1465
1466static void thread_sync_caches(void)
1467{
1468}
1469
1470static void *spu_worker_thread(void *unused)
1471{
1472 struct work_item *work;
1473
1474 while (1) {
1475 sem_wait(&t.sem_avail);
1476 if (worker->exit_thread)
1477 break;
1478
1479 work = &worker->i[worker->i_done & WORK_I_MASK];
1480 do_channel_work(work);
1481 worker->i_done++;
1482
1483 sem_post(&t.sem_done);
1484 }
1485
1486 return NULL;
1487}
1488
1489static void init_spu_thread(void)
1490{
1491 int ret;
1492
1493 if (sysconf(_SC_NPROCESSORS_ONLN) <= 1)
1494 return;
1495
1496 worker = calloc(1, sizeof(*worker));
1497 if (worker == NULL)
1498 return;
1499 ret = sem_init(&t.sem_avail, 0, 0);
1500 if (ret != 0)
1501 goto fail_sem_avail;
1502 ret = sem_init(&t.sem_done, 0, 0);
1503 if (ret != 0)
1504 goto fail_sem_done;
1505
1506 ret = pthread_create(&t.thread, NULL, spu_worker_thread, NULL);
1507 if (ret != 0)
1508 goto fail_thread;
1509
1510 spu_config.iThreadAvail = 1;
1511 return;
1512
1513fail_thread:
1514 sem_destroy(&t.sem_done);
1515fail_sem_done:
1516 sem_destroy(&t.sem_avail);
1517fail_sem_avail:
1518 free(worker);
1519 worker = NULL;
1520 spu_config.iThreadAvail = 0;
1521}
1522
1523static void exit_spu_thread(void)
1524{
1525 if (worker == NULL)
1526 return;
1527 worker->exit_thread = 1;
1528 sem_post(&t.sem_avail);
1529 pthread_join(t.thread, NULL);
1530 sem_destroy(&t.sem_done);
1531 sem_destroy(&t.sem_avail);
1532 free(worker);
1533 worker = NULL;
1534}
1535
1536#else // if !P_HAVE_PTHREAD
1537
1538static void init_spu_thread(void)
1539{
1540}
1541
1542static void exit_spu_thread(void)
1543{
1544}
1545
1546#endif
1547
1548// SPUINIT: this func will be called first by the main emu
1549long CALLBACK SPUinit(void)
1550{
1551 int i;
1552
1553 memset(&spu, 0, sizeof(spu));
1554 spu.spuMemC = calloc(1, 512 * 1024);
1555 InitADSR();
1556
1557 spu.s_chan = calloc(MAXCHAN+1, sizeof(spu.s_chan[0])); // channel + 1 infos (1 is security for fmod handling)
1558 spu.rvb = calloc(1, sizeof(REVERBInfo));
1559
1560 spu.spuAddr = 0;
1561 spu.decode_pos = 0;
1562 spu.pSpuIrq = spu.spuMemC;
1563
1564 SetupStreams(); // prepare streaming
1565
1566 if (spu_config.iVolume == 0)
1567 spu_config.iVolume = 768; // 1024 is 1.0
1568
1569 init_spu_thread();
1570
1571 for (i = 0; i < MAXCHAN; i++) // loop sound channels
1572 {
1573 spu.s_chan[i].ADSRX.SustainLevel = 0xf; // -> init sustain
1574 spu.s_chan[i].ADSRX.SustainIncrease = 1;
1575 spu.s_chan[i].pLoop = spu.spuMemC;
1576 spu.s_chan[i].pCurr = spu.spuMemC;
1577 spu.s_chan[i].bIgnoreLoop = 0;
1578 }
1579
1580 spu.bSpuInit=1; // flag: we are inited
1581
1582 return 0;
1583}
1584
1585// SPUOPEN: called by main emu after init
1586long CALLBACK SPUopen(void)
1587{
1588 if (spu.bSPUIsOpen) return 0; // security for some stupid main emus
1589
1590 SetupSound(); // setup sound (before init!)
1591
1592 spu.bSPUIsOpen = 1;
1593
1594 return PSE_SPU_ERR_SUCCESS;
1595}
1596
1597// SPUCLOSE: called before shutdown
1598long CALLBACK SPUclose(void)
1599{
1600 if (!spu.bSPUIsOpen) return 0; // some security
1601
1602 spu.bSPUIsOpen = 0; // no more open
1603
1604 out_current->finish(); // no more sound handling
1605
1606 return 0;
1607}
1608
1609// SPUSHUTDOWN: called by main emu on final exit
1610long CALLBACK SPUshutdown(void)
1611{
1612 SPUclose();
1613
1614 exit_spu_thread();
1615
1616 free(spu.spuMemC);
1617 spu.spuMemC = NULL;
1618 free(spu.s_chan);
1619 spu.s_chan = NULL;
1620 free(spu.rvb);
1621 spu.rvb = NULL;
1622
1623 RemoveStreams(); // no more streaming
1624 spu.bSpuInit=0;
1625
1626 return 0;
1627}
1628
1629// SETUP CALLBACKS
1630// this functions will be called once,
1631// passes a callback that should be called on SPU-IRQ/cdda volume change
1632void CALLBACK SPUregisterCallback(void (CALLBACK *callback)(int))
1633{
1634 spu.irqCallback = callback;
1635}
1636
1637void CALLBACK SPUregisterCDDAVolume(void (CALLBACK *CDDAVcallback)(short, short))
1638{
1639 //spu.cddavCallback = CDDAVcallback;
1640}
1641
1642void CALLBACK SPUregisterScheduleCb(void (CALLBACK *callback)(unsigned int))
1643{
1644 spu.scheduleCallback = callback;
1645}
1646
1647// COMMON PLUGIN INFO FUNCS
1648/*
1649char * CALLBACK PSEgetLibName(void)
1650{
1651 return _(libraryName);
1652}
1653
1654unsigned long CALLBACK PSEgetLibType(void)
1655{
1656 return PSE_LT_SPU;
1657}
1658
1659unsigned long CALLBACK PSEgetLibVersion(void)
1660{
1661 return (1 << 16) | (6 << 8);
1662}
1663
1664char * SPUgetLibInfos(void)
1665{
1666 return _(libraryInfo);
1667}
1668*/
1669
1670// debug
1671void spu_get_debug_info(int *chans_out, int *run_chans, int *fmod_chans_out, int *noise_chans_out)
1672{
1673 int ch = 0, fmod_chans = 0, noise_chans = 0, irq_chans = 0;
1674
1675 if (spu.s_chan == NULL)
1676 return;
1677
1678 for(;ch<MAXCHAN;ch++)
1679 {
1680 if (!(spu.dwChannelsAudible & (1<<ch)))
1681 continue;
1682 if (spu.s_chan[ch].bFMod == 2)
1683 fmod_chans |= 1 << ch;
1684 if (spu.s_chan[ch].bNoise)
1685 noise_chans |= 1 << ch;
1686 if((spu.spuCtrl&CTRL_IRQ) && spu.s_chan[ch].pCurr <= spu.pSpuIrq && spu.s_chan[ch].pLoop <= spu.pSpuIrq)
1687 irq_chans |= 1 << ch;
1688 }
1689
1690 *chans_out = spu.dwChannelsAudible;
1691 *run_chans = ~spu.dwChannelsAudible & ~spu.dwChannelDead & irq_chans;
1692 *fmod_chans_out = fmod_chans;
1693 *noise_chans_out = noise_chans;
1694}
1695
1696// vim:shiftwidth=1:expandtab