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