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