SOUNDIO.CPP 89 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158
  1. /*
  2. ** Command & Conquer Red Alert(tm)
  3. ** Copyright 2025 Electronic Arts Inc.
  4. **
  5. ** This program is free software: you can redistribute it and/or modify
  6. ** it under the terms of the GNU General Public License as published by
  7. ** the Free Software Foundation, either version 3 of the License, or
  8. ** (at your option) any later version.
  9. **
  10. ** This program is distributed in the hope that it will be useful,
  11. ** but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. ** GNU General Public License for more details.
  14. **
  15. ** You should have received a copy of the GNU General Public License
  16. ** along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. */
  18. /* $Id: soundio.cpp 1.41 1994/06/20 15:01:39 joe_bostic Exp $ */
  19. /***********************************************************************************************
  20. ** C O N F I D E N T I A L --- W E S T W O O D A S S O C I A T E S **
  21. ***********************************************************************************************
  22. * *
  23. * Project Name : Sound Library *
  24. * *
  25. * File Name : SOUND.CPP *
  26. * *
  27. * Programmer : Joe L. Bostic *
  28. * *
  29. * Start Date : July 22, 1991 *
  30. * *
  31. *---------------------------------------------------------------------------------------------*
  32. * Functions: *
  33. * Load_Long_Sample -- Loads a sample into XMS for double buffer system. *
  34. * Read_Long_Sample -- Loads/Processes/Formats/Builds offset. *
  35. * Save_Table_Entry -- Put an entry in the offset table. *
  36. * Play_Long_Sample -- Calls Init_Long_Sample and Start_Long_Sample. *
  37. * Start_Long_Sample -- Starts a sample playing that has be initialized. *
  38. * Get_Table_Entry -- Gets next entry in table. *
  39. * Long_Sample_Ticks -- Gets number of ticks in sample if in header. *
  40. * Long_Sample_Status -- Returns the status of the sample. *
  41. * Find_Table_Entry -- Finds next entry in table that matches mask. *
  42. * Get_Table_Start -- Returns a pointer to first entry in table. *
  43. * Long_Sample_Ticks_Played -- Number of ticks since sample started. *
  44. * Install_Sample_Driver_Callback -- Pokes callback function into JM driver *
  45. * Stop_Long_Sample -- Stops current long sample from playing. *
  46. * Long_Sample_Loaded_Size -- Max buffer size to load a long sample. *
  47. * Sound_Callback -- Audio driver callback function. *
  48. * DigiCallback -- Low level double buffering handler. *
  49. * Load_Sample_Into_Buffer -- Loads a digitized sample into a buffer. *
  50. * Stream_Sample -- Streams a sample directly from a file. *
  51. * Sample_Read -- Reads sample data from an openned file. *
  52. * Continue_Sample -- Tags another block of data onto the currently playing. *
  53. * Sample_Copy -- Copies sound data from source format to raw format. *
  54. * File_Stream_Preload -- Handles initial proload of a streaming samples bu*
  55. * Sample_Length -- returns length of a sample in ticks *
  56. * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
  57. extern void Colour_Debug (int call_number);
  58. #pragma pack(4)
  59. #define WIN32
  60. #ifndef _WIN32 // Denzil 6/2/98 Watcom 11.0 complains without this check
  61. #define _WIN32
  62. #endif // _WIN32
  63. #include <windows.h>
  64. #include <windowsx.h>
  65. #include "dsound.h"
  66. #include <mem.h>
  67. #include <wwmem.h>
  68. #include "soundint.h"
  69. #include <stdio.h>
  70. #include <string.h>
  71. #include <direct.h>
  72. #include <stdlib.h>
  73. #include <process.h>
  74. #include <keyboard.h>
  75. #include <file.h>
  76. #include <bios.h>
  77. #include <timer.h>
  78. #include <math.h>
  79. #pragma pack(1)
  80. #include "audio.h"
  81. #pragma pack(4)
  82. LPDIRECTSOUNDBUFFER DumpBuffer;
  83. HANDLE SoundThreadHandle = NULL;
  84. BOOL SoundThreadActive = FALSE;
  85. /*
  86. ** If this is defined, then the streaming audio buffer will be filled
  87. ** to maximum whenever filling is to occur. If undefined, it will fill
  88. ** the streaming buffer in smaller chunks.
  89. */
  90. #define SIMPLE_FILLING
  91. /*
  92. ** This is the number of times per sec that the maintenance callback gets called.
  93. */
  94. #define MAINTENANCE_RATE 40 //30 times per sec plus a safety margin
  95. /*
  96. ** Size of the temporary buffer in XMS/EMS that direct file
  97. ** streaming of sounds will allocate.
  98. */
  99. //#define STREAM_BUFFER_SIZE (128L*1024L)
  100. #define STREAM_BUFFER_SIZE (128L*1024L)
  101. /*
  102. ** Define the number of "StreamBufferSize" blocks that are read in
  103. ** at a minimum when the streaming sample load callback routine
  104. ** is called. We will IGNORE loads that are less that this in order
  105. ** to avoid constant seeking on the CD.
  106. */
  107. #define STREAM_CUSHION_BLOCKS 4
  108. /*
  109. ** This is the maximum size that a sonarc block can be. All sonarc blocks
  110. ** must be either a multiple of this value or a binary root of this value.
  111. */
  112. #define LARGEST_SONARC_BLOCK 2048
  113. //////////////////////////////////////////////////////////////////////////////////////
  114. ////////////////////////////////////// structs ///////////////////////////////////////
  115. //void *DigiBuffer = NULL;
  116. static BOOL StartingFileStream = FALSE;
  117. int StreamLowImpact = FALSE;
  118. MemoryFlagType StreamBufferFlag = MEM_NORMAL;
  119. int Misc;
  120. SFX_Type SoundType;
  121. Sample_Type SampleType;
  122. int ReverseChannels = FALSE;
  123. LPDIRECTSOUND SoundObject; //Direct sound object
  124. LPDIRECTSOUNDBUFFER PrimaryBufferPtr; //Pointer to the buffer that the
  125. unsigned SoundTimerHandle=0; //Windows Handle for sound timer
  126. WAVEFORMATEX DsBuffFormat; //format of direct sound buffer
  127. DSBUFFERDESC BufferDesc; //Buffer description for creating buffers
  128. WAVEFORMATEX PrimaryBuffFormat; //Copy of format of direct sound primary buffer
  129. DSBUFFERDESC PrimaryBufferDesc; //Copy of buffer description for re-creating primary buffer
  130. CRITICAL_SECTION GlobalAudioCriticalSection;
  131. /*
  132. ** Function to call if we detect focus loss
  133. */
  134. extern void (*Audio_Focus_Loss_Function)(void) = NULL;
  135. /*=========================================================================*/
  136. /* The following PRIVATE functions are in this file: */
  137. /*=========================================================================*/
  138. static BOOL File_Callback(short id, short *odd, void **buffer, long *size);
  139. static int __cdecl Stream_Sample_Vol(void *buffer, long size, BOOL (*callback)(short id, short *odd, void **buffer, long *size), int volume, int handle);
  140. void CALLBACK Sound_Timer_Callback ( UINT, UINT, DWORD, DWORD, DWORD );
  141. //static int __cdecl Stream_Sample(void *buffer, long size, BOOL (*callback)(short id, short *odd, void **buffer, long *size));
  142. void Sound_Thread (void *);
  143. volatile BOOL AudioDone;
  144. /*= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =*/
  145. // This callback is called whenever the queue buffer playback has begun
  146. // and another buffer is needed for queuing up. Returns TRUE if there
  147. // is more data to read from the file.
  148. static BOOL File_Callback(short id, short *odd, void **buffer, long *size)
  149. {
  150. SampleTrackerType *st; // Pointer to sample playback control struct.
  151. void *ptr; // Pointer to working portion of file buffer.
  152. if (id != -1) {
  153. st = &LockedData.SampleTracker[id];
  154. ptr = st->FileBuffer;
  155. if (ptr) {
  156. /*
  157. ** Move the next pending block into the primary
  158. ** position. Do this only if the queue pointer is
  159. ** null.
  160. */
  161. EnterCriticalSection(&GlobalAudioCriticalSection);
  162. st->DontTouch = TRUE;
  163. LeaveCriticalSection(&GlobalAudioCriticalSection);
  164. if (!*buffer && st->FilePending) {
  165. *buffer = Add_Long_To_Pointer(ptr, (long)(*odd % LockedData.StreamBufferCount)*(long)LockedData.StreamBufferSize);
  166. st->FilePending--;
  167. *odd = (short)(*odd + 1);
  168. if (!st->FilePending) {
  169. *size = st->FilePendingSize;
  170. } else {
  171. *size = LockedData.StreamBufferSize;
  172. }
  173. }
  174. EnterCriticalSection(&GlobalAudioCriticalSection);
  175. st->DontTouch = FALSE;
  176. LeaveCriticalSection(&GlobalAudioCriticalSection);
  177. Sound_Timer_Callback(0,0,0,0,0); //Shouldnt block as we are calling it from the same thread
  178. /*
  179. ** If the file handle is still valid, then read in the next
  180. ** block and add it to the next pending slot available.
  181. */
  182. if (st->FilePending <
  183. (StreamLowImpact ? (LockedData.StreamBufferCount>>1) : ((LockedData.StreamBufferCount-3))) && st->FileHandle != WW_ERROR) {
  184. int num_empty_buffers;
  185. #ifdef SIMPLE_FILLING
  186. num_empty_buffers = (LockedData.StreamBufferCount-2) - st->FilePending;
  187. #else
  188. //
  189. // num_empty_buffers will be from 1 to StreamBufferCount
  190. //
  191. if (StreamLowImpact) {
  192. num_empty_buffers = MIN((LockedData.StreamBufferCount >> 1)+STREAM_CUSHION_BLOCKS, (LockedData.StreamBufferCount - 2) - st->FilePending);
  193. }
  194. else {
  195. num_empty_buffers = (LockedData.StreamBufferCount - 2) - st->FilePending;
  196. }
  197. #endif
  198. while (num_empty_buffers && (st->FileHandle != WW_ERROR)) {
  199. int tofill;
  200. long psize;
  201. tofill = (*odd + st->FilePending) % LockedData.StreamBufferCount;
  202. ptr = Add_Long_To_Pointer(st->FileBuffer, (long)tofill * (long)LockedData.StreamBufferSize);
  203. psize = Read_File(st->FileHandle, ptr, LockedData.StreamBufferSize);
  204. /*
  205. ** If less than the requested amount of data was read, this
  206. ** indicates that the source file is exhausted. Flag the source
  207. ** file as closed so that no further reading is attempted.
  208. */
  209. if (psize != LockedData.StreamBufferSize) {
  210. Close_File(st->FileHandle);
  211. st->FileHandle = WW_ERROR;
  212. }
  213. /*
  214. ** If any real data went into the pending buffer, then flag
  215. ** that this buffer is valid.
  216. */
  217. if (psize) {
  218. EnterCriticalSection(&GlobalAudioCriticalSection);
  219. st->DontTouch = TRUE;
  220. st->FilePendingSize = psize;
  221. st->FilePending++;
  222. st->DontTouch = FALSE;
  223. LeaveCriticalSection(&GlobalAudioCriticalSection);
  224. Sound_Timer_Callback(0,0,0,0,0); //Shouldnt block as we are calling it from the same thread
  225. }
  226. num_empty_buffers--;
  227. }
  228. /*
  229. ** After filling all pending buffers, check to see if the queue buffer
  230. ** is empty. If so, then assign the first available pending buffer to the
  231. ** queue.
  232. */
  233. EnterCriticalSection(&GlobalAudioCriticalSection);
  234. st->DontTouch = TRUE;
  235. if (!st->QueueBuffer && st->FilePending) {
  236. st->QueueBuffer = Add_Long_To_Pointer(st->FileBuffer, (long)(st->Odd%LockedData.StreamBufferCount)*(long)LockedData.StreamBufferSize);
  237. st->FilePending--;
  238. st->Odd++;
  239. if (!st->FilePending) {
  240. st->QueueSize = st->FilePendingSize;
  241. } else {
  242. st->QueueSize = LockedData.StreamBufferSize;
  243. }
  244. }
  245. st->DontTouch = FALSE;
  246. LeaveCriticalSection(&GlobalAudioCriticalSection);
  247. Sound_Timer_Callback(0,0,0,0,0); //Shouldnt block as we are calling it from the same thread
  248. }
  249. /*
  250. ** If there are no more buffers that the callback routine
  251. ** can slot into the primary position, then signal that
  252. ** no furthur callbacks are needed.
  253. */
  254. if (st->FilePending) {
  255. //LeaveCriticalSection(&GlobalAudioCriticalSection);
  256. return(TRUE);
  257. }
  258. }
  259. //LeaveCriticalSection(&GlobalAudioCriticalSection);
  260. }
  261. return(FALSE);
  262. }
  263. // Generic streaming sample playback initialization.
  264. static int __cdecl Stream_Sample_Vol(void *buffer, long size, BOOL (*callback)(short id, short *odd, void **buffer, long *size), int volume, int handle)
  265. {
  266. int playid=-1; // Sample play ID.
  267. SampleTrackerType *st; // Working pointer to sample control structure.
  268. long oldsize; // Copy of original sound size.
  269. AUDHeaderType header;
  270. if (buffer && size && LockedData.DigiHandle != -1) {
  271. /*
  272. ** Start the first section of the sound playing.
  273. */
  274. Mem_Copy(buffer, &header, sizeof(header));
  275. oldsize = header.Size;
  276. header.Size = size-sizeof(header);
  277. Mem_Copy(&header, buffer, sizeof(header));
  278. playid = Play_Sample_Handle(buffer, 0xFF, volume, 0x0, handle);
  279. header.Size = oldsize;
  280. Mem_Copy(&header, buffer, sizeof(header));
  281. /*
  282. ** If the sample actually started playing, then flag this
  283. ** sample as a streaming type and signal for a callback
  284. ** to occur.
  285. */
  286. if (playid != -1) {
  287. st = &LockedData.SampleTracker[playid];
  288. st->Callback = callback;
  289. st->Odd = 0;
  290. // ServiceSomething = TRUE;
  291. }
  292. }
  293. return (playid);
  294. }
  295. #if (0)
  296. static int __cdecl Stream_Sample(void *buffer, long size, BOOL (*callback)(short id, short *odd, void **buffer, long *size), int handle)
  297. {
  298. return Stream_Sample_Vol(buffer, size, callback, 0xFF, handle);
  299. }
  300. #endif
  301. /***********************************************************************************************
  302. * File_Stream_Sample -- Streams a sample directly from a file. *
  303. * *
  304. * This will take the file specified and play it directly from disk. *
  305. * It performs this by allocating a temporary buffer in XMS/EMS and *
  306. * then keeping this buffer filled by the Sound_Callback() routine. *
  307. * *
  308. * INPUT: filename -- The name of the file to play. *
  309. * *
  310. * OUTPUT: Returns the handle to the sound -- just like Play_Sample(). *
  311. * *
  312. * WARNINGS: The temporary buffer is allocated when this routine is *
  313. * called and then freed when the sound is finished. Keep *
  314. * this in mind. *
  315. * *
  316. * HISTORY: *
  317. * 01/06/1994 JLB : Created. *
  318. *=============================================================================================*/
  319. int File_Stream_Sample(char const *filename, BOOL real_time_start)
  320. {
  321. return File_Stream_Sample_Vol(filename, 0xFF, real_time_start);
  322. }
  323. /***************************************************************************
  324. * FILE_STREAM_PRELOAD -- Handles initial proload of streaming samples *
  325. * *
  326. * This function is called before a sample which streams from disk is *
  327. * started. It can be called to either fill the buffer in small chunks *
  328. * from the call back routine or to fill the entire buffer at once. This *
  329. * is wholely dependant on whether the Loading bit is set within the *
  330. * sample tracker. *
  331. * *
  332. * INPUT:LockedData.SampleTracker * to the header which tracks this samples*
  333. * processing.*
  334. * *
  335. * OUTPUT: *
  336. * *
  337. * WARNINGS: *
  338. * *
  339. * HISTORY: *
  340. * 06/05/1995 PWG : Created. *
  341. *=========================================================================*/
  342. void File_Stream_Preload(int handle)
  343. {
  344. SampleTrackerType *st = &LockedData.SampleTracker[handle];
  345. int fh = st->FileHandle;
  346. int maxnum = (LockedData.StreamBufferCount >> 1) + STREAM_CUSHION_BLOCKS;
  347. void *buffer = st->FileBuffer;
  348. int num;
  349. /*
  350. ** Figure just how much we need to load. If we are doing the load in progress
  351. ** then we will only load two blocks.
  352. */
  353. if (st->Loading) {
  354. num = st->FilePending + 2;
  355. num = MIN(num, maxnum);
  356. } else {
  357. num = maxnum;
  358. }
  359. //EnterCriticalSection(&GlobalAudioCriticalSection);
  360. /*
  361. ** Loop through the blocks and load up the number we need.
  362. */
  363. for (int index = st->FilePending; index < num; index++) {
  364. long s = Read_File(fh, Add_Long_To_Pointer(buffer, (long)index * (long)LockedData.StreamBufferSize), LockedData.StreamBufferSize);
  365. if (s) {
  366. st->FilePendingSize = s;
  367. st->FilePending++;
  368. }
  369. if (s < LockedData.StreamBufferSize) break;
  370. }
  371. Sound_Timer_Callback(0,0,0,0,0); //Shouldnt block as we are calling it from the same thread
  372. /*
  373. ** If the last block was incomplete (ie. it didn't completely fill the buffer) or
  374. ** we have now filled up as much of the Streaming Buffer as we need to, then now is
  375. ** the time to kick off the sample.
  376. */
  377. if (st->FilePendingSize < LockedData.StreamBufferSize || index == maxnum) {
  378. /*
  379. ** Actually start the sample playing, and don't worry about the file callback
  380. ** it won't be called for a while.
  381. */
  382. int old = LockedData.SoundVolume;
  383. int size = (st->FilePending == 1) ? st->FilePendingSize : LockedData.StreamBufferSize;
  384. LockedData.SoundVolume = LockedData.ScoreVolume;
  385. StartingFileStream = TRUE;
  386. Stream_Sample_Vol(buffer, size, File_Callback, st->Volume, handle);
  387. StartingFileStream = FALSE;
  388. LockedData.SoundVolume = old;
  389. /*
  390. ** The Sample is finished loading (if it was loading in small pieces) so record that
  391. ** so that it will now use the active logic in the file call back.
  392. */
  393. st->Loading = FALSE;
  394. /*
  395. ** Decrement the file pending because the first block is already playing thanks
  396. ** to the play sample call above.
  397. */
  398. st->FilePending--;
  399. /*
  400. ** If File pending is now a zero, then we only preloaded one block and there
  401. ** is nothing more to play. So clear the sample tracing structure of the
  402. ** information it no longer needs.
  403. */
  404. if (!st->FilePending) {
  405. st->Odd = 0;
  406. st->QueueBuffer = 0;
  407. st->QueueSize = 0;
  408. st->FilePendingSize = 0;
  409. st->Callback = NULL;
  410. Close_File(fh);
  411. } else {
  412. /*
  413. ** The QueueBuffer counts as an already played block so remove it from the total.
  414. ** Note: We didn't remove it before because there might not have been one.
  415. */
  416. st->FilePending--;
  417. /*
  418. ** When we start loading we need to start past the first two blocks. Why this
  419. ** is called Odd, I haven't got the slightest.
  420. */
  421. st->Odd = 2;
  422. /*
  423. ** If the file pending size is less than the stream buffer, then the last block
  424. ** we loaded was the last block period. So close the file and reset the handle.
  425. */
  426. if (st->FilePendingSize != LockedData.StreamBufferSize) {
  427. Close_File(fh);
  428. st->FileHandle = WW_ERROR;
  429. }
  430. /*
  431. ** The Queue buffer needs to point at the next block to be processed. The size
  432. ** of the queue is dependant on how many more blocks there are.
  433. */
  434. st->QueueBuffer = Add_Long_To_Pointer(buffer, LockedData.StreamBufferSize);
  435. if (!st->FilePending) {
  436. st->QueueSize = st->FilePendingSize;
  437. } else {
  438. st->QueueSize = LockedData.StreamBufferSize;
  439. }
  440. }
  441. }
  442. //LeaveCriticalSection(&GlobalAudioCriticalSection);
  443. }
  444. /***********************************************************************************************
  445. * File_Stream_Sample_Vol -- Streams a sample directly from a file. *
  446. * *
  447. * This will take the file specified and play it directly from disk. *
  448. * It performs this by allocating a temporary buffer in XMS/EMS and *
  449. * then keeping this buffer filled by the Sound_Callback() routine. *
  450. * *
  451. * INPUT: filename -- The name of the file to play. *
  452. * *
  453. * OUTPUT: Returns the handle to the sound -- just like Play_Sample(). *
  454. * *
  455. * WARNINGS: The temporary buffer is allocated when this routine is *
  456. * called and then freed when the sound is finished. Keep *
  457. * this in mind. *
  458. * *
  459. * HISTORY: *
  460. *=============================================================================================*/
  461. int File_Stream_Sample_Vol(char const *filename, int volume, BOOL real_time_start)
  462. {
  463. static void *buffer = NULL;
  464. SampleTrackerType *st;
  465. int fh;
  466. int handle = -1;
  467. int index;
  468. if (LockedData.DigiHandle != -1 && filename && Find_File(filename)) {
  469. /*
  470. ** Make sure all sample tracker structures point to the same
  471. ** upper memory buffer. This allocation only occurs if at
  472. ** least one sample gets "streamed".
  473. */
  474. if (!buffer) {
  475. buffer = Alloc(LockedData.StreamBufferSize * LockedData.StreamBufferCount, (MemoryFlagType)(StreamBufferFlag | MEM_TEMP | MEM_LOCK));
  476. for (index = 0; index < MAX_SFX; index++) {
  477. LockedData.SampleTracker[index].FileBuffer = buffer;
  478. }
  479. }
  480. /*
  481. ** If after trying to allocate the buffer we still fail then
  482. ** we can stream this sample.
  483. */
  484. if (!buffer) return(-1);
  485. /*
  486. ** Lets see if we can sucessfully open up the file. If we can't,
  487. ** then there is no point in going any farther.
  488. */
  489. if ((fh = Open_File(filename, READ)) == -1) {
  490. return (-1);
  491. }
  492. /*
  493. ** Reserve a handle so that we can fill in the sample tracker
  494. ** with the needed information. If we dont get valid handle then
  495. ** we might as well give up.
  496. */
  497. if ((unsigned)(handle = Get_Free_Sample_Handle(0xFF)) >= MAX_SFX) {
  498. return(-1);
  499. }
  500. /*
  501. ** Now lets get a pointer to the proper sample handler and start
  502. ** our manipulations.
  503. */
  504. st = &LockedData.SampleTracker[handle];
  505. st->IsScore = TRUE;
  506. st->FilePending = 0;
  507. st->FilePendingSize = 0;
  508. st->Loading = real_time_start;
  509. st->Volume = volume;
  510. st->FileHandle = fh;
  511. /*
  512. ** Now that we have setup our initial data properly, let load up
  513. ** the beginning of the sample we intend to stream.
  514. */
  515. File_Stream_Preload(handle);
  516. }
  517. return (handle);
  518. }
  519. /***********************************************************************************************
  520. * Sound_Callback -- Audio driver callback function. *
  521. * *
  522. * Maintains the audio buffers. This routine must be called at least *
  523. * 11 times per second or else audio glitches will occur. *
  524. * *
  525. * INPUT: none *
  526. * *
  527. * OUTPUT: none *
  528. * *
  529. * WARNINGS: If this routine is not called often enough then audio *
  530. * glitches will occur. *
  531. * *
  532. * HISTORY: *
  533. * 01/06/1994 JLB : Created. *
  534. *=============================================================================================*/
  535. void __cdecl Sound_Callback(void)
  536. {
  537. int index;
  538. SampleTrackerType *st;
  539. if (LockedData.DigiHandle != -1) {
  540. /*
  541. ** Call the timer callback now as we may block it in this function
  542. */
  543. Sound_Timer_Callback(0,0,0,0,0);
  544. st = &LockedData.SampleTracker[0];
  545. for (index = 0; index < MAX_SFX; index++) {
  546. if (st->Loading) {
  547. File_Stream_Preload(index);
  548. } else {
  549. /*
  550. ** General service routine to handle moving small blocks from the
  551. ** source into the low RAM staging buffers.
  552. */
  553. if (st->Active) {
  554. /*
  555. ** Special check to see if the sample is a fading one AND
  556. ** it has faded to silence, then stop it here.
  557. */
  558. if (st->Reducer && !st->Volume) {
  559. //EnterCriticalSection(&GlobalAudioCriticalSection);
  560. Stop_Sample(index);
  561. //LeaveCriticalSection(&GlobalAudioCriticalSection);
  562. } else {
  563. /*
  564. ** Fill the queuebuffer if it is currently empty
  565. ** and there is a callback function defined to fill it.
  566. **
  567. ** PWG/CDY & CO: We should be down by at least two blocks
  568. ** before we bother with this
  569. */
  570. if ((!st->QueueBuffer ||
  571. (st->FileHandle != WW_ERROR && st->FilePending < LockedData.StreamBufferCount-3)) &&
  572. st->Callback) {
  573. if (!st->Callback((short)index, (short int *)&st->Odd, &st->QueueBuffer, &st->QueueSize)) {
  574. st->Callback = NULL;
  575. }
  576. }
  577. }
  578. } else {
  579. /*
  580. ** This catches the case where a streaming sample gets
  581. ** aborted prematurely because of failure to call the
  582. ** callback function frequently enough. In this case, the
  583. ** sample will be flagged as inactive, but the file handle
  584. ** will not have been closed.
  585. */
  586. if (st->FileHandle != WW_ERROR) {
  587. //EnterCriticalSection(&GlobalAudioCriticalSection);
  588. Close_File(st->FileHandle);
  589. st->FileHandle = WW_ERROR;
  590. //LeaveCriticalSection(&GlobalAudioCriticalSection);
  591. }
  592. }
  593. }
  594. /*
  595. ** Advance to the next sample control structure.
  596. */
  597. st++;
  598. }
  599. }
  600. }
  601. /***********************************************************************************************
  602. * Load_Sample -- Loads a digitized sample into RAM. *
  603. * *
  604. * This routine loads a digitized sample into RAM. *
  605. * *
  606. * INPUT: filename -- Name of the sound file to load. *
  607. * *
  608. * OUTPUT: Returns with a pointer to the loaded sound file. This pointer *
  609. * is passed to Play_Sample when playback is desired. *
  610. * *
  611. * WARNINGS: If there is insufficient memory to load the sample, then *
  612. * NULL will be returned. *
  613. * *
  614. * HISTORY: *
  615. * 04/17/1992 JLB : Created. *
  616. * 01/06/1994 JLB : HMI version. *
  617. *=============================================================================================*/
  618. void *Load_Sample(char const *filename)
  619. {
  620. void *buffer = NULL;
  621. long size;
  622. int fh;
  623. if (LockedData.DigiHandle == -1 || !filename || !Find_File(filename)) {
  624. return (NULL);
  625. }
  626. fh = Open_File(filename, READ);
  627. if (fh != WW_ERROR) {
  628. size = File_Size(fh)+sizeof(AUDHeaderType);
  629. buffer = Alloc(size, MEM_NORMAL);
  630. if (buffer) {
  631. Sample_Read(fh, buffer, size);
  632. }
  633. Close_File(fh);
  634. Misc = size;
  635. }
  636. return(buffer);
  637. }
  638. /***********************************************************************************************
  639. * Load_Sample_Into_Buffer -- Loads a digitized sample into a buffer. *
  640. * *
  641. * This routine is used to load a digitized sample into a buffer *
  642. * provided by the programmer. This buffer can be in XMS or EMS. *
  643. * *
  644. * INPUT: filename -- The filename to load. *
  645. * *
  646. * buffer -- Pointer to the buffer to load into. *
  647. * *
  648. * size -- The size of the buffer to load into. *
  649. * *
  650. * OUTPUT: Returns the number of bytes actually used in the buffer. *
  651. * *
  652. * WARNINGS: This routine will not overflow the buffer provided. This *
  653. * means that the buffer must be big enough to hold the data *
  654. * or else the sound will be cut short. *
  655. * *
  656. * HISTORY: *
  657. * 01/06/1994 JLB : Created. *
  658. *=============================================================================================*/
  659. long Load_Sample_Into_Buffer(char const *filename, void *buffer, long size)
  660. {
  661. int fh;
  662. /*
  663. ** Verify legality of parameters.
  664. */
  665. if (!buffer || !size || LockedData.DigiHandle == -1 || !filename || !Find_File(filename)) {
  666. return (NULL);
  667. }
  668. fh = Open_File(filename, READ);
  669. if (fh != WW_ERROR) {
  670. size = Sample_Read(fh, buffer, size);
  671. Close_File(fh);
  672. } else {
  673. return(0);
  674. }
  675. return(size);
  676. }
  677. /***********************************************************************************************
  678. * Sample_Read -- Reads sample data from an openned file. *
  679. * *
  680. * This routine reads a sample file. It is presumed that the file is *
  681. * already positioned at the start of the sample. From this, it can *
  682. * determine if it is a VOC or raw data and proceed accordingly. *
  683. * *
  684. * INPUT: fh -- File handle of already openned sample file. *
  685. * *
  686. * buffer -- Pointer to the buffer to load data into. *
  687. * *
  688. * size -- The size of the buffer. *
  689. * *
  690. * OUTPUT: Returns the number of bytes actually used in the buffer. *
  691. * *
  692. * WARNINGS: none *
  693. * *
  694. * HISTORY: *
  695. * 01/06/1994 JLB : Created. *
  696. *=============================================================================================*/
  697. long Sample_Read(int fh, void *buffer, long size)
  698. {
  699. AUDHeaderType RawHeader;
  700. void *outbuffer; // Pointer to start of raw data.
  701. long actual_bytes_read; // Actual bytes read in, including header
  702. /*
  703. ** Conversion formula for TCrate and Hz rate.
  704. **
  705. ** TC = 256 - 1m/rate
  706. ** rate = 1m / (256-TC)
  707. */
  708. if (!buffer || fh == WW_ERROR || size <= sizeof(RawHeader)) return(NULL);
  709. size -= sizeof(RawHeader);
  710. outbuffer = Add_Long_To_Pointer(buffer, sizeof(RawHeader));
  711. actual_bytes_read = Read_File(fh, &RawHeader, sizeof(RawHeader));
  712. actual_bytes_read +=Read_File(fh, outbuffer, MIN(size, RawHeader.Size));
  713. Mem_Copy(&RawHeader, buffer, sizeof(RawHeader));
  714. return(actual_bytes_read);
  715. }
  716. /***********************************************************************************************
  717. * Free_Sample -- Frees a previously loaded digitized sample. *
  718. * *
  719. * Use this routine to free the memory allocated by a previous call to *
  720. * Load_Sample. *
  721. * *
  722. * INPUT: sample -- Pointer to the sample to be freed. *
  723. * *
  724. * OUTPUT: none *
  725. * *
  726. * WARNINGS: none *
  727. * *
  728. * HISTORY: *
  729. * 04/17/1992 JLB : Created. *
  730. *=============================================================================================*/
  731. void Free_Sample(void const *sample)
  732. {
  733. if (sample) Free((void *)sample);
  734. }
  735. /***********************************************************************************************
  736. * Sound_Timer_Callback -- windows timer callback for sound maintenance *
  737. * *
  738. * *
  739. * *
  740. * INPUT: Nothing *
  741. * *
  742. * OUTPUT: Nothing *
  743. * *
  744. * WARNINGS: None *
  745. * *
  746. * HISTORY: *
  747. * 11/2/95 4:01PM ST : Created *
  748. *=============================================================================================*/
  749. void CALLBACK Sound_Timer_Callback ( UINT, UINT, DWORD, DWORD, DWORD )
  750. {
  751. //if (!InTimerCallback){
  752. //InTimerCallback++;
  753. //Colour_Debug (5);
  754. EnterCriticalSection(&GlobalAudioCriticalSection);
  755. maintenance_callback();
  756. LeaveCriticalSection(&GlobalAudioCriticalSection);
  757. //Colour_Debug (0);
  758. //InTimerCallback--;
  759. //}
  760. }
  761. void Sound_Thread (void *)
  762. {
  763. DuplicateHandle (GetCurrentProcess(), GetCurrentThread() , GetCurrentProcess() ,&SoundThreadHandle , THREAD_ALL_ACCESS , TRUE , 0);
  764. SetThreadPriority (SoundThreadHandle, THREAD_PRIORITY_TIME_CRITICAL);
  765. SoundThreadActive = TRUE;
  766. while (!AudioDone){
  767. EnterCriticalSection(&GlobalAudioCriticalSection);
  768. maintenance_callback();
  769. LeaveCriticalSection(&GlobalAudioCriticalSection);
  770. Sleep(1000/40);
  771. }
  772. SoundThreadActive = FALSE;
  773. }
  774. /***********************************************************************************************
  775. * Set_Primary_Buffer_Format -- set the format of the primary sound buffer *
  776. * *
  777. * *
  778. * *
  779. * INPUT: Nothing *
  780. * *
  781. * OUTPUT: TRUE if successfully set *
  782. * *
  783. * WARNINGS: None *
  784. * *
  785. * HISTORY: *
  786. * 12/22/95 4:06PM ST : Created *
  787. *=============================================================================================*/
  788. BOOL Set_Primary_Buffer_Format(void)
  789. {
  790. if (SoundObject && PrimaryBufferPtr){
  791. return (PrimaryBufferPtr->SetFormat ( &PrimaryBuffFormat ) == DS_OK);
  792. }
  793. return (FALSE);
  794. }
  795. /***********************************************************************************************
  796. * Print_Sound_Error -- show error messages from failed sound initialisation *
  797. * *
  798. * *
  799. * *
  800. * INPUT: error text *
  801. * handle to window *
  802. * *
  803. * OUTPUT: Nothing *
  804. * *
  805. * WARNINGS: None *
  806. * *
  807. * HISTORY: *
  808. * 2/7/96 10:17AM ST : Created *
  809. *=============================================================================================*/
  810. void Print_Sound_Error(char *sound_error, HWND window)
  811. {
  812. MessageBox(window, sound_error, "Command & Conquer", MB_ICONEXCLAMATION|MB_OK);
  813. }
  814. /***********************************************************************************************
  815. * Audio_Init -- Initialise the sound system *
  816. * *
  817. * *
  818. * *
  819. * INPUT: window - window to send callback messages to *
  820. * maximum bits_per_sample - 8 or 16 *
  821. * stereo - will stereo samples be played *
  822. * rate - maximum sample rate required *
  823. * reverse_channels *
  824. * *
  825. * OUTPUT: TRUE if correctly initialised *
  826. * *
  827. * WARNINGS: None *
  828. * *
  829. * HISTORY: *
  830. * Unknown.... *
  831. * 08-24-95 10:01am ST : Modified for Windows 95 Direct Sound *
  832. *=============================================================================================*/
  833. BOOL Audio_Init( HWND window , int bits_per_sample, BOOL stereo , int rate , int reverse_channels)
  834. {
  835. int index;
  836. int sample=1;
  837. short old_bits_per_sample;
  838. short old_block_align;
  839. long old_bytes_per_sec;
  840. Init_Locked_Data();
  841. memset(&LockedData.SampleTracker[0], 0, sizeof(LockedData.SampleTracker));
  842. if ( !SoundObject ){
  843. /*
  844. ** Create the direct sound object
  845. */
  846. if ( DirectSoundCreate (NULL,&SoundObject,NULL) !=DS_OK ) {
  847. Print_Sound_Error("Warning - Unable to create Direct Sound Object",window);
  848. return (FALSE);
  849. }
  850. /*
  851. ** Give ourselves exclusive access to it
  852. */
  853. if ( SoundObject->SetCooperativeLevel( window, DSSCL_PRIORITY ) != DS_OK){
  854. Print_Sound_Error("Warning - Unable to set Direct Sound cooperative level",window);
  855. SoundObject->Release();
  856. SoundObject = NULL;
  857. return (FALSE);
  858. }
  859. /*
  860. ** Set up the primary buffer structure
  861. */
  862. memset (&BufferDesc , 0 , sizeof(DSBUFFERDESC));
  863. BufferDesc.dwSize=sizeof(DSBUFFERDESC);
  864. BufferDesc.dwFlags=DSBCAPS_PRIMARYBUFFER | DSBCAPS_CTRLVOLUME;
  865. /*
  866. ** Set up the primary buffer format
  867. */
  868. memset (&DsBuffFormat , 0 , sizeof(WAVEFORMATEX));
  869. DsBuffFormat.wFormatTag = WAVE_FORMAT_PCM;
  870. DsBuffFormat.nChannels = (unsigned short) (1 + stereo);
  871. DsBuffFormat.nSamplesPerSec = rate;
  872. DsBuffFormat.wBitsPerSample = (short) bits_per_sample;
  873. DsBuffFormat.nBlockAlign = (unsigned short)( (DsBuffFormat.wBitsPerSample/8) * DsBuffFormat.nChannels);
  874. DsBuffFormat.nAvgBytesPerSec= DsBuffFormat.nSamplesPerSec * DsBuffFormat.nBlockAlign;
  875. DsBuffFormat.cbSize = 0;
  876. /*
  877. ** Make a copy of the primary buffer description so we can reset its format later
  878. */
  879. memcpy (&PrimaryBufferDesc , &BufferDesc , sizeof(DSBUFFERDESC));
  880. memcpy (&PrimaryBuffFormat , &DsBuffFormat , sizeof(WAVEFORMATEX));
  881. /*
  882. ** Create the primary buffer object
  883. */
  884. if ( SoundObject->CreateSoundBuffer (&PrimaryBufferDesc ,
  885. &PrimaryBufferPtr ,
  886. NULL ) !=DS_OK ){
  887. Print_Sound_Error("Warning - Unable to create Direct Sound primary buffer",window);
  888. SoundObject->Release();
  889. SoundObject = NULL;
  890. return (FALSE);
  891. }
  892. /*
  893. ** Set the format of the primary sound buffer
  894. **
  895. */
  896. if (!Set_Primary_Buffer_Format()){
  897. /*
  898. ** If we failed to create a 16 bit primary buffer - try for an 8bit one
  899. */
  900. if (DsBuffFormat.wBitsPerSample == 16){
  901. /*
  902. ** Save the old values
  903. */
  904. old_bits_per_sample = DsBuffFormat.wBitsPerSample;
  905. old_block_align = DsBuffFormat.nBlockAlign;
  906. old_bytes_per_sec = DsBuffFormat.nAvgBytesPerSec;
  907. /*
  908. ** Set up the 8-bit ones
  909. */
  910. DsBuffFormat.wBitsPerSample = 8;
  911. DsBuffFormat.nBlockAlign = (unsigned short)( (DsBuffFormat.wBitsPerSample/8) * DsBuffFormat.nChannels);
  912. DsBuffFormat.nAvgBytesPerSec= DsBuffFormat.nSamplesPerSec * DsBuffFormat.nBlockAlign;
  913. /*
  914. ** Make a copy of the primary buffer description so we can reset its format later
  915. */
  916. memcpy (&PrimaryBufferDesc , &BufferDesc , sizeof(DSBUFFERDESC));
  917. memcpy (&PrimaryBuffFormat , &DsBuffFormat , sizeof(WAVEFORMATEX));
  918. }
  919. if (!Set_Primary_Buffer_Format()){
  920. /*
  921. ** We failed to set any useful format so print up an error message and give up
  922. */
  923. PrimaryBufferPtr->Release();
  924. PrimaryBufferPtr = NULL;
  925. SoundObject->Release();
  926. SoundObject = NULL;
  927. Print_Sound_Error("Warning - Your sound card does not meet the products audio requirements",window);
  928. return (FALSE);
  929. }else{
  930. /*
  931. ** OK, got an 8bit sound buffer. Not perfect but it will do
  932. ** We still want 16 bit secondary buffers so restore those values
  933. */
  934. DsBuffFormat.wBitsPerSample = old_bits_per_sample;
  935. DsBuffFormat.nBlockAlign = old_block_align;
  936. DsBuffFormat.nAvgBytesPerSec = old_bytes_per_sec;
  937. }
  938. }
  939. /*
  940. ** Start the primary sound buffer playing
  941. **
  942. */if ( PrimaryBufferPtr->Play(0,0,DSBPLAY_LOOPING) != DS_OK ){
  943. Print_Sound_Error("Unable to play Direct Sound primary buffer",window);
  944. PrimaryBufferPtr->Release();
  945. PrimaryBufferPtr = NULL;
  946. SoundObject->Release();
  947. SoundObject = NULL;
  948. return (FALSE);
  949. }
  950. LockedData.DigiHandle=1;
  951. /*
  952. ** Initialise the global critical section object for sound thread syncronisation
  953. */
  954. InitializeCriticalSection(&GlobalAudioCriticalSection);
  955. /*
  956. ** Initialise the Windows timer system to provide us with a callback
  957. **
  958. */
  959. SoundTimerHandle = timeSetEvent ( 1000/MAINTENANCE_RATE , 1 , Sound_Timer_Callback , 0 , TIME_PERIODIC);
  960. AudioDone = FALSE;
  961. //_beginthread(&Sound_Thread, NULL, 16*1024, NULL);
  962. /*
  963. ** Define the format for the secondary sound buffers
  964. */
  965. BufferDesc.dwFlags=DSBCAPS_CTRLVOLUME;
  966. BufferDesc.dwBufferBytes=SECONDARY_BUFFER_SIZE;
  967. BufferDesc.lpwfxFormat = (LPWAVEFORMATEX) &DsBuffFormat;
  968. /*
  969. ** Allocate a decompression buffer equal to the size of a SONARC frame
  970. ** block.
  971. */
  972. LockedData.UncompBuffer = Alloc(LARGEST_SONARC_BLOCK + 50, (MemoryFlagType)(MEM_NORMAL|MEM_CLEAR|MEM_LOCK));
  973. /*
  974. ** Allocate once secondary direct sound buffer for each simultaneous sound effect
  975. **
  976. */
  977. for (index = 0; index < MAX_SFX; index++) {
  978. SoundObject->CreateSoundBuffer (&BufferDesc , &LockedData.SampleTracker[index].PlayBuffer , NULL);
  979. LockedData.SampleTracker[index].PlaybackRate = rate;
  980. LockedData.SampleTracker[index].Stereo = (stereo) ? AUD_FLAG_STEREO : 0;
  981. LockedData.SampleTracker[index].BitSize = (bits_per_sample == 16) ? AUD_FLAG_16BIT : 0;
  982. LockedData.SampleTracker[index].FileHandle = WW_ERROR;
  983. LockedData.SampleTracker[index].QueueBuffer = NULL;
  984. InitializeCriticalSection (&LockedData.SampleTracker[index].AudioCriticalSection);
  985. }
  986. SoundType = (SFX_Type)sample;
  987. SampleType = (Sample_Type)sample;
  988. ReverseChannels = reverse_channels;
  989. }
  990. return(TRUE);
  991. }
  992. /***********************************************************************************************
  993. * Sound_End -- Uninitializes the sound driver. *
  994. * *
  995. * This routine will uninitialize the sound driver (if any was *
  996. * installed). This routine must be called at program termination *
  997. * time. *
  998. * *
  999. * INPUT: none *
  1000. * *
  1001. * OUTPUT: none *
  1002. * *
  1003. * WARNINGS: none *
  1004. * *
  1005. * HISTORY: *
  1006. * 07/23/1991 JLB : Created. *
  1007. * 11/02/1995 ST : Modified for Direct Sound *
  1008. *=============================================================================================*/
  1009. void Sound_End(void)
  1010. {
  1011. int index;
  1012. if (SoundObject && PrimaryBufferPtr){
  1013. /*
  1014. ** Stop all sounds and release the Direct Sound secondary sound buffers
  1015. */
  1016. for (index=0 ; index < MAX_SFX; index++){
  1017. if ( LockedData.SampleTracker[index].PlayBuffer ){
  1018. Stop_Sample (index);
  1019. LockedData.SampleTracker[index].PlayBuffer->Stop();
  1020. LockedData.SampleTracker[index].PlayBuffer->Release();
  1021. LockedData.SampleTracker[index].PlayBuffer = NULL;
  1022. DeleteCriticalSection(&LockedData.SampleTracker[index].AudioCriticalSection);
  1023. }
  1024. }
  1025. }
  1026. /*
  1027. ** Stop and release the direct sound primary buffer
  1028. */
  1029. if (PrimaryBufferPtr){
  1030. PrimaryBufferPtr->Stop();
  1031. PrimaryBufferPtr->Release();
  1032. PrimaryBufferPtr = NULL;
  1033. }
  1034. /*
  1035. ** Release the Direct Sound Object
  1036. */
  1037. if (SoundObject){
  1038. SoundObject->Release();
  1039. SoundObject = NULL;
  1040. }
  1041. if (LockedData.UncompBuffer) {
  1042. Free(LockedData.UncompBuffer);
  1043. LockedData.UncompBuffer = 0;
  1044. }
  1045. /*
  1046. ** Remove the Windows timer event we installed for the sound callback
  1047. */
  1048. if (SoundTimerHandle){
  1049. timeKillEvent(SoundTimerHandle);
  1050. SoundTimerHandle = 0;
  1051. }
  1052. AudioDone = TRUE;
  1053. /*
  1054. ** Since the timer has stopped, we are finished with our global critical section.
  1055. */
  1056. DeleteCriticalSection(&GlobalAudioCriticalSection);
  1057. }
  1058. /***********************************************************************************************
  1059. * Stop_Sample -- Stops any currently playing sampled sound. *
  1060. * *
  1061. * *
  1062. * *
  1063. * INPUT: *
  1064. * *
  1065. * OUTPUT: *
  1066. * *
  1067. * WARNINGS: *
  1068. * *
  1069. * HISTORY: *
  1070. * 06/02/1992 JLB : Created. *
  1071. * 11/2/95 4:09PM ST : Modified for Direct Sound *
  1072. *=============================================================================================*/
  1073. void Stop_Sample(int handle)
  1074. {
  1075. if (LockedData.DigiHandle != -1 && (unsigned)handle < MAX_SFX) {
  1076. EnterCriticalSection (&GlobalAudioCriticalSection);
  1077. if (LockedData.SampleTracker[handle].Active || LockedData.SampleTracker[handle].Loading) {
  1078. LockedData.SampleTracker[handle].Active = FALSE;
  1079. if (!LockedData.SampleTracker[handle].IsScore) {
  1080. LockedData.SampleTracker[handle].Original = NULL;
  1081. }
  1082. LockedData.SampleTracker[handle].Priority = 0;
  1083. /*
  1084. ** Stop the sample if it is playing.
  1085. */
  1086. if (!LockedData.SampleTracker[handle].Loading) {
  1087. LockedData.SampleTracker[handle].PlayBuffer->Stop();
  1088. }
  1089. LockedData.SampleTracker[handle].Loading = FALSE;
  1090. /*
  1091. ** If this is a streaming sample, then close the source file.
  1092. */
  1093. if (LockedData.SampleTracker[handle].FileHandle != WW_ERROR) {
  1094. Close_File(LockedData.SampleTracker[handle].FileHandle);
  1095. LockedData.SampleTracker[handle].FileHandle = WW_ERROR;
  1096. }
  1097. LockedData.SampleTracker[handle].QueueBuffer = NULL;
  1098. }
  1099. LeaveCriticalSection (&GlobalAudioCriticalSection);
  1100. }
  1101. }
  1102. /***********************************************************************************************
  1103. * Sample_Status -- Queries the current playing sample status (if any). *
  1104. * *
  1105. * *
  1106. * *
  1107. * INPUT: *
  1108. * *
  1109. * OUTPUT: *
  1110. * *
  1111. * WARNINGS: *
  1112. * *
  1113. * HISTORY: *
  1114. * 06/02/1992 JLB : Created. *
  1115. *=============================================================================================*/
  1116. BOOL Sample_Status(int handle)
  1117. {
  1118. DWORD status;
  1119. /*
  1120. ** If its an invalid handle or we do not have a sound driver then
  1121. ** the sample in question is not playing.
  1122. */
  1123. if (LockedData.DigiHandle == -1 || (unsigned)handle >= MAX_SFX) return(FALSE);
  1124. /*
  1125. ** If the sample is loading, then for all intents and purposes the
  1126. ** sample is playing.
  1127. */
  1128. if (LockedData.SampleTracker[handle].Loading) return(TRUE);
  1129. /*
  1130. ** If the sample is not active, then it is not playing
  1131. */
  1132. if (!LockedData.SampleTracker[handle].Active) return(FALSE);
  1133. /*
  1134. ** If we made it this far, then the Sample is still playing if sos says
  1135. ** that it is.
  1136. */
  1137. DumpBuffer = LockedData.SampleTracker[handle].PlayBuffer;
  1138. if (LockedData.SampleTracker[handle].PlayBuffer->GetStatus( &status ) == DS_OK){
  1139. return ( (DSBSTATUS_PLAYING & status) || (DSBSTATUS_LOOPING & status) );
  1140. }else{
  1141. return (TRUE);
  1142. }
  1143. }
  1144. /***********************************************************************************************
  1145. * Is_Sample_Playing -- returns the play state of a sample *
  1146. * *
  1147. * *
  1148. * *
  1149. * INPUT: ptr to sample data *
  1150. * *
  1151. * OUTPUT: TRUE if sample is currently playing *
  1152. * *
  1153. * WARNINGS: None *
  1154. * *
  1155. * HISTORY: *
  1156. * 11/2/95 4:11PM ST : Commented *
  1157. *=============================================================================================*/
  1158. BOOL Is_Sample_Playing(void const * sample)
  1159. {
  1160. int index;
  1161. //EnterCriticalSection(&GlobalAudioCriticalSection);
  1162. if (!sample) {
  1163. //LeaveCriticalSection(&GlobalAudioCriticalSection);
  1164. return FALSE;
  1165. }
  1166. for (index = 0; index < MAX_SFX; index++) {
  1167. if (LockedData.SampleTracker[index].Original == sample && Sample_Status(index)) {
  1168. //LeaveCriticalSection(&GlobalAudioCriticalSection);
  1169. return (TRUE);
  1170. }
  1171. }
  1172. //LeaveCriticalSection(&GlobalAudioCriticalSection);
  1173. return (FALSE);
  1174. }
  1175. /***********************************************************************************************
  1176. * Stop_Sample_Playing -- stops a playing sample *
  1177. * *
  1178. * *
  1179. * *
  1180. * INPUT: ptr to sample data *
  1181. * *
  1182. * OUTPUT: Nothing *
  1183. * *
  1184. * WARNINGS: None *
  1185. * *
  1186. * HISTORY: *
  1187. * 11/2/95 4:13PM ST : Commented *
  1188. *=============================================================================================*/
  1189. void Stop_Sample_Playing(void const * sample)
  1190. {
  1191. int index;
  1192. if (sample) {
  1193. for (index = 0; index < MAX_SFX; index++) {
  1194. if (LockedData.SampleTracker[index].Original == sample) {
  1195. Stop_Sample(index);
  1196. break;
  1197. }
  1198. }
  1199. }
  1200. }
  1201. /***********************************************************************************************
  1202. * Get_Free_Sample_Handle -- finds a free slot in which to play a new sample *
  1203. * *
  1204. * *
  1205. * *
  1206. * INPUT: priority of sample we want to play *
  1207. * *
  1208. * OUTPUT: Handle or -1 if none free *
  1209. * *
  1210. * WARNINGS: None *
  1211. * *
  1212. * HISTORY: *
  1213. * 11/2/95 4:14PM ST : Added function header *
  1214. *=============================================================================================*/
  1215. int Get_Free_Sample_Handle(int priority)
  1216. {
  1217. int id;
  1218. /*
  1219. ** Find a free SFX holding buffer slot.
  1220. */
  1221. for (id = MAX_SFX - 1; id >= 0; id--) {
  1222. if (!LockedData.SampleTracker[id].Active && !LockedData.SampleTracker[id].Loading) {
  1223. if (!StartingFileStream && LockedData.SampleTracker[id].IsScore) {
  1224. StartingFileStream = TRUE; // Ensures only one channel is kept free for scores.
  1225. continue;
  1226. }
  1227. break;
  1228. }
  1229. }
  1230. if (id < 0) {
  1231. for (id = 0; id < MAX_SFX; id++) {
  1232. if (LockedData.SampleTracker[id].Priority <= priority) break;
  1233. }
  1234. if (id == MAX_SFX) {
  1235. return(-1); // Cannot play!
  1236. }
  1237. Stop_Sample(id); // This sample gets clobbered.
  1238. }
  1239. if (id == -1) {
  1240. return -1;
  1241. }
  1242. if (LockedData.SampleTracker[id].FileHandle != WW_ERROR) {
  1243. Close_File(LockedData.SampleTracker[id].FileHandle);
  1244. LockedData.SampleTracker[id].FileHandle = WW_ERROR;
  1245. }
  1246. if (LockedData.SampleTracker[id].Original && !LockedData.SampleTracker[id].IsScore) {
  1247. LockedData.SampleTracker[id].Original = NULL;
  1248. }
  1249. LockedData.SampleTracker[id].IsScore = FALSE;
  1250. return(id);
  1251. }
  1252. int Play_Sample(void const *sample, int priority, int volume, signed short panloc)
  1253. {
  1254. return(Play_Sample_Handle(sample, priority, volume, panloc, Get_Free_Sample_Handle(priority)));
  1255. }
  1256. /***********************************************************************************************
  1257. * Attempt_Audio_Restore -- tries to restore the direct sound buffers *
  1258. * *
  1259. * *
  1260. * *
  1261. * INPUT: ptr to direct sound buffer *
  1262. * *
  1263. * OUTPUT: TRUE if buffer was successfully restored *
  1264. * *
  1265. * WARNINGS: None *
  1266. * *
  1267. * HISTORY: *
  1268. * 3/20/96 9:47AM ST : Created *
  1269. *=============================================================================================*/
  1270. BOOL Attempt_Audio_Restore (LPDIRECTSOUNDBUFFER sound_buffer)
  1271. {
  1272. int return_code;
  1273. DWORD play_status;
  1274. int restore_attempts=0;
  1275. /*
  1276. ** Call the audio focus loss function if it has been set up
  1277. */
  1278. if (Audio_Focus_Loss_Function){
  1279. Audio_Focus_Loss_Function();
  1280. }
  1281. /*
  1282. ** Try to restore the sound buffer
  1283. */
  1284. do{
  1285. Restore_Sound_Buffers();
  1286. return_code = sound_buffer->GetStatus ( &play_status );
  1287. } while (restore_attempts++<2 && return_code == DSERR_BUFFERLOST);
  1288. return ((BOOL) ~(return_code == DSERR_BUFFERLOST));
  1289. }
  1290. /***********************************************************************************************
  1291. * Convert_HMI_To_Direct_Sound_Volume -- Converts a linear volume value into an expotential *
  1292. * value *
  1293. * *
  1294. * This function converts a linear C&C volume in the range 0-255 (255 loudest) to a direct *
  1295. * sound volume in the range 0 to -10000 (with 0 being the loadest) *
  1296. * *
  1297. * INPUT: volume in range 0-255 *
  1298. * *
  1299. * OUTPUT: volume in range -10000 to 0 *
  1300. * *
  1301. * WARNINGS: None *
  1302. * *
  1303. * Note: The 27.685 value comes from 255 divided by the log of 10001 *
  1304. * *
  1305. * HISTORY: *
  1306. * 9/18/96 11:36AM ST : Created *
  1307. *=============================================================================================*/
  1308. int Convert_HMI_To_Direct_Sound_Volume(int volume)
  1309. {
  1310. if (volume == 0) return -10000;
  1311. if (volume == 255) return 0;
  1312. float vol = (float)volume;
  1313. float retval = exp ( (255.0-vol)/27.68597374) -1;
  1314. return ((int)-retval);
  1315. }
  1316. /***********************************************************************************************
  1317. * Play_Sample_Vol -- Plays a digitized sample. *
  1318. * *
  1319. * Use this routine to play a previously loaded digitized sample. *
  1320. * *
  1321. * INPUT: sample -- Sample pointer as returned from Load_Sample. *
  1322. * *
  1323. * volume -- The volume to play (0..255 with 255=loudest). *
  1324. * *
  1325. * OUTPUT: none *
  1326. * *
  1327. * WARNINGS: none *
  1328. * *
  1329. * HISTORY: *
  1330. * 04/17/1992 JLB : Created. *
  1331. * 05/24/1992 JLB : Volume support -- Soundblaster Pro *
  1332. * 04/22/1994 JLB : Multiple sample playback rates. *
  1333. * 11/02/1995 ST : Windows Direct Sound support *
  1334. *=============================================================================================*/
  1335. extern BOOL Any_Locked(void);
  1336. int Play_Sample_Handle(void const *sample, int priority, int volume, signed short , int id)
  1337. {
  1338. AUDHeaderType RawHeader;
  1339. SampleTrackerType *st=NULL; // Working pointer to sample tracker structure.
  1340. LPVOID play_buffer_ptr; //pointer to locked direct sound buffer
  1341. LPVOID dummy_buffer_ptr; //dummy pointer to second area of locked direct sound buffer
  1342. DWORD lock_length1;
  1343. DWORD lock_length2;
  1344. DWORD play_status;
  1345. HRESULT return_code;
  1346. int retries=0;
  1347. if (Any_Locked()) return(0);
  1348. st = &LockedData.SampleTracker[id];
  1349. //EnterCriticalSection (&GlobalAudioCriticalSection);
  1350. if (!sample || LockedData.DigiHandle == -1) {
  1351. //LeaveCriticalSection (&GlobalAudioCriticalSection);
  1352. return(-1);
  1353. }
  1354. if (id == -1) {
  1355. //LeaveCriticalSection (&GlobalAudioCriticalSection);
  1356. return -1;
  1357. }
  1358. /*
  1359. ** Fetch the control bytes from the start of the sample data.
  1360. */
  1361. Mem_Copy((void *)sample, (void *)&RawHeader, sizeof(RawHeader));
  1362. /*
  1363. ** Fudge the sample rate to 22k
  1364. */
  1365. if (RawHeader.Rate <24000 && RawHeader.Rate >20000) RawHeader.Rate = 22050;
  1366. /*
  1367. ** Prepare the sample tracker structure for processing of this
  1368. ** sample. Fill the structure with data that can be determined
  1369. ** before the sample is started.
  1370. */
  1371. EnterCriticalSection(&GlobalAudioCriticalSection);
  1372. st->Compression = (SCompressType) ((unsigned char)RawHeader.Compression);
  1373. st->Original = sample;
  1374. st->OriginalSize = RawHeader.Size + sizeof(RawHeader);
  1375. st->Priority = (short)priority;
  1376. st->DontTouch = TRUE;
  1377. st->Odd = 0;
  1378. st->Reducer = 0;
  1379. st->Restart = FALSE;
  1380. st->QueueBuffer = NULL;
  1381. st->QueueSize = NULL;
  1382. st->TrailerLen = 0;
  1383. st->Remainder = RawHeader.Size;
  1384. st->Source = Add_Long_To_Pointer((void *)sample, sizeof(RawHeader));
  1385. st->Service = FALSE;
  1386. LeaveCriticalSection(&GlobalAudioCriticalSection);
  1387. /*
  1388. ** If the code in question using HMI based compression then we need
  1389. ** to set up for uncompressing it.
  1390. */
  1391. if (st->Compression == SCOMP_SOS) {
  1392. st->sosinfo.wChannels = (RawHeader.Flags & AUD_FLAG_STEREO) ? 2 : 1;
  1393. st->sosinfo.wBitSize = (RawHeader.Flags & AUD_FLAG_16BIT) ? 16 : 8;
  1394. st->sosinfo.dwCompSize = RawHeader.Size;
  1395. st->sosinfo.dwUnCompSize = RawHeader.Size * ( st->sosinfo.wBitSize / 4 );
  1396. sosCODECInitStream(&st->sosinfo);
  1397. }
  1398. /*
  1399. ** If the sample rate , bits per sample or stereo capabilities of the buffer do not
  1400. ** match the sample then reallocate the direct sound buffer with the required capabilities
  1401. */
  1402. if ( ( RawHeader.Rate != st->PlaybackRate ) ||
  1403. ( ( RawHeader.Flags & AUD_FLAG_16BIT ) != ( st->BitSize & AUD_FLAG_16BIT ) ) ||
  1404. ( ( RawHeader.Flags & AUD_FLAG_STEREO) != ( st->Stereo & AUD_FLAG_STEREO ) ) ) {
  1405. st->Active=0;
  1406. st->Service=0;
  1407. st->MoreSource=0;
  1408. /*
  1409. ** Stop the sound buffer playing
  1410. */
  1411. DumpBuffer = st->PlayBuffer;
  1412. do {
  1413. return_code = st->PlayBuffer->GetStatus ( &play_status );
  1414. if (return_code==DSERR_BUFFERLOST){
  1415. if (!Attempt_Audio_Restore(st->PlayBuffer)) return(-1);
  1416. }
  1417. }while (return_code == DSERR_BUFFERLOST);
  1418. if (play_status & (DSBSTATUS_PLAYING | DSBSTATUS_LOOPING) ){
  1419. st->PlayBuffer->Stop();
  1420. if (return_code==DSERR_BUFFERLOST){
  1421. if (!Attempt_Audio_Restore(st->PlayBuffer)) return(-1);
  1422. }
  1423. }
  1424. st->PlayBuffer->Release();
  1425. st->PlayBuffer=NULL;
  1426. DsBuffFormat.nSamplesPerSec = (unsigned short int) RawHeader.Rate;
  1427. DsBuffFormat.nChannels = (RawHeader.Flags & AUD_FLAG_STEREO) ? 2 : 1 ;
  1428. DsBuffFormat.wBitsPerSample = (RawHeader.Flags & AUD_FLAG_16BIT) ? 16 : 8 ;
  1429. DsBuffFormat.nBlockAlign = (short) ((DsBuffFormat.wBitsPerSample/8) * DsBuffFormat.nChannels);
  1430. DsBuffFormat.nAvgBytesPerSec= DsBuffFormat.nSamplesPerSec * DsBuffFormat.nBlockAlign;
  1431. /*
  1432. ** Create the new sound buffer
  1433. */
  1434. return_code= SoundObject->CreateSoundBuffer (&BufferDesc , &st->PlayBuffer , NULL);
  1435. if (return_code==DSERR_BUFFERLOST){
  1436. if (!Attempt_Audio_Restore(st->PlayBuffer)) return(-1);
  1437. }
  1438. /*
  1439. ** Just return if the create failed unexpectedly
  1440. **
  1441. ** If we failed then flag the buffer as having an impossible format so it wont match
  1442. ** any sample. This will ensure that we try and create the buffer again next time its used.
  1443. */
  1444. if (return_code!=DS_OK && return_code!=DSERR_BUFFERLOST){
  1445. st->PlaybackRate = 0;
  1446. st->Stereo = 0;
  1447. st->BitSize = 0;
  1448. return(-1);
  1449. }
  1450. /*
  1451. ** Remember the format of the new buffer
  1452. */
  1453. st->PlaybackRate = RawHeader.Rate;
  1454. st->Stereo = RawHeader.Flags & AUD_FLAG_STEREO;
  1455. st->BitSize = RawHeader.Flags & AUD_FLAG_16BIT;
  1456. }
  1457. /*
  1458. ** Fill in 3/4 of the play buffer.
  1459. */
  1460. //
  1461. // Stop the sound buffer playing before we lock it
  1462. //
  1463. do {
  1464. DumpBuffer = st->PlayBuffer;
  1465. return_code = st->PlayBuffer->GetStatus ( &play_status );
  1466. if (return_code==DSERR_BUFFERLOST){
  1467. if (!Attempt_Audio_Restore(st->PlayBuffer)) return(-1);
  1468. }
  1469. } while (return_code==DSERR_BUFFERLOST);
  1470. if (play_status & (DSBSTATUS_PLAYING | DSBSTATUS_LOOPING) ){
  1471. st->Active=0;
  1472. st->Service=0;
  1473. st->MoreSource=0;
  1474. st->PlayBuffer->Stop();
  1475. }
  1476. //
  1477. // Lock the direct sound buffer so we can write to it
  1478. //
  1479. do {
  1480. return_code = st->PlayBuffer->Lock ( 0 ,
  1481. SECONDARY_BUFFER_SIZE,
  1482. &play_buffer_ptr,
  1483. &lock_length1,
  1484. &dummy_buffer_ptr,
  1485. &lock_length2,
  1486. 0 );
  1487. if (return_code==DSERR_BUFFERLOST){
  1488. if (!Attempt_Audio_Restore(st->PlayBuffer)) return(-1);
  1489. }
  1490. } while (return_code==DSERR_BUFFERLOST);
  1491. if (return_code != DS_OK) {
  1492. //LeaveCriticalSection (&GlobalAudioCriticalSection);
  1493. return (-1);
  1494. }
  1495. //
  1496. // Decompress the sample into the direct sound buffer
  1497. //
  1498. st->DestPtr=(void*)Sample_Copy ( st,
  1499. &st->Source,
  1500. &st->Remainder,
  1501. &st->QueueBuffer,
  1502. &st->QueueSize,
  1503. play_buffer_ptr,
  1504. SECONDARY_BUFFER_SIZE*1/4,
  1505. st->Compression,
  1506. &st->Trailer[0],
  1507. &st->TrailerLen);
  1508. if ( st->DestPtr==(void*) (SECONDARY_BUFFER_SIZE*1/4) ){
  1509. // Must be more data to copy so we dont need to zero the buffer
  1510. st->MoreSource=TRUE;
  1511. st->Service=TRUE;
  1512. st->OneShot=FALSE;
  1513. } else {
  1514. // Whole sample is in the buffer so flag that we dont need to
  1515. // copy more. Clear out the end of the buffer so that it
  1516. // goes quiet if we play past the end
  1517. st->MoreSource=FALSE;
  1518. st->OneShot=TRUE;
  1519. st->Service=TRUE; //We still need to service it so that we can stop it when
  1520. // it plays past the end of the sample data
  1521. //memset ( (char*)( (unsigned)play_buffer_ptr + (unsigned)st->DestPtr ), 0 , SECONDARY_BUFFER_SIZE - (unsigned)st->DestPtr );
  1522. memset ( (char*)( (unsigned)play_buffer_ptr + (unsigned)st->DestPtr ), 0 , SECONDARY_BUFFER_SIZE/4);
  1523. }
  1524. st->PlayBuffer->Unlock( play_buffer_ptr,
  1525. lock_length1,
  1526. dummy_buffer_ptr,
  1527. lock_length2);
  1528. /*
  1529. **
  1530. ** Set the volume of the sample.
  1531. **
  1532. */
  1533. st->Volume = (volume << 7);
  1534. do {
  1535. //return_code = st->PlayBuffer->SetVolume ( Convert_HMI_To_Direct_Sound_Volume(volume));
  1536. st->PlayBuffer->SetVolume ( Convert_HMI_To_Direct_Sound_Volume( ( LockedData.SoundVolume*volume)/256) );
  1537. //return_code = st->PlayBuffer->SetVolume (- ( ( (32768- ( (st->Volume >> 8) *LockedData.SoundVolume) )
  1538. // *1000) >>15 ) );
  1539. if (return_code==DSERR_BUFFERLOST){
  1540. if (!Attempt_Audio_Restore(st->PlayBuffer)) return(-1);
  1541. }
  1542. } while (return_code==DSERR_BUFFERLOST);
  1543. /*
  1544. ** Make sure the primary sound buffer is playing
  1545. */
  1546. if (!Start_Primary_Sound_Buffer(FALSE)){
  1547. //LeaveCriticalSection (&GlobalAudioCriticalSection);
  1548. return(-1);
  1549. }
  1550. /*
  1551. ** Set the buffers play pointer to the beginning of the buffer
  1552. */
  1553. do {
  1554. return_code = st->PlayBuffer->SetCurrentPosition (0);
  1555. if (return_code==DSERR_BUFFERLOST){
  1556. if (!Attempt_Audio_Restore(st->PlayBuffer)) return(-1);
  1557. }
  1558. } while (return_code==DSERR_BUFFERLOST);
  1559. /*
  1560. ** Start the sample playing now.
  1561. */
  1562. do
  1563. {
  1564. return_code = st->PlayBuffer->Play (0,0,DSBPLAY_LOOPING);
  1565. switch (return_code){
  1566. case DS_OK :
  1567. EnterCriticalSection (&GlobalAudioCriticalSection);
  1568. st->Active=TRUE;
  1569. st->Handle=(short)id;
  1570. st->DontTouch = FALSE;
  1571. LeaveCriticalSection (&GlobalAudioCriticalSection);
  1572. return (st->Handle);
  1573. case DSERR_BUFFERLOST :
  1574. if (!Attempt_Audio_Restore(st->PlayBuffer)) return(-1);
  1575. break;
  1576. default:
  1577. st->Active=FALSE;
  1578. //LeaveCriticalSection (&GlobalAudioCriticalSection);
  1579. return (st->Handle);
  1580. }
  1581. } while (return_code==DSERR_BUFFERLOST);
  1582. //LeaveCriticalSection (&GlobalAudioCriticalSection);
  1583. return (st->Handle);
  1584. }
  1585. /***********************************************************************************************
  1586. * Restore_Sound_Buffers -- restore the sound buffers *
  1587. * *
  1588. * *
  1589. * *
  1590. * INPUT: Nothing *
  1591. * *
  1592. * OUTPUT: Nothing *
  1593. * *
  1594. * WARNINGS: None *
  1595. * *
  1596. * HISTORY: *
  1597. * 11/3/95 3:53PM ST : Created *
  1598. *=============================================================================================*/
  1599. void Restore_Sound_Buffers ( void )
  1600. {
  1601. if (PrimaryBufferPtr){
  1602. PrimaryBufferPtr->Restore();
  1603. }
  1604. for ( int index = 0; index < MAX_SFX; index++) {
  1605. if (LockedData.SampleTracker[index].PlayBuffer){
  1606. LockedData.SampleTracker[index].PlayBuffer->Restore();
  1607. }
  1608. }
  1609. }
  1610. /***********************************************************************************************
  1611. * Set_Sound_Vol -- sets the overall volume for sampled sounds *
  1612. * *
  1613. * *
  1614. * *
  1615. * INPUT: volume *
  1616. * *
  1617. * OUTPUT: the previous volume setting *
  1618. * *
  1619. * WARNINGS: None *
  1620. * *
  1621. * HISTORY: *
  1622. * 11/2/95 4:19PM ST : Added function header *
  1623. *=============================================================================================*/
  1624. int Set_Sound_Vol(int volume)
  1625. {
  1626. int old;
  1627. old = LockedData.SoundVolume;
  1628. LockedData.SoundVolume = volume & 0xFF;
  1629. return(old);
  1630. }
  1631. /***********************************************************************************************
  1632. * Set_Score_Vol -- sets the overall volume for music scores *
  1633. * *
  1634. * *
  1635. * *
  1636. * INPUT: volume *
  1637. * *
  1638. * OUTPUT: the previous volume setting *
  1639. * *
  1640. * WARNINGS: None *
  1641. * *
  1642. * HISTORY: *
  1643. * 11/2/95 4:19PM ST : Added function header *
  1644. *=============================================================================================*/
  1645. int Set_Score_Vol(int volume)
  1646. {
  1647. int old;
  1648. SampleTrackerType *st; //ptr to SampleTracker structure
  1649. old = LockedData.ScoreVolume;
  1650. LockedData.ScoreVolume = volume & 0xFF;
  1651. for (int index=0 ; index<MAX_SFX ; index++){
  1652. st = &LockedData.SampleTracker[index];
  1653. if (st->IsScore && st->Active){
  1654. //st->PlayBuffer->SetVolume (- ( ( (32768- ( (st->Volume >> 8) *LockedData.ScoreVolume) )
  1655. // *1000) >>15 ) );
  1656. //st->PlayBuffer->SetVolume ( Convert_HMI_To_Direct_Sound_Volume ( st->Volume >>7 ) );
  1657. st->PlayBuffer->SetVolume ( Convert_HMI_To_Direct_Sound_Volume( ( LockedData.ScoreVolume*(st->Volume >>7))/256) );
  1658. }
  1659. }
  1660. return(old);
  1661. }
  1662. /***********************************************************************************************
  1663. * Fade_Sample -- Start a sample fading *
  1664. * *
  1665. * *
  1666. * *
  1667. * INPUT: Sample handle *
  1668. * fade rate *
  1669. * *
  1670. * OUTPUT: Nothing *
  1671. * *
  1672. * WARNINGS: None *
  1673. * *
  1674. * HISTORY: *
  1675. * 11/2/95 4:21PM ST : Added function header *
  1676. *=============================================================================================*/
  1677. void Fade_Sample(int handle, int ticks)
  1678. {
  1679. if (Sample_Status(handle)) {
  1680. if (!ticks || LockedData.SampleTracker[handle].Loading) {
  1681. Stop_Sample(handle);
  1682. } else {
  1683. SampleTrackerType * st;
  1684. st = &LockedData.SampleTracker[handle];
  1685. st->Reducer = (short) ((st->Volume / ticks)+1);
  1686. }
  1687. }
  1688. }
  1689. int Get_Digi_Handle(void)
  1690. {
  1691. return(LockedData.DigiHandle);
  1692. }
  1693. /***************************************************************************
  1694. * SAMPLE_LENGTH -- returns length of a sample in ticks *
  1695. * *
  1696. * INPUT: void const *sample - pointer to the sample to get length of. *
  1697. * *
  1698. * OUTPUT: long - length of the sample in ticks (60/sec) *
  1699. * *
  1700. * HISTORY: *
  1701. * 07/05/1995 PWG : Created. *
  1702. *=========================================================================*/
  1703. long Sample_Length(void const *sample)
  1704. {
  1705. AUDHeaderType RawHeader;
  1706. if (!sample) return(0);
  1707. Mem_Copy((void *)sample, (void *)&RawHeader, sizeof(RawHeader));
  1708. long time = RawHeader.UncompSize;
  1709. /*
  1710. ** If the sample is a 16 bit sample, then it will take only half
  1711. ** as long to play.
  1712. */
  1713. if (RawHeader.Flags & AUD_FLAG_16BIT) {
  1714. time >>= 1;
  1715. }
  1716. /*
  1717. ** If the sample is a stereo sample, then it will take only half
  1718. ** as long to play.
  1719. */
  1720. if (RawHeader.Flags & AUD_FLAG_STEREO) {
  1721. time >>= 1;
  1722. }
  1723. if (RawHeader.Rate/60) {
  1724. time /= (RawHeader.Rate/60);
  1725. }
  1726. return(time);
  1727. }
  1728. /***********************************************************************************************
  1729. * Start_Primary_Sound_Buffer -- start the primary sound buffer playing *
  1730. * *
  1731. * *
  1732. * *
  1733. * INPUT: Nothing *
  1734. * *
  1735. * OUTPUT: Nothing *
  1736. * *
  1737. * WARNINGS: None *
  1738. * *
  1739. * HISTORY: *
  1740. * 2/1/96 12:28PM ST : Created *
  1741. *=============================================================================================*/
  1742. extern BOOL GameInFocus;
  1743. BOOL Start_Primary_Sound_Buffer (BOOL forced)
  1744. {
  1745. DWORD status;
  1746. if (PrimaryBufferPtr && GameInFocus){
  1747. if (forced){
  1748. PrimaryBufferPtr->Play(0,0,DSBPLAY_LOOPING);
  1749. return (TRUE);
  1750. } else {
  1751. if (PrimaryBufferPtr->GetStatus (&status) == DS_OK){
  1752. if (! ((status & DSBSTATUS_PLAYING) || (status & DSBSTATUS_LOOPING))){
  1753. PrimaryBufferPtr->Play(0,0,DSBPLAY_LOOPING);
  1754. return (TRUE);
  1755. }else{
  1756. return (TRUE);
  1757. }
  1758. }
  1759. }
  1760. }
  1761. return (FALSE);
  1762. }
  1763. /***********************************************************************************************
  1764. * Stop_Primary_Sound_Buffer -- stops the primary sound buffer from playing. *
  1765. * *
  1766. * *
  1767. * *
  1768. * INPUT: Nothing *
  1769. * *
  1770. * OUTPUT: Nothing *
  1771. * *
  1772. * WARNINGS: This stops all sound playback *
  1773. * *
  1774. * HISTORY: *
  1775. * 2/1/96 12:28PM ST : Created *
  1776. *=============================================================================================*/
  1777. void Stop_Primary_Sound_Buffer (void)
  1778. {
  1779. if (PrimaryBufferPtr){
  1780. PrimaryBufferPtr->Stop();
  1781. PrimaryBufferPtr->Stop(); // Oh I
  1782. PrimaryBufferPtr->Stop(); // Hate Direct Sound
  1783. PrimaryBufferPtr->Stop(); // So much.....
  1784. }
  1785. for ( int index = 0; index < MAX_SFX; index++) {
  1786. Stop_Sample(index);
  1787. }
  1788. }
  1789. void Suspend_Audio_Thread(void)
  1790. {
  1791. if (SoundThreadActive){
  1792. //SuspendThread(SoundThreadHandle);
  1793. timeKillEvent(SoundTimerHandle);
  1794. SoundTimerHandle = NULL;
  1795. SoundThreadActive = FALSE;
  1796. }
  1797. }
  1798. void Resume_Audio_Thread(void)
  1799. {
  1800. if (!SoundThreadActive){
  1801. //ResumeThread(SoundThreadHandle);
  1802. SoundTimerHandle = timeSetEvent ( 1000/MAINTENANCE_RATE , 1 , Sound_Timer_Callback , 0 , TIME_PERIODIC);
  1803. SoundThreadActive = TRUE;
  1804. }
  1805. }