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