Audio.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616
  1. #include <windows.h>
  2. #include <math.h>
  3. #define _AUDIO_
  4. #include "audio.h"
  5. HANDLE hAudioThread;
  6. DWORD AudioTId;
  7. WAVEFORMATEX wf;
  8. HWND hwndApp;
  9. BOOL AudioNeedRestore;
  10. char logtt[128];
  11. void PrintLog(LPSTR l);
  12. int InitDirectSound( HWND );
  13. BOOL CALLBACK EnumerateSoundDevice(GUID FAR *, LPSTR, LPSTR, LPVOID );
  14. void Audio_MixSound(int DestAddr, int SrcAddr, int MixLen, int LVolume, int RVolume);
  15. void Audio_MixChannels();
  16. void Audio_MixAmbient();
  17. void Audio_MixAmbient3d();
  18. DWORD WINAPI ProcessAudioThread (LPVOID ptr)
  19. {
  20. for (;;) {
  21. if (iSoundActive)
  22. ProcessAudio();
  23. Sleep(70);
  24. }
  25. return 0;
  26. }
  27. void Init_SetCooperative()
  28. {
  29. }
  30. int InitDirectSound( HWND hwnd)
  31. {
  32. PrintLog("\n");
  33. PrintLog("==Init Direct Sound==\n");
  34. HRESULT hres;
  35. iTotalSoundDevices = 0;
  36. lpSoundBuffer = (char*) _SoundBufferData;
  37. if( !lpSoundBuffer )
  38. return 0;
  39. PrintLog("Back Sound Buffer created.\n");
  40. for( int i = 0; i < MAX_SOUND_DEVICE; i++ )
  41. sdd[i].DSC.dwSize = sizeof( DSCAPS );
  42. hres = DirectSoundEnumerate( (LPDSENUMCALLBACK)EnumerateSoundDevice, NULL);
  43. if( hres != DS_OK ) {
  44. wsprintf(logtt, "DirectSoundEnumerate Error: %Xh\n", hres);
  45. PrintLog(logtt);
  46. return 0;
  47. }
  48. PrintLog("DirectSoundEnumerate: Ok\n");
  49. iTotal16SD = 0;
  50. for( i = 0; i < iTotalSoundDevices; i++ ) {
  51. LPDIRECTSOUND lpds;
  52. if( DirectSoundCreate( &sdd[i].Guid, &lpds, NULL ) != DS_OK ) continue;
  53. if( lpds->GetCaps( &sdd[i].DSC ) != DS_OK ) continue;
  54. if( sdd[i].DSC.dwFlags & (DSCAPS_PRIMARY16BIT | DSCAPS_PRIMARYSTEREO | DSCAPS_SECONDARY16BIT | DSCAPS_SECONDARYSTEREO ) ) {
  55. sdd[i].status = 1;
  56. iTotal16SD++;
  57. wsprintf(logtt,"Acceptable device: %d\n",i);
  58. PrintLog(logtt);
  59. }
  60. }
  61. if (!iTotal16SD) return 0;
  62. iCurrentDriver = 0;
  63. while( !sdd[iCurrentDriver].status )
  64. iCurrentDriver++;
  65. wsprintf(logtt,"Device selected : %d\n",iCurrentDriver);
  66. PrintLog(logtt);
  67. hres = DirectSoundCreate( &sdd[iCurrentDriver].Guid, &lpDS, NULL );
  68. if( (hres != DS_OK) || (!lpDS) ) {
  69. wsprintf(logtt, "DirectSoundCreate Error: %Xh\n", hres);
  70. PrintLog(logtt);
  71. return 0;
  72. }
  73. PrintLog("DirectSoundCreate: Ok\n");
  74. PrimaryMode = TRUE;
  75. PrintLog("Attempting to set WRITEPRIMARY CooperativeLevel:\n");
  76. hres = lpDS->SetCooperativeLevel( hwnd, DSSCL_WRITEPRIMARY );
  77. if (hres != DS_OK) {
  78. wsprintf(logtt, "SetCooperativeLevel Error: %Xh\n", hres);
  79. PrintLog(logtt);
  80. PrimaryMode = FALSE;
  81. } else
  82. PrintLog("Set Cooperative : Ok\n");
  83. if (!PrimaryMode) {
  84. PrintLog("Attempting to set EXCLUSIVE CooperativeLevel:\n");
  85. hres = lpDS->SetCooperativeLevel( hwnd, DSSCL_EXCLUSIVE);
  86. if (hres != DS_OK) {
  87. wsprintf(logtt, "==>>SetCooperativeLevel Error: %Xh\n", hres);
  88. PrintLog(logtt);
  89. return 0;
  90. }
  91. PrintLog("Set Cooperative : Ok\n");
  92. }
  93. /*======= creating primary buffer ==============*/
  94. CopyMemory( &WaveFormat, &wf, sizeof( WAVEFORMATEX ) );
  95. DSBUFFERDESC dsbd;
  96. dsbd.dwSize = sizeof( DSBUFFERDESC );
  97. dsbd.dwFlags = DSBCAPS_PRIMARYBUFFER;
  98. dsbd.dwBufferBytes = 0;
  99. dsbd.lpwfxFormat = NULL;
  100. dsbd.dwReserved = 0;
  101. hres = lpDS->CreateSoundBuffer( &dsbd, &lpdsPrimary, NULL );
  102. if( hres != DS_OK ) {
  103. wsprintf(logtt, "==>>CreatePrimarySoundBuffer Error: %Xh\n", hres);
  104. PrintLog(logtt);
  105. return 0;
  106. }
  107. PrintLog("CreateSoundBuffer: Ok (Primary)\n");
  108. lpdsWork = lpdsPrimary;
  109. hres = lpdsPrimary->SetFormat( &wf );
  110. if( hres != DS_OK ) {
  111. wsprintf(logtt, "SetFormat Error: %Xh\n", hres);
  112. PrintLog(logtt);
  113. return 0;
  114. }
  115. PrintLog("SetFormat : Ok\n");
  116. if (PrimaryMode) goto SKIPSECONDARY;
  117. // ========= creating secondary ================//
  118. dsbd.dwSize = sizeof( DSBUFFERDESC );
  119. dsbd.dwFlags = 0;
  120. dsbd.dwBufferBytes = 2*8192;
  121. dsbd.lpwfxFormat = &wf;
  122. dsbd.dwReserved = 0;
  123. hres = lpDS->CreateSoundBuffer( &dsbd, &lpdsSecondary, NULL );
  124. if( hres != DS_OK ) {
  125. wsprintf(logtt, "CreateSecondarySoundBuffer Error: %Xh\n", hres);
  126. PrintLog(logtt);
  127. return 0;
  128. }
  129. PrintLog("CreateSoundBuffer: Ok (Secondary)\n");
  130. lpdsWork = lpdsSecondary;
  131. SKIPSECONDARY:
  132. DSBCAPS dsbc;
  133. dsbc.dwSize = sizeof( DSBCAPS );
  134. lpdsWork->GetCaps( &dsbc );
  135. iBufferLength = dsbc.dwBufferBytes;
  136. iBufferLength /= 8192;
  137. hres = lpdsWork->Play( 0, 0, DSBPLAY_LOOPING );
  138. if( hres != DS_OK ) {
  139. wsprintf(logtt, "Play Error: %Xh\n", hres);
  140. PrintLog(logtt);
  141. return 0;
  142. }
  143. PrintLog("Play : Ok\n");
  144. iSoundActive = 1;
  145. FillMemory( channel, sizeof( CHANNEL )*MAX_CHANNEL, 0 );
  146. ambient.iLength = 0;
  147. hAudioThread = CreateThread(NULL, 0, ProcessAudioThread, NULL, 0, &AudioTId);
  148. SetThreadPriority(hAudioThread, THREAD_PRIORITY_HIGHEST);
  149. PrintLog("Direct Sound activated.\n");
  150. return 1;
  151. }
  152. void InitAudioSystem(HWND hw)
  153. {
  154. hwndApp = hw;
  155. wf.wFormatTag = WAVE_FORMAT_PCM;
  156. wf.nChannels = 2;
  157. wf.nSamplesPerSec = 11025*2;
  158. wf.nAvgBytesPerSec = 44100*2;
  159. wf.nBlockAlign = 4;
  160. wf.wBitsPerSample = 16;
  161. wf.cbSize = 0;
  162. if( !InitDirectSound( hwndApp ) )
  163. PrintLog("Sound System failed\n");
  164. }
  165. void AudioStop()
  166. {
  167. FillMemory(&ambient, sizeof(ambient), 0);
  168. FillMemory(&mambient, sizeof(mambient), 0);
  169. FillMemory(&ambient2, sizeof(ambient2), 0);
  170. FillMemory(channel, sizeof( CHANNEL )*MAX_CHANNEL, 0 );
  171. AudioNeedRestore = TRUE;
  172. }
  173. void AudioSetCameraPos(float cx, float cy, float cz, float ca, float cb)
  174. {
  175. xCamera = (int) cx;
  176. yCamera = (int) cy;
  177. zCamera = (int) cz;
  178. alphaCamera = ca;
  179. cosa = (float)cos(ca);
  180. sina = (float)sin(ca);
  181. }
  182. void SetAmbient(int length, short int* lpdata, int av)
  183. {
  184. if (!iSoundActive) return;
  185. if (ambient.lpData == lpdata) return;
  186. ambient2 = ambient;
  187. ambient.iLength = length;
  188. ambient.lpData = lpdata;
  189. ambient.iPosition = 0;
  190. ambient.volume = 0;
  191. ambient.avolume = av;
  192. }
  193. void SetAmbient3d(int length, short int* lpdata, float cx, float cy, float cz)
  194. {
  195. if (!iSoundActive) return;
  196. if (mambient.iPosition >= length) mambient.iPosition = 0;
  197. mambient.iLength = length;
  198. mambient.lpData = lpdata;
  199. mambient.x = cx;
  200. mambient.y = cy;
  201. mambient.z = cz;
  202. }
  203. void AddVoice3dv(int length, short int* lpdata, float cx, float cy, float cz, int vol)
  204. {
  205. if (!iSoundActive) return;
  206. if (lpdata == 0) return;
  207. for( int i = 0; i < MAX_CHANNEL; i++ )
  208. if( !channel[i].status ) {
  209. channel[i].iLength = length;
  210. channel[i].lpData = lpdata;
  211. channel[i].iPosition = 0;
  212. channel[i].x = (int)cx;
  213. channel[i].y = (int)cy;
  214. channel[i].z = (int)cz;
  215. channel[i].status = 1;
  216. channel[i].volume = vol;
  217. return;
  218. }
  219. return;
  220. }
  221. void AddVoice3d(int length, short int* lpdata, float cx, float cy, float cz)
  222. {
  223. AddVoice3dv(length, lpdata, cx, cy, cz, 256);
  224. }
  225. void AddVoicev(int length, short int* lpdata, int v)
  226. {
  227. AddVoice3dv(length, lpdata, 0, 0, 0, v);
  228. }
  229. void AddVoice(int length, short int* lpdata)
  230. {
  231. AddVoice3dv(length, lpdata, 0,0,0, 256);
  232. }
  233. BOOL CALLBACK EnumerateSoundDevice( GUID* lpGuid, LPSTR lpstrDescription, LPSTR lpstrModule, LPVOID lpContext)
  234. {
  235. if( lpGuid == NULL )
  236. if( !iTotalSoundDevices )
  237. return TRUE;
  238. else
  239. return FALSE;
  240. wsprintf(logtt,"Device%d: ",iTotalSoundDevices);
  241. PrintLog(logtt);
  242. PrintLog(lpstrDescription);
  243. PrintLog("/");
  244. PrintLog(lpstrModule);
  245. PrintLog("\n");
  246. CopyMemory( &sdd[iTotalSoundDevices].Guid, lpGuid, sizeof( GUID ) );
  247. iTotalSoundDevices++;
  248. return TRUE;
  249. }
  250. void Audio_Shutdown()
  251. {
  252. if (!iSoundActive) return;
  253. lpdsWork->Stop();
  254. TerminateThread(hAudioThread ,0);
  255. }
  256. void Audio_Restore()
  257. {
  258. if (!iSoundActive) return;
  259. lpdsWork->Stop();
  260. lpdsWork->Restore();
  261. HRESULT hres = lpdsWork->Play( 0, 0, DSBPLAY_LOOPING );
  262. if (hres != DS_OK) AudioNeedRestore = TRUE;
  263. else AudioNeedRestore = FALSE;
  264. if (!AudioNeedRestore)
  265. PrintLog("Audio restored.\n");
  266. }
  267. int ProcessAudio()
  268. {
  269. LPVOID lpStart1;
  270. LPVOID lpStart2;
  271. DWORD len1, len2;
  272. HRESULT hres;
  273. static int PrevBlock = 1;
  274. if (AudioNeedRestore) Audio_Restore();
  275. if (AudioNeedRestore) return 1;
  276. hres = lpdsWork->GetCurrentPosition( &len1, &dwWritePos );
  277. hres = lpdsWork->GetCurrentPosition( &len2, &dwWritePos );
  278. if( hres != DS_OK ) { AudioNeedRestore = TRUE; return 0; }
  279. if ( (len1>len2) || (len1<len2+16) )
  280. hres = lpdsWork->GetCurrentPosition( &len2, &dwWritePos );
  281. if (len1+len2==0) {
  282. Sleep(5);
  283. lpdsWork->GetCurrentPosition( &len2, &dwWritePos );
  284. if (!len2) { AudioNeedRestore = TRUE; return 0; }
  285. }
  286. dwPlayPos = len2;
  287. int CurBlock = dwPlayPos / (4096*2);
  288. if (CurBlock==PrevBlock) return 1;
  289. if( (int)dwPlayPos < CurBlock*4096*2 + 2) return 1; // it's no time to put info
  290. FillMemory( lpSoundBuffer, MAX_BUFFER_LENGTH*2, 0 );
  291. Audio_MixChannels();
  292. Audio_MixAmbient();
  293. Audio_MixAmbient3d();
  294. PrevBlock = CurBlock;
  295. int NextBlock = (CurBlock + 1) % iBufferLength;
  296. hres = lpdsWork->Lock(NextBlock*4096*2, 4096*2, &lpStart1, &len1, &lpStart2, &len2, 0 );
  297. if( hres != DS_OK ) {
  298. return 0;
  299. }
  300. CopyMemory( lpStart1, lpSoundBuffer, 4096*2);
  301. hres = lpdsWork->Unlock( lpStart1, len1, lpStart2, len2 );
  302. if( hres != DS_OK )
  303. return 0;
  304. return 1;
  305. }
  306. void CalcLRVolumes(int v0, int x, int y, int z, int &lv, int &rv)
  307. {
  308. if (x==0) {
  309. lv = v0*180;
  310. rv = v0*180;
  311. return; }
  312. v0*=200;
  313. x-=xCamera;
  314. y-=yCamera;
  315. z-=zCamera;
  316. float xx = (float)x * cosa + (float)z * sina;
  317. float yy = (float)y;
  318. float zz = (float)fabs((float)z * cosa - (float)x * sina);
  319. float xa = (float)fabs(xx);
  320. float l = 0.8f;
  321. float r = 0.8f;
  322. float d = (float)sqrt( xx*xx + yy*yy + zz*zz) - MIN_RADIUS;
  323. float k;
  324. if (d<=0) k=1.f;
  325. //else k = (MAX_RADIUS - d) / MAX_RADIUS;
  326. else k = 1224.f / (1224 + d);
  327. if (d>6000) {
  328. d-=6000;
  329. k = k * (4000 - d) / (4000);
  330. }
  331. if (k<0) k=0.f;
  332. float fi = (float)atan2(xa, zz);
  333. r = 0.7f + 0.3f * fi / (3.141593f/2.f);
  334. l = 0.7f - 0.6f * fi / (3.141593f/2.f);
  335. if (xx>0) { lv=(int)(v0*l*k); rv=(int)(v0*r*k); }
  336. else { lv=(int)(v0*r*k); rv=(int)(v0*l*k); }
  337. }
  338. void Audio_MixChannels()
  339. {
  340. int iMixLen;
  341. int srcofs;
  342. int LV, RV;
  343. for( int i = 0; i < MAX_CHANNEL; i++ )
  344. if( channel[ i ].status ) {
  345. if( channel[ i ].iPosition + 2048*2 >= channel[ i ].iLength )
  346. iMixLen = (channel[ i ].iLength - channel[ i ].iPosition)>>1;
  347. else
  348. iMixLen = 1024*2;
  349. srcofs = (int) channel[i].lpData + channel[i].iPosition;
  350. CalcLRVolumes(channel[i].volume, channel[i].x, channel[i].y, channel[i].z, LV, RV);
  351. if (LV || RV)
  352. Audio_MixSound((int)lpSoundBuffer, srcofs, iMixLen, LV, RV);
  353. if (channel[ i ].iPosition + 2048*2 >= channel[ i ].iLength )
  354. channel[ i ].status = 0; else channel[ i ].iPosition += 2048*2;
  355. }
  356. }
  357. void Audio_DoMixAmbient(AMBIENT &ambient)
  358. {
  359. if (ambient.lpData==0) return;
  360. int iMixLen,srcofs;
  361. int v = (32000 * ambient.volume * ambient.avolume) / 256 / 256;
  362. if( ambient.iPosition + 2048*2 >= ambient.iLength )
  363. iMixLen = (ambient.iLength - ambient.iPosition)>>1;
  364. else iMixLen = 1024*2;
  365. srcofs = (int) ambient.lpData + ambient.iPosition;
  366. Audio_MixSound((int)lpSoundBuffer, srcofs, iMixLen, v, v);
  367. if (ambient.iPosition + 2048*2 >= ambient.iLength )
  368. ambient.iPosition=0; else ambient.iPosition += 2048*2;
  369. if (iMixLen<1024*2) {
  370. Audio_MixSound((int)lpSoundBuffer + iMixLen*4,
  371. (int)ambient.lpData, 1024*2-iMixLen, v, v);
  372. ambient.iPosition+=(1024*2-iMixLen)*2;
  373. }
  374. }
  375. void Audio_MixAmbient()
  376. {
  377. Audio_DoMixAmbient(ambient);
  378. if (ambient.volume<256) ambient.volume = min(ambient.volume+16, 256);
  379. if (ambient2.volume) Audio_DoMixAmbient(ambient2);
  380. if (ambient2.volume>0) ambient2.volume = max(ambient2.volume-16, 0);
  381. }
  382. void Audio_MixAmbient3d()
  383. {
  384. if (mambient.lpData==0) return;
  385. int iMixLen,srcofs;
  386. int LV, RV;
  387. CalcLRVolumes(256, (int)mambient.x, (int)mambient.y, (int)mambient.z, LV, RV);
  388. if (!(LV || RV)) return;
  389. if( mambient.iPosition + 2048*2 >= mambient.iLength )
  390. iMixLen = (mambient.iLength - mambient.iPosition)>>1;
  391. else iMixLen = 1024*2;
  392. srcofs = (int) mambient.lpData + mambient.iPosition;
  393. Audio_MixSound((int)lpSoundBuffer, srcofs, iMixLen, LV, RV);
  394. if (mambient.iPosition + 2048*2 >= mambient.iLength )
  395. mambient.iPosition=0; else mambient.iPosition += 2048*2;
  396. if (iMixLen<1024*2) {
  397. Audio_MixSound((int)lpSoundBuffer + iMixLen*4,
  398. (int)mambient.lpData, 1024*2-iMixLen, LV, RV);
  399. mambient.iPosition+=(1024*2-iMixLen)*2;
  400. }
  401. }
  402. void Audio_MixSound(int DestAddr, int SrcAddr, int MixLen, int LVolume, int RVolume)
  403. {
  404. _asm {
  405. mov edi, DestAddr
  406. mov ecx, MixLen
  407. mov esi, SrcAddr
  408. }
  409. SOUND_CYCLE :
  410. _asm {
  411. movsx eax, word ptr [esi]
  412. imul LVolume
  413. sar eax, 16
  414. mov bx, word ptr [edi]
  415. add ax, bx
  416. jo LEFT_CHECK_OVERFLOW
  417. mov word ptr [edi], ax
  418. jmp CYCLE_RIGHT
  419. }
  420. LEFT_CHECK_OVERFLOW :
  421. __asm {
  422. cmp bx, 0
  423. js LEFT_MAX_NEGATIVE
  424. mov ax, 32767
  425. mov word ptr [edi], ax
  426. jmp CYCLE_RIGHT
  427. }
  428. LEFT_MAX_NEGATIVE :
  429. __asm mov word ptr [edi], -32767
  430. CYCLE_RIGHT :
  431. __asm {
  432. movsx eax, word ptr [esi]
  433. imul dword ptr RVolume
  434. sar eax, 16
  435. mov bx, word ptr [edi+2]
  436. add ax, bx
  437. jo RIGHT_CHECK_OVERFLOW
  438. mov word ptr [edi+2], ax
  439. jmp CYCLE_CONTINUE
  440. }
  441. RIGHT_CHECK_OVERFLOW :
  442. __asm {
  443. cmp bx, 0
  444. js RIGHT_MAX_NEGATIVE
  445. mov word ptr [edi+2], 32767
  446. jmp CYCLE_CONTINUE
  447. }
  448. RIGHT_MAX_NEGATIVE :
  449. __asm mov word ptr [edi+2], -32767
  450. CYCLE_CONTINUE :
  451. __asm {
  452. add edi, 4
  453. add esi, 2
  454. dec ecx
  455. jnz SOUND_CYCLE
  456. }
  457. }