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