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