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