spu: fix decode buffers
[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
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 "arm_features.h"
29
30 #ifdef ENABLE_NLS
31 #include <libintl.h>
32 #include <locale.h>
33 #define _(x)  gettext(x)
34 #define N_(x) (x)
35 #else
36 #define _(x)  (x)
37 #define N_(x) (x)
38 #endif
39
40 #ifdef __ARM_ARCH_7A__
41  #define ssat32_to_16(v) \
42   asm("ssat %0,#16,%1" : "=r" (v) : "r" (v))
43 #else
44  #define ssat32_to_16(v) do { \
45   if (v < -32768) v = -32768; \
46   else if (v > 32767) v = 32767; \
47  } while (0)
48 #endif
49
50 #define PSXCLK  33868800        /* 33.8688 MHz */
51
52 /*
53 #if defined (USEMACOSX)
54 static char * libraryName     = N_("Mac OS X Sound");
55 #elif defined (USEALSA)
56 static char * libraryName     = N_("ALSA Sound");
57 #elif defined (USEOSS)
58 static char * libraryName     = N_("OSS Sound");
59 #elif defined (USESDL)
60 static char * libraryName     = N_("SDL Sound");
61 #elif defined (USEPULSEAUDIO)
62 static char * libraryName     = N_("PulseAudio Sound");
63 #else
64 static char * libraryName     = N_("NULL Sound");
65 #endif
66
67 static char * libraryInfo     = N_("P.E.Op.S. Sound Driver V1.7\nCoded by Pete Bernert and the P.E.Op.S. team\n");
68 */
69
70 // globals
71
72 // psx buffer / addresses
73
74 unsigned short  regArea[10000];
75 unsigned short  spuMem[256*1024];
76 unsigned char * spuMemC;
77 unsigned char * pSpuIrq=0;
78 unsigned char * pSpuBuffer;
79
80 // user settings
81
82 int             iVolume=768; // 1024 is 1.0
83 int             iXAPitch=1;
84 int             iUseReverb=2;
85 int             iUseInterpolation=2;
86
87 // MAIN infos struct for each channel
88
89 SPUCHAN         s_chan[MAXCHAN+1];                     // channel + 1 infos (1 is security for fmod handling)
90 REVERBInfo      rvb;
91
92 unsigned int    dwNoiseVal;                            // global noise generator
93 unsigned int    dwNoiseCount;
94
95 unsigned short  spuCtrl=0;                             // some vars to store psx reg infos
96 unsigned short  spuStat=0;
97 unsigned short  spuIrq=0;
98 unsigned long   spuAddr=0xffffffff;                    // address into spu mem
99 int             bSpuInit=0;
100 int             bSPUIsOpen=0;
101
102 unsigned int dwNewChannel=0;                           // flags for faster testing, if new channel starts
103 unsigned int dwChannelOn=0;                            // not silent channels
104 unsigned int dwPendingChanOff=0;
105 unsigned int dwChannelDead=0;                          // silent+not useful channels
106
107 void (CALLBACK *irqCallback)(void)=0;                  // func of main emu, called on spu irq
108 void (CALLBACK *cddavCallback)(unsigned short,unsigned short)=0;
109
110 // certain globals (were local before, but with the new timeproc I need em global)
111
112 static const int f[8][2] = {   {    0,  0  },
113                         {   60,  0  },
114                         {  115, -52 },
115                         {   98, -55 },
116                         {  122, -60 } };
117 int ChanBuf[NSSIZE+3];
118 int SSumLR[(NSSIZE+3)*2];
119 int iFMod[NSSIZE];
120 int iCycle = 0;
121 short * pS;
122
123 static int decode_dirty_ch;
124 int decode_pos;
125 int had_dma;
126 int lastch=-1;             // last channel processed on spu irq in timer mode
127 static int lastns=0;       // last ns pos
128 static int cycles_since_update;
129
130 #define CDDA_BUFFER_SIZE (16384 * sizeof(uint32_t)) // must be power of 2
131
132 ////////////////////////////////////////////////////////////////////////
133 // CODE AREA
134 ////////////////////////////////////////////////////////////////////////
135
136 // dirty inline func includes
137
138 #include "reverb.c"
139 #include "adsr.c"
140
141 ////////////////////////////////////////////////////////////////////////
142 // helpers for simple interpolation
143
144 //
145 // easy interpolation on upsampling, no special filter, just "Pete's common sense" tm
146 //
147 // instead of having n equal sample values in a row like:
148 //       ____
149 //           |____
150 //
151 // we compare the current delta change with the next delta change.
152 //
153 // if curr_delta is positive,
154 //
155 //  - and next delta is smaller (or changing direction):
156 //         \.
157 //          -__
158 //
159 //  - and next delta significant (at least twice) bigger:
160 //         --_
161 //            \.
162 //
163 //  - and next delta is nearly same:
164 //          \.
165 //           \.
166 //
167 //
168 // if curr_delta is negative,
169 //
170 //  - and next delta is smaller (or changing direction):
171 //          _--
172 //         /
173 //
174 //  - and next delta significant (at least twice) bigger:
175 //            /
176 //         __- 
177 //
178 //  - and next delta is nearly same:
179 //           /
180 //          /
181 //
182
183
184 INLINE void InterpolateUp(int ch)
185 {
186  if(s_chan[ch].SB[32]==1)                              // flag == 1? calc step and set flag... and don't change the value in this pass
187   {
188    const int id1=s_chan[ch].SB[30]-s_chan[ch].SB[29];  // curr delta to next val
189    const int id2=s_chan[ch].SB[31]-s_chan[ch].SB[30];  // and next delta to next-next val :)
190
191    s_chan[ch].SB[32]=0;
192
193    if(id1>0)                                           // curr delta positive
194     {
195      if(id2<id1)
196       {s_chan[ch].SB[28]=id1;s_chan[ch].SB[32]=2;}
197      else
198      if(id2<(id1<<1))
199       s_chan[ch].SB[28]=(id1*s_chan[ch].sinc)/0x10000L;
200      else
201       s_chan[ch].SB[28]=(id1*s_chan[ch].sinc)/0x20000L; 
202     }
203    else                                                // curr delta negative
204     {
205      if(id2>id1)
206       {s_chan[ch].SB[28]=id1;s_chan[ch].SB[32]=2;}
207      else
208      if(id2>(id1<<1))
209       s_chan[ch].SB[28]=(id1*s_chan[ch].sinc)/0x10000L;
210      else
211       s_chan[ch].SB[28]=(id1*s_chan[ch].sinc)/0x20000L; 
212     }
213   }
214  else
215  if(s_chan[ch].SB[32]==2)                              // flag 1: calc step and set flag... and don't change the value in this pass
216   {
217    s_chan[ch].SB[32]=0;
218
219    s_chan[ch].SB[28]=(s_chan[ch].SB[28]*s_chan[ch].sinc)/0x20000L;
220    //if(s_chan[ch].sinc<=0x8000)
221    //     s_chan[ch].SB[29]=s_chan[ch].SB[30]-(s_chan[ch].SB[28]*((0x10000/s_chan[ch].sinc)-1));
222    //else
223    s_chan[ch].SB[29]+=s_chan[ch].SB[28];
224   }
225  else                                                  // no flags? add bigger val (if possible), calc smaller step, set flag1
226   s_chan[ch].SB[29]+=s_chan[ch].SB[28];
227 }
228
229 //
230 // even easier interpolation on downsampling, also no special filter, again just "Pete's common sense" tm
231 //
232
233 INLINE void InterpolateDown(int ch)
234 {
235  if(s_chan[ch].sinc>=0x20000L)                                 // we would skip at least one val?
236   {
237    s_chan[ch].SB[29]+=(s_chan[ch].SB[30]-s_chan[ch].SB[29])/2; // add easy weight
238    if(s_chan[ch].sinc>=0x30000L)                               // we would skip even more vals?
239     s_chan[ch].SB[29]+=(s_chan[ch].SB[31]-s_chan[ch].SB[30])/2;// add additional next weight
240   }
241 }
242
243 ////////////////////////////////////////////////////////////////////////
244 // helpers for gauss interpolation
245
246 #define gval0 (((short*)(&s_chan[ch].SB[29]))[gpos])
247 #define gval(x) ((int)((short*)(&s_chan[ch].SB[29]))[(gpos+x)&3])
248
249 #include "gauss_i.h"
250
251 ////////////////////////////////////////////////////////////////////////
252
253 #include "xa.c"
254
255 static void do_irq(void)
256 {
257  //if(!(spuStat & STAT_IRQ))
258  {
259   spuStat |= STAT_IRQ;                                 // asserted status?
260   if(irqCallback) irqCallback();
261  }
262 }
263
264 static int check_irq(int ch, unsigned char *pos)
265 {
266  if((spuCtrl & CTRL_IRQ) && pos == pSpuIrq)
267  {
268   //printf("ch%d irq %04x\n", ch, pos - spuMemC);
269   do_irq();
270   return 1;
271  }
272  return 0;
273 }
274
275 ////////////////////////////////////////////////////////////////////////
276 // START SOUND... called by main thread to setup a new sound on a channel
277 ////////////////////////////////////////////////////////////////////////
278
279 INLINE void StartSound(int ch)
280 {
281  StartADSR(ch);
282  StartREVERB(ch);
283
284  // fussy timing issues - do in VoiceOn
285  //s_chan[ch].pCurr=s_chan[ch].pStart;                   // set sample start
286  //s_chan[ch].bStop=0;
287  //s_chan[ch].bOn=1;
288
289  s_chan[ch].SB[26]=0;                                  // init mixing vars
290  s_chan[ch].SB[27]=0;
291  s_chan[ch].iSBPos=28;
292
293  s_chan[ch].SB[29]=0;                                  // init our interpolation helpers
294  s_chan[ch].SB[30]=0;
295
296  if(iUseInterpolation>=2)                              // gauss interpolation?
297       {s_chan[ch].spos=0x30000L;s_chan[ch].SB[28]=0;}  // -> start with more decoding
298  else {s_chan[ch].spos=0x10000L;s_chan[ch].SB[31]=0;}  // -> no/simple interpolation starts with one 44100 decoding
299
300  dwNewChannel&=~(1<<ch);                               // clear new channel bit
301 }
302
303 ////////////////////////////////////////////////////////////////////////
304 // ALL KIND OF HELPERS
305 ////////////////////////////////////////////////////////////////////////
306
307 INLINE int FModChangeFrequency(int ch,int ns)
308 {
309  unsigned int NP=s_chan[ch].iRawPitch;
310  int sinc;
311
312  NP=((32768L+iFMod[ns])*NP)/32768L;
313
314  if(NP>0x3fff) NP=0x3fff;
315  if(NP<0x1)    NP=0x1;
316
317  sinc=NP<<4;                                           // calc frequency
318  if(iUseInterpolation==1)                              // freq change in simple interpolation mode
319   s_chan[ch].SB[32]=1;
320  iFMod[ns]=0;
321
322  return sinc;
323 }                    
324
325 ////////////////////////////////////////////////////////////////////////
326
327 INLINE void StoreInterpolationVal(int ch,int fa)
328 {
329  if(s_chan[ch].bFMod==2)                               // fmod freq channel
330   s_chan[ch].SB[29]=fa;
331  else
332   {
333    ssat32_to_16(fa);
334
335    if(iUseInterpolation>=2)                            // gauss/cubic interpolation
336     {     
337      int gpos = s_chan[ch].SB[28];
338      gval0 = fa;          
339      gpos = (gpos+1) & 3;
340      s_chan[ch].SB[28] = gpos;
341     }
342    else
343    if(iUseInterpolation==1)                            // simple interpolation
344     {
345      s_chan[ch].SB[28] = 0;                    
346      s_chan[ch].SB[29] = s_chan[ch].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'
347      s_chan[ch].SB[30] = s_chan[ch].SB[31];
348      s_chan[ch].SB[31] = fa;
349      s_chan[ch].SB[32] = 1;                            // -> flag: calc new interolation
350     }
351    else s_chan[ch].SB[29]=fa;                          // no interpolation
352   }
353 }
354
355 ////////////////////////////////////////////////////////////////////////
356
357 INLINE int iGetInterpolationVal(int ch, int spos)
358 {
359  int fa;
360
361  if(s_chan[ch].bFMod==2) return s_chan[ch].SB[29];
362
363  switch(iUseInterpolation)
364   {   
365    //--------------------------------------------------//
366    case 3:                                             // cubic interpolation
367     {
368      long xd;int gpos;
369      xd = (spos >> 1)+1;
370      gpos = s_chan[ch].SB[28];
371
372      fa  = gval(3) - 3*gval(2) + 3*gval(1) - gval0;
373      fa *= (xd - (2<<15)) / 6;
374      fa >>= 15;
375      fa += gval(2) - gval(1) - gval(1) + gval0;
376      fa *= (xd - (1<<15)) >> 1;
377      fa >>= 15;
378      fa += gval(1) - gval0;
379      fa *= xd;
380      fa >>= 15;
381      fa = fa + gval0;
382
383     } break;
384    //--------------------------------------------------//
385    case 2:                                             // gauss interpolation
386     {
387      int vl, vr;int gpos;
388      vl = (spos >> 6) & ~3;
389      gpos = s_chan[ch].SB[28];
390      vr=(gauss[vl]*(int)gval0)&~2047;
391      vr+=(gauss[vl+1]*gval(1))&~2047;
392      vr+=(gauss[vl+2]*gval(2))&~2047;
393      vr+=(gauss[vl+3]*gval(3))&~2047;
394      fa = vr>>11;
395     } break;
396    //--------------------------------------------------//
397    case 1:                                             // simple interpolation
398     {
399      if(s_chan[ch].sinc<0x10000L)                      // -> upsampling?
400           InterpolateUp(ch);                           // --> interpolate up
401      else InterpolateDown(ch);                         // --> else down
402      fa=s_chan[ch].SB[29];
403     } break;
404    //--------------------------------------------------//
405    default:                                            // no interpolation
406     {
407      fa=s_chan[ch].SB[29];                  
408     } break;
409    //--------------------------------------------------//
410   }
411
412  return fa;
413 }
414
415 static void decode_block_data(int *dest, const unsigned char *src, int predict_nr, int shift_factor)
416 {
417  int nSample;
418  int fa, s_1, s_2, d, s;
419
420  s_1 = dest[27];
421  s_2 = dest[26];
422
423  for (nSample = 0; nSample < 28; src++)
424  {
425   d = (int)*src;
426   s = (int)(signed short)((d & 0x0f) << 12);
427
428   fa = s >> shift_factor;
429   fa += ((s_1 * f[predict_nr][0])>>6) + ((s_2 * f[predict_nr][1])>>6);
430   s_2=s_1;s_1=fa;
431
432   dest[nSample++] = fa;
433
434   s = (int)(signed short)((d & 0xf0) << 8);
435   fa = s >> shift_factor;
436   fa += ((s_1 * f[predict_nr][0])>>6) + ((s_2 * f[predict_nr][1])>>6);
437   s_2=s_1;s_1=fa;
438
439   dest[nSample++] = fa;
440  }
441 }
442
443 static int decode_block(int ch)
444 {
445  unsigned char *start;
446  int predict_nr,shift_factor,flags;
447  int ret = 0;
448
449  start=s_chan[ch].pCurr;                   // set up the current pos
450
451  if(s_chan[ch].prevflags&1)                // 1: stop/loop
452  {
453   if(!(s_chan[ch].prevflags&2))
454   {
455    dwChannelOn&=~(1<<ch);                  // -> turn everything off
456    s_chan[ch].bStop=1;
457    s_chan[ch].ADSRX.EnvelopeVol=0;
458   }
459
460   start = s_chan[ch].pLoop;
461  }
462  else
463   ret = check_irq(ch, start);              // hack, see check_irq below..
464
465  predict_nr=(int)start[0];
466  shift_factor=predict_nr&0xf;
467  predict_nr >>= 4;
468
469  decode_block_data(s_chan[ch].SB, start + 2, predict_nr, shift_factor);
470
471  flags=(int)start[1];
472  if(flags&4)
473   s_chan[ch].pLoop=start;                  // loop adress
474
475  start+=16;
476
477  if(flags&1) {                             // 1: stop/loop
478   start = s_chan[ch].pLoop;
479   ret |= check_irq(ch, start);             // hack.. :(
480  }
481
482  if (start - spuMemC >= 0x80000)
483   start = spuMemC;
484
485  s_chan[ch].pCurr = start;                 // store values for next cycle
486  s_chan[ch].prevflags = flags;
487
488  return ret;
489 }
490
491 // do block, but ignore sample data
492 static int skip_block(int ch)
493 {
494  unsigned char *start = s_chan[ch].pCurr;
495  int flags = start[1];
496  int ret = check_irq(ch, start);
497
498  if(s_chan[ch].prevflags & 1)
499   start = s_chan[ch].pLoop;
500
501  if(flags & 4)
502   s_chan[ch].pLoop = start;
503
504  start += 16;
505
506  if(flags & 1)
507   start = s_chan[ch].pLoop;
508
509  s_chan[ch].pCurr = start;
510  s_chan[ch].prevflags = flags;
511
512  return ret;
513 }
514
515 #define make_do_samples(name, fmod_code, interp_start, interp1_code, interp2_code, interp_end) \
516 static int do_samples_##name(int ch, int ns, int ns_to) \
517 {                                            \
518  int sinc = s_chan[ch].sinc;                 \
519  int spos = s_chan[ch].spos;                 \
520  int sbpos = s_chan[ch].iSBPos;              \
521  int *SB = s_chan[ch].SB;                    \
522  int ret = -1;                               \
523  int d, fa;                                  \
524  interp_start;                               \
525                                              \
526  for (; ns < ns_to; ns++)                    \
527  {                                           \
528   fmod_code;                                 \
529                                              \
530   while (spos >= 0x10000)                    \
531   {                                          \
532    if(sbpos == 28)                           \
533    {                                         \
534     sbpos = 0;                               \
535     d = decode_block(ch);                    \
536     if(d)                                    \
537      ret = ns_to = ns + 1;                   \
538    }                                         \
539                                              \
540    fa = SB[sbpos++];                         \
541    interp1_code;                             \
542    spos -= 0x10000;                          \
543   }                                          \
544                                              \
545   interp2_code;                              \
546   spos += sinc;                              \
547  }                                           \
548                                              \
549  s_chan[ch].sinc = sinc;                     \
550  s_chan[ch].spos = spos;                     \
551  s_chan[ch].iSBPos = sbpos;                  \
552  interp_end;                                 \
553                                              \
554  return ret;                                 \
555 }
556
557 #define fmod_recv_check \
558   if(s_chan[ch].bFMod==1 && iFMod[ns]) \
559     sinc = FModChangeFrequency(ch,ns)
560
561 make_do_samples(default, fmod_recv_check, ,
562   StoreInterpolationVal(ch, fa),
563   ChanBuf[ns] = iGetInterpolationVal(ch, spos), )
564 make_do_samples(noint, , fa = s_chan[ch].SB[29], , ChanBuf[ns] = fa, s_chan[ch].SB[29] = fa)
565
566 #define simple_interp_store \
567   s_chan[ch].SB[28] = 0; \
568   s_chan[ch].SB[29] = s_chan[ch].SB[30]; \
569   s_chan[ch].SB[30] = s_chan[ch].SB[31]; \
570   s_chan[ch].SB[31] = fa; \
571   s_chan[ch].SB[32] = 1
572
573 #define simple_interp_get \
574   if(sinc<0x10000)          /* -> upsampling? */ \
575        InterpolateUp(ch);   /* --> interpolate up */ \
576   else InterpolateDown(ch); /* --> else down */ \
577   ChanBuf[ns] = s_chan[ch].SB[29]
578
579 make_do_samples(simple, , ,
580   simple_interp_store, simple_interp_get, )
581
582 static int do_samples_noise(int ch, int ns, int ns_to)
583 {
584  int level, shift, bit;
585  int ret = -1, d;
586
587  s_chan[ch].spos += s_chan[ch].sinc * (ns_to - ns);
588  while (s_chan[ch].spos >= 28*0x10000)
589  {
590   d = skip_block(ch);
591   if (d)
592    ret = ns_to;
593   s_chan[ch].spos -= 28*0x10000;
594  }
595
596  // modified from DrHell/shalma, no fraction
597  level = (spuCtrl >> 10) & 0x0f;
598  level = 0x8000 >> level;
599
600  for (; ns < ns_to; ns++)
601  {
602   dwNoiseCount += 2;
603   if (dwNoiseCount >= level)
604   {
605    dwNoiseCount -= level;
606    shift = (dwNoiseVal >> 10) & 0x1f;
607    bit = (0x69696969 >> shift) & 1;
608    if (dwNoiseVal & 0x8000)
609     bit ^= 1;
610    dwNoiseVal = (dwNoiseVal << 1) | bit;
611   }
612
613   ChanBuf[ns] = (signed short)dwNoiseVal;
614  }
615
616  return ret;
617 }
618
619 #ifdef HAVE_ARMV5
620 // asm code; lv and rv must be 0-3fff
621 extern void mix_chan(int start, int count, int lv, int rv);
622 extern void mix_chan_rvb(int start, int count, int lv, int rv);
623 #else
624 static void mix_chan(int start, int count, int lv, int rv)
625 {
626  int *dst = SSumLR + start * 2;
627  const int *src = ChanBuf + start;
628  int l, r;
629
630  while (count--)
631   {
632    int sval = *src++;
633
634    l = (sval * lv) >> 14;
635    r = (sval * rv) >> 14;
636    *dst++ += l;
637    *dst++ += r;
638   }
639 }
640
641 static void mix_chan_rvb(int start, int count, int lv, int rv)
642 {
643  int *dst = SSumLR + start * 2;
644  int *drvb = sRVBStart + start * 2;
645  const int *src = ChanBuf + start;
646  int l, r;
647
648  while (count--)
649   {
650    int sval = *src++;
651
652    l = (sval * lv) >> 14;
653    r = (sval * rv) >> 14;
654    *dst++ += l;
655    *dst++ += r;
656    *drvb++ += l;
657    *drvb++ += r;
658   }
659 }
660 #endif
661
662 // 0x0800-0x0bff  Voice 1
663 // 0x0c00-0x0fff  Voice 3
664 static void noinline do_decode_bufs(int which, int start, int count)
665 {
666  const int *src = ChanBuf + start;
667  unsigned short *dst = &spuMem[0x800/2 + which*0x400/2];
668  int cursor = decode_pos;
669
670  while (count-- > 0)
671   {
672    dst[cursor] = *src++;
673    cursor = (cursor + 1) & 0x1ff;
674   }
675
676  // decode_pos is updated and irqs are checked later, after voice loop
677 }
678
679 ////////////////////////////////////////////////////////////////////////
680 // MAIN SPU FUNCTION
681 // here is the main job handler...
682 // basically the whole sound processing is done in this fat func!
683 ////////////////////////////////////////////////////////////////////////
684
685 static int do_samples(int forced_updates)
686 {
687  int volmult = iVolume;
688  int ns,ns_from,ns_to;
689  int ch,d,silentch;
690  int bIRQReturn=0;
691
692  while(1)
693   {
694    // ok, at the beginning we are looking if there is
695    // enuff free place in the dsound/oss buffer to
696    // fill in new data, or if there is a new channel to start.
697    // if not, we wait (thread) or return (timer/spuasync)
698    // until enuff free place is available/a new channel gets
699    // started
700
701    if(!forced_updates && out_current->busy())          // still enuff data in sound buffer?
702     {
703      return 0;
704     }
705
706    cycles_since_update = 0;
707    if(forced_updates > 0)
708     forced_updates--;
709
710    //--------------------------------------------------// continue from irq handling in timer mode? 
711
712    ns_from=0;
713    ns_to=NSSIZE;
714    ch=0;
715    if(lastch>=0)                                       // will be -1 if no continue is pending
716     {
717      ch=lastch; ns_from=lastns; lastch=-1;             // -> setup all kind of vars to continue
718     }
719
720    silentch=~(dwChannelOn|dwNewChannel);
721
722    //--------------------------------------------------//
723    //- main channel loop                              -// 
724    //--------------------------------------------------//
725     {
726      for(;ch<MAXCHAN;ch++)                             // loop em all... we will collect 1 ms of sound of each playing channel
727       {
728        if(dwNewChannel&(1<<ch)) StartSound(ch);        // start new sound
729        if(!(dwChannelOn&(1<<ch))) continue;            // channel not playing? next
730
731        if(s_chan[ch].bNoise)
732         d=do_samples_noise(ch, ns_from, ns_to);
733        else if(s_chan[ch].bFMod==2 || (s_chan[ch].bFMod==0 && iUseInterpolation==0))
734         d=do_samples_noint(ch, ns_from, ns_to);
735        else if(s_chan[ch].bFMod==0 && iUseInterpolation==1)
736         d=do_samples_simple(ch, ns_from, ns_to);
737        else
738         d=do_samples_default(ch, ns_from, ns_to);
739        if(d>=0)
740         {
741          bIRQReturn=1;
742          lastch=ch; 
743          lastns=ns_to=d;
744         }
745
746        MixADSR(ch, ns_from, ns_to);
747
748        if(ch==1 || ch==3)
749         {
750          do_decode_bufs(ch/2, ns_from, ns_to-ns_from);
751          decode_dirty_ch |= 1<<ch;
752         }
753
754        if(s_chan[ch].bFMod==2)                         // fmod freq channel
755         memcpy(iFMod, ChanBuf, sizeof(iFMod));
756        else if(s_chan[ch].bRVBActive)
757         mix_chan_rvb(ns_from,ns_to-ns_from,s_chan[ch].iLeftVolume,s_chan[ch].iRightVolume);
758        else
759         mix_chan(ns_from,ns_to-ns_from,s_chan[ch].iLeftVolume,s_chan[ch].iRightVolume);
760       }
761     }
762
763     // advance "stopped" channels that can cause irqs
764     // (all chans are always playing on the real thing..)
765     if(spuCtrl&CTRL_IRQ)
766      for(ch=0;ch<MAXCHAN;ch++)
767       {
768        if(!(silentch&(1<<ch))) continue;               // already handled
769        if(dwChannelDead&(1<<ch)) continue;
770        if(s_chan[ch].pCurr > pSpuIrq && s_chan[ch].pLoop > pSpuIrq)
771         continue;
772
773        s_chan[ch].spos += s_chan[ch].sinc * (ns_to - ns_from);
774        while(s_chan[ch].spos >= 28 * 0x10000)
775         {
776          unsigned char *start = s_chan[ch].pCurr;
777
778          // no need for bIRQReturn since the channel is silent
779          skip_block(ch);
780          if(start == s_chan[ch].pCurr)
781           {
782            // looping on self
783            dwChannelDead |= 1<<ch;
784            s_chan[ch].spos = 0;
785            break;
786           }
787
788          s_chan[ch].spos -= 28 * 0x10000;
789         }
790       }
791
792     if(bIRQReturn)                                     // special return for "spu irq - wait for cpu action"
793       return 0;
794
795   if(unlikely(silentch & decode_dirty_ch & (1<<1)))    // must clear silent channel decode buffers
796    {
797     memset(&spuMem[0x800/2], 0, 0x400);
798     decode_dirty_ch &= ~(1<<1);
799    }
800   if(unlikely(silentch & decode_dirty_ch & (1<<3)))
801    {
802     memset(&spuMem[0xc00/2], 0, 0x400);
803     decode_dirty_ch &= ~(1<<3);
804    }
805
806   //---------------------------------------------------//
807   //- here we have another 1 ms of sound data
808   //---------------------------------------------------//
809   // mix XA infos (if any)
810
811   MixXA();
812   
813   ///////////////////////////////////////////////////////
814   // mix all channels (including reverb) into one buffer
815
816   if(iUseReverb)
817    REVERBDo();
818
819   if((spuCtrl&0x4000)==0) // muted? (rare, don't optimize for this)
820    {
821     memset(pS, 0, NSSIZE * 2 * sizeof(pS[0]));
822     pS += NSSIZE*2;
823    }
824   else
825   for (ns = 0; ns < NSSIZE*2; )
826    {
827     d = SSumLR[ns]; SSumLR[ns] = 0;
828     d = d * volmult >> 10;
829     ssat32_to_16(d);
830     *pS++ = d;
831     ns++;
832
833     d = SSumLR[ns]; SSumLR[ns] = 0;
834     d = d * volmult >> 10;
835     ssat32_to_16(d);
836     *pS++ = d;
837     ns++;
838    }
839
840   //////////////////////////////////////////////////////                   
841   // special irq handling in the decode buffers (0x0000-0x1000)
842   // we know: 
843   // the decode buffers are located in spu memory in the following way:
844   // 0x0000-0x03ff  CD audio left
845   // 0x0400-0x07ff  CD audio right
846   // 0x0800-0x0bff  Voice 1
847   // 0x0c00-0x0fff  Voice 3
848   // and decoded data is 16 bit for one sample
849   // we assume: 
850   // even if voices 1/3 are off or no cd audio is playing, the internal
851   // play positions will move on and wrap after 0x400 bytes.
852   // Therefore: we just need a pointer from spumem+0 to spumem+3ff, and 
853   // increase this pointer on each sample by 2 bytes. If this pointer
854   // (or 0x400 offsets of this pointer) hits the spuirq address, we generate
855   // an IRQ. Only problem: the "wait for cpu" option is kinda hard to do here
856   // in some of Peops timer modes. So: we ignore this option here (for now).
857
858   if(unlikely((spuCtrl&CTRL_IRQ) && pSpuIrq && pSpuIrq<spuMemC+0x1000))
859    {
860     int irq_pos=(pSpuIrq-spuMemC)/2 & 0x1ff;
861     if((decode_pos <= irq_pos && irq_pos < decode_pos+NSSIZE)
862        || (decode_pos+NSSIZE > 0x200 && irq_pos < ((decode_pos+NSSIZE) & 0x1ff)))
863      {
864       //printf("decoder irq %x\n", decode_pos);
865       do_irq();
866      }
867    }
868   decode_pos = (decode_pos + NSSIZE) & 0x1ff;
869
870   InitREVERB();
871
872   // feed the sound
873   // wanna have around 1/60 sec (16.666 ms) updates
874   if (iCycle++ > 16/FRAG_MSECS)
875    {
876     out_current->feed(pSpuBuffer,
877                         ((unsigned char *)pS) - ((unsigned char *)pSpuBuffer));
878     pS = (short *)pSpuBuffer;
879     iCycle = 0;
880    }
881  }
882
883  return 0;
884 }
885
886 // SPU ASYNC... even newer epsxe func
887 //  1 time every 'cycle' cycles... harhar
888
889 // rearmed: called every 2ms now
890
891 void CALLBACK SPUasync(unsigned long cycle)
892 {
893  static int old_ctrl;
894  int forced_updates = 0;
895  int do_update = 0;
896
897  if(!bSpuInit) return;                               // -> no init, no call
898
899  cycles_since_update += cycle;
900
901  if(dwNewChannel || had_dma)
902   {
903    forced_updates = 1;
904    do_update = 1;
905    had_dma = 0;
906   }
907
908  if((spuCtrl&CTRL_IRQ) && (((spuCtrl^old_ctrl)&CTRL_IRQ) // irq was enabled
909     || cycles_since_update > PSXCLK/60 / 4)) {
910   do_update = 1;
911   forced_updates = cycles_since_update / (PSXCLK/44100) / NSSIZE;
912  }
913  // with no irqs, once per frame should be fine (using a bit more because of BIAS)
914  else if(cycles_since_update > PSXCLK/60 * 5/4)
915   do_update = 1;
916
917  old_ctrl = spuCtrl;
918
919  if(do_update)
920   do_samples(forced_updates);
921 }
922
923 // SPU UPDATE... new epsxe func
924 //  1 time every 32 hsync lines
925 //  (312/32)x50 in pal
926 //  (262/32)x60 in ntsc
927
928 // since epsxe 1.5.2 (linux) uses SPUupdate, not SPUasync, I will
929 // leave that func in the linux port, until epsxe linux is using
930 // the async function as well
931
932 void CALLBACK SPUupdate(void)
933 {
934  SPUasync(0);
935 }
936
937 // XA AUDIO
938
939 void CALLBACK SPUplayADPCMchannel(xa_decode_t *xap)
940 {
941  if(!xap)       return;
942  if(!xap->freq) return;                                // no xa freq ? bye
943
944  FeedXA(xap);                                          // call main XA feeder
945 }
946
947 // CDDA AUDIO
948 int CALLBACK SPUplayCDDAchannel(short *pcm, int nbytes)
949 {
950  if (!pcm)      return -1;
951  if (nbytes<=0) return -1;
952
953  return FeedCDDA((unsigned char *)pcm, nbytes);
954 }
955
956 // to be called after state load
957 void ClearWorkingState(void)
958 {
959  memset(SSumLR,0,sizeof(SSumLR));                      // init some mixing buffers
960  memset(iFMod,0,sizeof(iFMod));     
961  pS=(short *)pSpuBuffer;                               // setup soundbuffer pointer
962 }
963
964 // SETUPSTREAMS: init most of the spu buffers
965 void SetupStreams(void)
966
967  int i;
968
969  pSpuBuffer=(unsigned char *)malloc(32768);            // alloc mixing buffer
970
971  if(iUseReverb==1) i=88200*2;
972  else              i=NSSIZE*2;
973
974  sRVBStart = (int *)malloc(i*4);                       // alloc reverb buffer
975  memset(sRVBStart,0,i*4);
976  sRVBEnd  = sRVBStart + i;
977  sRVBPlay = sRVBStart;
978
979  XAStart =                                             // alloc xa buffer
980   (uint32_t *)malloc(44100 * sizeof(uint32_t));
981  XAEnd   = XAStart + 44100;
982  XAPlay  = XAStart;
983  XAFeed  = XAStart;
984
985  CDDAStart =                                           // alloc cdda buffer
986   (uint32_t *)malloc(CDDA_BUFFER_SIZE);
987  CDDAEnd   = CDDAStart + 16384;
988  CDDAPlay  = CDDAStart;
989  CDDAFeed  = CDDAStart;
990
991  for(i=0;i<MAXCHAN;i++)                                // loop sound channels
992   {
993 // we don't use mutex sync... not needed, would only 
994 // slow us down:
995 //   s_chan[i].hMutex=CreateMutex(NULL,FALSE,NULL);
996    s_chan[i].ADSRX.SustainLevel = 0xf;                 // -> init sustain
997    s_chan[i].pLoop=spuMemC;
998    s_chan[i].pCurr=spuMemC;
999   }
1000
1001  ClearWorkingState();
1002
1003  bSpuInit=1;                                           // flag: we are inited
1004 }
1005
1006 // REMOVESTREAMS: free most buffer
1007 void RemoveStreams(void)
1008
1009  free(pSpuBuffer);                                     // free mixing buffer
1010  pSpuBuffer = NULL;
1011  free(sRVBStart);                                      // free reverb buffer
1012  sRVBStart = NULL;
1013  free(XAStart);                                        // free XA buffer
1014  XAStart = NULL;
1015  free(CDDAStart);                                      // free CDDA buffer
1016  CDDAStart = NULL;
1017 }
1018
1019 // INIT/EXIT STUFF
1020
1021 // SPUINIT: this func will be called first by the main emu
1022 long CALLBACK SPUinit(void)
1023 {
1024  spuMemC = (unsigned char *)spuMem;                    // just small setup
1025  memset((void *)&rvb, 0, sizeof(REVERBInfo));
1026  InitADSR();
1027
1028  spuIrq = 0;
1029  spuAddr = 0xffffffff;
1030  spuMemC = (unsigned char *)spuMem;
1031  decode_pos = 0;
1032  memset((void *)s_chan, 0, (MAXCHAN + 1) * sizeof(SPUCHAN));
1033  pSpuIrq = 0;
1034  lastch = -1;
1035
1036  SetupStreams();                                       // prepare streaming
1037
1038  return 0;
1039 }
1040
1041 // SPUOPEN: called by main emu after init
1042 long CALLBACK SPUopen(void)
1043 {
1044  if (bSPUIsOpen) return 0;                             // security for some stupid main emus
1045
1046  SetupSound();                                         // setup sound (before init!)
1047
1048  bSPUIsOpen = 1;
1049
1050  return PSE_SPU_ERR_SUCCESS;
1051 }
1052
1053 // SPUCLOSE: called before shutdown
1054 long CALLBACK SPUclose(void)
1055 {
1056  if (!bSPUIsOpen) return 0;                            // some security
1057
1058  bSPUIsOpen = 0;                                       // no more open
1059
1060  out_current->finish();                                // no more sound handling
1061
1062  return 0;
1063 }
1064
1065 // SPUSHUTDOWN: called by main emu on final exit
1066 long CALLBACK SPUshutdown(void)
1067 {
1068  SPUclose();
1069  RemoveStreams();                                      // no more streaming
1070  bSpuInit=0;
1071
1072  return 0;
1073 }
1074
1075 // SPUTEST: we don't test, we are always fine ;)
1076 long CALLBACK SPUtest(void)
1077 {
1078  return 0;
1079 }
1080
1081 // SPUCONFIGURE: call config dialog
1082 long CALLBACK SPUconfigure(void)
1083 {
1084 #ifdef _MACOSX
1085  DoConfiguration();
1086 #else
1087 // StartCfgTool("CFG");
1088 #endif
1089  return 0;
1090 }
1091
1092 // SPUABOUT: show about window
1093 void CALLBACK SPUabout(void)
1094 {
1095 #ifdef _MACOSX
1096  DoAbout();
1097 #else
1098 // StartCfgTool("ABOUT");
1099 #endif
1100 }
1101
1102 // SETUP CALLBACKS
1103 // this functions will be called once, 
1104 // passes a callback that should be called on SPU-IRQ/cdda volume change
1105 void CALLBACK SPUregisterCallback(void (CALLBACK *callback)(void))
1106 {
1107  irqCallback = callback;
1108 }
1109
1110 void CALLBACK SPUregisterCDDAVolume(void (CALLBACK *CDDAVcallback)(unsigned short,unsigned short))
1111 {
1112  cddavCallback = CDDAVcallback;
1113 }
1114
1115 // COMMON PLUGIN INFO FUNCS
1116 /*
1117 char * CALLBACK PSEgetLibName(void)
1118 {
1119  return _(libraryName);
1120 }
1121
1122 unsigned long CALLBACK PSEgetLibType(void)
1123 {
1124  return  PSE_LT_SPU;
1125 }
1126
1127 unsigned long CALLBACK PSEgetLibVersion(void)
1128 {
1129  return (1 << 16) | (6 << 8);
1130 }
1131
1132 char * SPUgetLibInfos(void)
1133 {
1134  return _(libraryInfo);
1135 }
1136 */
1137
1138 // debug
1139 void spu_get_debug_info(int *chans_out, int *run_chans, int *fmod_chans_out, int *noise_chans_out)
1140 {
1141  int ch = 0, fmod_chans = 0, noise_chans = 0, irq_chans = 0;
1142
1143  for(;ch<MAXCHAN;ch++)
1144  {
1145   if (!(dwChannelOn & (1<<ch)))
1146    continue;
1147   if (s_chan[ch].bFMod == 2)
1148    fmod_chans |= 1 << ch;
1149   if (s_chan[ch].bNoise)
1150    noise_chans |= 1 << ch;
1151   if((spuCtrl&CTRL_IRQ) && s_chan[ch].pCurr <= pSpuIrq && s_chan[ch].pLoop <= pSpuIrq)
1152    irq_chans |= 1 << ch;
1153  }
1154
1155  *chans_out = dwChannelOn;
1156  *run_chans = ~dwChannelOn & ~dwChannelDead & irq_chans;
1157  *fmod_chans_out = fmod_chans;
1158  *noise_chans_out = noise_chans;
1159 }
1160
1161 // vim:shiftwidth=1:expandtab