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