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