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