2 * $Logfile: /Freespace2/code/Sound/ds.cpp $
7 * C file for interface to DirectSound
10 * Revision 1.5 2002/06/02 09:50:42 relnev
13 * Revision 1.4 2002/06/02 07:17:44 cemason
14 * Added OpenAL support.
16 * Revision 1.3 2002/05/28 17:03:29 theoddone33
17 * fs2 gets to the main game loop now
19 * Revision 1.2 2002/05/27 21:35:50 theoddone33
20 * Stub out dsound backend
22 * Revision 1.1.1.1 2002/05/03 03:28:10 root
26 * 18 10/25/99 5:56p Jefff
27 * increase num software channels to the number the users hardware can
28 * handle. not less than 16, tho.
30 * 17 9/08/99 3:22p Dave
31 * Updated builtin mission list.
33 * 16 8/27/99 6:38p Alanl
34 * crush the blasted repeating messages bug
36 * 15 8/23/99 11:16p Danw
39 * 14 8/22/99 11:06p Alanl
40 * fix small bug in ds_close_channel
42 * 13 8/19/99 11:25a Alanl
43 * change format of secondary buffer from 44100 to 22050
45 * 12 8/17/99 4:11p Danw
46 * AL: temp fix for solving A3D crash
48 * 11 8/06/99 2:20p Jasonh
49 * AL: free 3D portion of buffer first
51 * 10 8/04/99 9:48p Alanl
52 * fix bug with setting 3D properties on a 2D sound buffer
54 * 9 8/04/99 11:42a Danw
55 * tone down EAX reverb
57 * 8 8/01/99 2:06p Alanl
58 * increase the rolloff for A3D
60 * 7 7/20/99 5:28p Dave
61 * Fixed debug build error.
63 * 6 7/20/99 1:49p Dave
64 * Peter Drake build. Fixed some release build warnings.
66 * 5 7/14/99 11:32a Danw
67 * AL: add some debug code to catch nefarious A3D problem
69 * 4 5/23/99 8:11p Alanl
70 * Added support for EAX
72 * 3 10/08/98 4:29p Dave
73 * Removed reference to osdefs.h
75 * 2 10/07/98 10:54a Dave
78 * 1 10/07/98 10:51a Dave
80 * 72 6/28/98 6:34p Lawrance
81 * add sanity check in while() loop for releasing channels
83 * 71 6/13/98 1:45p Sandeep
85 * 70 6/10/98 2:29p Lawrance
86 * don't use COM for initializing DirectSound... appears some machines
89 * 69 5/26/98 2:10a Lawrance
90 * make sure DirectSound pointer gets freed if Aureal resource manager
93 * 68 5/21/98 9:14p Lawrance
94 * remove obsolete registry setting
96 * 67 5/20/98 4:28p Allender
97 * upped sound buffers as per alan's request
99 * 66 5/15/98 3:36p John
100 * Fixed bug with new graphics window code and standalone server. Made
101 * hwndApp not be a global anymore.
103 * 65 5/06/98 3:37p Lawrance
104 * allow panned sounds geesh
106 * 64 5/05/98 4:49p Lawrance
107 * Put in code to authenticate A3D, improve A3D support
109 * 63 4/20/98 11:17p Lawrance
110 * fix bug with releasing channels
112 * 62 4/20/98 7:34p Lawrance
113 * take out obsolete directsound3d debug command
115 * 61 4/20/98 11:10a Lawrance
116 * put correct flags when creating sound buffer
118 * 60 4/20/98 12:03a Lawrance
119 * Allow prioritizing of CTRL3D buffers
121 * 59 4/19/98 9:31p Lawrance
122 * Use Aureal_enabled flag
124 * 58 4/19/98 9:39a Lawrance
125 * use DYNAMIC_LOOPERS for Aureal resource manager
127 * 57 4/19/98 4:13a Lawrance
128 * Improve how dsound is initialized
130 * 56 4/18/98 9:13p Lawrance
131 * Added Aureal support.
133 * 55 4/13/98 5:04p Lawrance
134 * Write functions to determine how many milliseconds are left in a sound
136 * 54 4/09/98 5:53p Lawrance
137 * Make DirectSound init more robust
139 * 53 4/01/98 9:21p John
140 * Made NDEBUG, optimized build with no warnings or errors.
142 * 52 3/31/98 5:19p John
143 * Removed demo/save/restore. Made NDEBUG defined compile. Removed a
144 * bunch of debug stuff out of player file. Made model code be able to
145 * unload models and malloc out only however many models are needed.
148 * 51 3/29/98 12:56a Lawrance
149 * preload the warp in and explosions sounds before a mission.
151 * 50 3/25/98 6:10p Lawrance
152 * Work on DirectSound3D
154 * 49 3/24/98 4:28p Lawrance
155 * Make DirectSound3D support more robust
157 * 48 3/24/98 11:49a Dave
158 * AL: Change way buffer gets locked.
160 * 47 3/24/98 11:27a Lawrance
161 * Use buffer_size for memcpy when locking buffer
163 * 46 3/23/98 10:32a Lawrance
164 * Add functions for extracting raw sound data
166 * 45 3/19/98 5:36p Lawrance
167 * Add some sound debug functions to see how many sounds are playing, and
168 * to start/stop random looping sounds.
170 * 44 3/07/98 3:35p Dave
171 * AL: check for ds being initialized in ds_create_buffer()
173 * 43 2/18/98 5:49p Lawrance
174 * Even if the ADPCM codec is unavailable, allow game to continue.
176 * 42 2/16/98 7:31p Lawrance
177 * get compression/decompression of voice working
179 * 41 2/15/98 11:10p Lawrance
180 * more work on real-time voice system
182 * 40 2/15/98 4:43p Lawrance
183 * work on real-time voice
185 * 39 2/06/98 7:30p John
186 * Added code to monitor the number of channels of sound actually playing.
188 * 38 2/06/98 8:56a Allender
189 * fixed calling convention problem with DLL handles
191 * 37 2/04/98 6:08p Lawrance
192 * Read function pointers from dsound.dll, further work on
193 * DirectSoundCapture.
195 * 36 2/03/98 11:53p Lawrance
196 * Adding support for DirectSoundCapture
198 * 35 1/31/98 5:48p Lawrance
199 * Start on real-time voice recording
201 * 34 1/10/98 1:14p John
202 * Added explanation to debug console commands
204 * 33 12/21/97 4:33p John
205 * Made debug console functions a class that registers itself
206 * automatically, so you don't need to add the function to
207 * debugfunctions.cpp.
209 * 32 12/08/97 12:24a Lawrance
210 * Allow duplicate sounds to be stopped if less than OR equal to new sound
213 * 31 12/05/97 5:19p Lawrance
214 * re-do sound priorities to make more general and extensible
216 * 30 11/28/97 2:09p Lawrance
217 * Overhaul how ADPCM conversion works... use much less memory... safer
220 * 29 11/22/97 11:32p Lawrance
221 * decompress ADPCM data into 8 bit (not 16bit) for regular sounds (ie not
224 * 28 11/20/97 5:36p Dave
225 * Hooked in a bunch of main hall changes (including sound). Made it
226 * possible to reposition (rewind/ffwd)
227 * sound buffer pointers. Fixed animation direction change framerate
230 * 27 10/13/97 7:41p Lawrance
231 * store duration of sound
233 * 26 10/11/97 6:39p Lawrance
234 * start playing primary buffer, to reduce latency on sounds starting
236 * 25 10/08/97 5:09p Lawrance
237 * limit player impact sounds so only one plays at a time
239 * 24 9/26/97 5:43p Lawrance
240 * fix a bug that was freeing memory early when playing compressed sound
243 * 23 9/09/97 3:39p Sandeep
244 * warning level 4 bugs
246 * 22 8/16/97 4:05p Lawrance
247 * don't load sounds into hardware if running Lean_and_mean
249 * 21 8/05/97 1:39p Lawrance
250 * support compressed stereo playback
252 * 20 7/31/97 10:38a Lawrance
253 * return old debug function for toggling DirectSound3D
255 * 19 7/29/97 3:27p Lawrance
256 * make console toggle for directsound3d work right
258 * 18 7/28/97 11:39a Lawrance
259 * allow individual volume scaling on 3D buffers
261 * 17 7/18/97 8:18p Lawrance
262 * fix bug in ds_get_free_channel() that caused sounds to not play when
265 * 16 7/17/97 8:04p Lawrance
266 * allow priority sounds to play if free channel, otherwise stop lowest
267 * volume priority sound of same type
269 * 15 7/17/97 5:57p John
270 * made directsound3d config value work
272 * 14 7/17/97 5:43p John
273 * added new config stuff
275 * 13 7/17/97 4:25p John
276 * First, broken, stage of changing config stuff
278 * 12 7/15/97 12:13p Lawrance
279 * don't stop sounds that have highest priority
281 * 11 7/15/97 11:15a Lawrance
282 * limit the max instances of simultaneous sound effects, implement
283 * priorities to force critical sounds
285 * 10 6/09/97 11:50p Lawrance
286 * integrating DirectSound3D
288 * 9 6/08/97 5:59p Lawrance
289 * integrate DirectSound3D into sound system
291 * 8 6/04/97 1:19p Lawrance
292 * made hardware mixing robust
294 * 7 6/03/97 1:56p Hoffoss
295 * Return correct error code when direct sound init fails.
297 * 6 6/03/97 12:07p Lawrance
298 * don't enable 3D sounds in Primary buffer
300 * 5 6/02/97 3:45p Dan
301 * temp disable of hardware mixing until problem solved with
302 * CreateBuffer() failing
304 * 4 6/02/97 1:45p Lawrance
305 * implementing hardware mixing
307 * 3 5/29/97 4:01p Lawrance
308 * let snd_init() have final say on initialization
310 * 2 5/29/97 12:04p Lawrance
311 * creation of file to hold DirectSound specific portions
330 #include <initguid.h>
332 #include "verifya3d.h"
337 #include <SDL/SDL_audio.h>
341 // Pointers to functions contained in DSOUND.dll
342 HRESULT (__stdcall *pfn_DirectSoundCreate)(LPGUID lpGuid, LPDIRECTSOUND *ppDS, IUnknown FAR *pUnkOuter) = NULL;
343 HRESULT (__stdcall *pfn_DirectSoundCaptureCreate)(LPGUID lpGUID, LPDIRECTSOUNDCAPTURE *lplpDSC, LPUNKNOWN pUnkOuter) = NULL;
345 HINSTANCE Ds_dll_handle=NULL;
347 LPDIRECTSOUND pDirectSound = NULL;
348 LPDIRECTSOUNDBUFFER pPrimaryBuffer = NULL;
349 LPIA3D2 pIA3d2 = NULL;
351 static LPKSPROPERTYSET pPropertySet; // pointer to sound card property set
352 static LPDIRECTSOUNDBUFFER Ds_property_set_pdsb = NULL;
353 static LPDIRECTSOUND3DBUFFER Ds_property_set_pds3db = NULL;
355 static int Ds_must_call_couninitialize = 0;
357 channel* Channels; //[MAX_CHANNELS];
358 static int channel_next_sig = 1;
360 #define MAX_DS_SOFTWARE_BUFFERS 256
361 typedef struct ds_sound_buffer
363 LPDIRECTSOUNDBUFFER pdsb;
369 ds_sound_buffer ds_software_buffers[MAX_DS_SOFTWARE_BUFFERS];
371 #define MAX_DS_HARDWARE_BUFFERS 32
372 ds_sound_buffer ds_hardware_buffers[MAX_DS_HARDWARE_BUFFERS];
374 static DSCAPS Soundcard_caps; // current soundcard capabilities
376 extern int Snd_sram; // mem (in bytes) used up by storing sounds in system memory
377 extern int Snd_hram; // mem (in bytes) used up by storing sounds in soundcard memory
379 static int Ds_use_ds3d = 0;
380 static int Ds_use_a3d = 0;
381 static int Ds_use_eax = 0;
383 GUID IID_IA3d2_Def = {0xfb80d1e0, 0x98d3, 0x11d1, {0x90, 0xfb, 0x00, 0x60, 0x08, 0xa1, 0xf4, 0x41}};
384 GUID CLSID_A3d_Def = {0xd8f1eee0, 0xf634, 0x11cf, {0x87, 0x0, 0x0, 0xa0, 0x24, 0x5d, 0x91, 0x8b}};
386 static bool Stop_logging_sounds = false;
389 ///////////////////////////
393 ///////////////////////////
396 //#define EAX_PRESET_GENERIC EAX_ENVIRONMENT_GENERIC,0.5F,1.493F,0.5F
397 #define EAX_PRESET_GENERIC EAX_ENVIRONMENT_GENERIC,0.2F,0.2F,1.0F
398 #define EAX_PRESET_PADDEDCELL EAX_ENVIRONMENT_PADDEDCELL,0.25F,0.1F,0.0F
399 #define EAX_PRESET_ROOM EAX_ENVIRONMENT_ROOM,0.417F,0.4F,0.666F
400 #define EAX_PRESET_BATHROOM EAX_ENVIRONMENT_BATHROOM,0.653F,1.499F,0.166F
401 #define EAX_PRESET_LIVINGROOM EAX_ENVIRONMENT_LIVINGROOM,0.208F,0.478F,0.0F
402 #define EAX_PRESET_STONEROOM EAX_ENVIRONMENT_STONEROOM,0.5F,2.309F,0.888F
403 #define EAX_PRESET_AUDITORIUM EAX_ENVIRONMENT_AUDITORIUM,0.403F,4.279F,0.5F
404 #define EAX_PRESET_CONCERTHALL EAX_ENVIRONMENT_CONCERTHALL,0.5F,3.961F,0.5F
405 #define EAX_PRESET_CAVE EAX_ENVIRONMENT_CAVE,0.5F,2.886F,1.304F
406 #define EAX_PRESET_ARENA EAX_ENVIRONMENT_ARENA,0.361F,7.284F,0.332F
407 #define EAX_PRESET_HANGAR EAX_ENVIRONMENT_HANGAR,0.5F,10.0F,0.3F
408 #define EAX_PRESET_CARPETEDHALLWAY EAX_ENVIRONMENT_CARPETEDHALLWAY,0.153F,0.259F,2.0F
409 #define EAX_PRESET_HALLWAY EAX_ENVIRONMENT_HALLWAY,0.361F,1.493F,0.0F
410 #define EAX_PRESET_STONECORRIDOR EAX_ENVIRONMENT_STONECORRIDOR,0.444F,2.697F,0.638F
411 #define EAX_PRESET_ALLEY EAX_ENVIRONMENT_ALLEY,0.25F,1.752F,0.776F
412 #define EAX_PRESET_FOREST EAX_ENVIRONMENT_FOREST,0.111F,3.145F,0.472F
413 #define EAX_PRESET_CITY EAX_ENVIRONMENT_CITY,0.111F,2.767F,0.224F
414 #define EAX_PRESET_MOUNTAINS EAX_ENVIRONMENT_MOUNTAINS,0.194F,7.841F,0.472F
415 #define EAX_PRESET_QUARRY EAX_ENVIRONMENT_QUARRY,1.0F,1.499F,0.5F
416 #define EAX_PRESET_PLAIN EAX_ENVIRONMENT_PLAIN,0.097F,2.767F,0.224F
417 #define EAX_PRESET_PARKINGLOT EAX_ENVIRONMENT_PARKINGLOT,0.208F,1.652F,1.5F
418 #define EAX_PRESET_SEWERPIPE EAX_ENVIRONMENT_SEWERPIPE,0.652F,2.886F,0.25F
419 #define EAX_PRESET_UNDERWATER EAX_ENVIRONMENT_UNDERWATER,1.0F,1.499F,0.0F
420 #define EAX_PRESET_DRUGGED EAX_ENVIRONMENT_DRUGGED,0.875F,8.392F,1.388F
421 #define EAX_PRESET_DIZZY EAX_ENVIRONMENT_DIZZY,0.139F,17.234F,0.666F
422 #define EAX_PRESET_PSYCHOTIC EAX_ENVIRONMENT_PSYCHOTIC,0.486F,7.563F,0.806F
424 static LPKSPROPERTYSET Ds_eax_reverb = NULL;
426 static int Ds_eax_inited = 0;
428 EAX_REVERBPROPERTIES Ds_eax_presets[] =
430 {EAX_PRESET_GENERIC},
431 {EAX_PRESET_PADDEDCELL},
433 {EAX_PRESET_BATHROOM},
434 {EAX_PRESET_LIVINGROOM},
435 {EAX_PRESET_STONEROOM},
436 {EAX_PRESET_AUDITORIUM},
437 {EAX_PRESET_CONCERTHALL},
441 {EAX_PRESET_CARPETEDHALLWAY},
442 {EAX_PRESET_HALLWAY},
443 {EAX_PRESET_STONECORRIDOR},
447 {EAX_PRESET_MOUNTAINS},
450 {EAX_PRESET_PARKINGLOT},
451 {EAX_PRESET_SEWERPIPE},
452 {EAX_PRESET_UNDERWATER},
453 {EAX_PRESET_DRUGGED},
455 {EAX_PRESET_PSYCHOTIC},
458 GUID DSPROPSETID_EAX_ReverbProperties_Def = {0x4a4e6fc1, 0xc341, 0x11d1, {0xb7, 0x3a, 0x44, 0x45, 0x53, 0x54, 0x00, 0x00}};
459 GUID DSPROPSETID_EAXBUFFER_ReverbProperties_Def = {0x4a4e6fc0, 0xc341, 0x11d1, {0xb7, 0x3a, 0x44, 0x45, 0x53, 0x54, 0x00, 0x00}};
461 //----------------------------------------------------------------
463 void ds_get_soundcard_caps(DSCAPS *dscaps);
465 static int Ds_use_ds3d = 0;
466 static int Ds_use_a3d = 0;
467 static int Ds_use_eax = 0;
469 ALCdevice *ds_sound_device;
470 void *ds_sound_context = (void *)0;
474 static int MAX_CHANNELS = 0; // initialized properly in ds_init_channels()
476 int ds_vol_lookup[101]; // lookup table for direct sound volumes
477 int ds_initialized = FALSE;
480 //--------------------------------------------------------------------------
483 // Determine if a secondary buffer is a 3d secondary buffer.
486 int ds_is_3d_buffer(LPDIRECTSOUNDBUFFER pdsb)
491 dsbc.dwSize = sizeof(dsbc);
492 hr = pdsb->GetCaps(&dsbc);
493 if ( hr == DS_OK && dsbc.dwFlags & DSBCAPS_CTRL3D ) {
502 //--------------------------------------------------------------------------
505 // Determine if a secondary buffer is a 3d secondary buffer.
507 int ds_is_3d_buffer(int sid)
511 return ds_is_3d_buffer(ds_software_buffers[sid].pdsb);
520 //--------------------------------------------------------------------------
521 // ds_build_vol_lookup()
523 // Fills up the ds_vol_lookup[] tables that converts from a volume in the form
524 // 0.0 -> 1.0 to -10000 -> 0 (this is the DirectSound method, where units are
525 // hundredths of decibls)
527 void ds_build_vol_lookup()
532 ds_vol_lookup[0] = -10000;
533 for ( i = 1; i <= 100; i++ ) {
535 ds_vol_lookup[i] = fl2i( (log(vol) / log(2.0f)) * 1000.0f);
540 //--------------------------------------------------------------------------
541 // ds_convert_volume()
543 // Takes volume between 0.0f and 1.0f and converts into
544 // DirectSound style volumes between -10000 and 0.
545 int ds_convert_volume(float volume)
549 index = fl2i(volume * 100.0f);
555 return ds_vol_lookup[index];
558 //--------------------------------------------------------------------------
559 // ds_get_percentage_vol()
561 // Converts -10000 -> 0 range volume to 0 -> 1
562 float ds_get_percentage_vol(int ds_vol)
565 vol = pow(2.0, ds_vol/1000.0);
569 static unsigned char *Force8to16 (unsigned char *buf, unsigned int *len)
574 nbuf = (unsigned char *) malloc (*len * 2);
576 for (i = 0; i < *len; i++) {
577 short int x = ((buf[i] << 8) | buf[i]) ^ 0x8000;
578 nbuf[i*2+0] = (x & 0x00ff);
579 nbuf[i*2+1] = (x >> 8) & 0xff;
588 extern void *acLoadWAV (void *data, ALuint *size, void **udata,
589 ALushort *fmt, ALushort *chan, ALushort *freq);
592 // ---------------------------------------------------------------------------------------
595 // Parse a wave file.
597 // parameters: filename => file of sound to parse
598 // dest => address of pointer of where to store raw sound data (output parm)
599 // dest_size => number of bytes of sound data stored (output parm)
600 // header => address of pointer to a WAVEFORMATEX struct (output parm)
602 // returns: 0 => wave file successfully parsed
605 // NOTE: memory is malloced for the header and dest in this function. It is the responsibility
606 // of the caller to free this memory later.
608 int ds_parse_wave(char *filename, ubyte **dest, uint *dest_size, WAVEFORMATEX **header)
615 ALvoid *data, *my_data;
618 nprintf (("Sound", "SOUND ==> ds_parse_wave(%s)", filename));
620 fp = cfopen (filename, "rb");
622 nprintf(("Error", "Couldn't open '%s'\n", filename ));
627 cfseek (fp, 0, CF_SEEK_END);
630 fp = cfopen (filename, "rb");
631 data = (ALvoid *) malloc(len);
632 cfread(data, len, 1, fp);
635 if (acLoadWAV (data, &size, &my_data, &fmt, &chan, &freq) == NULL)
640 if((fmt == AUDIO_U8)) {
641 nb = Force8to16 ((unsigned char *)my_data, (unsigned int *)&len);
647 if (fmt == AUDIO_S16LSB || fmt == AUDIO_S16MSB) {
649 fmt = AL_FORMAT_STEREO16;
651 fmt = AL_FORMAT_MONO16;
655 (*dest) = (ubyte *)malloc(sizeof(ALuint));
656 alGenBuffers (1, &pi);
657 alBufferData (pi, fmt, my_data, len, freq);
658 *((ALuint*)(*dest)) = (pi);
661 (*header) = (WAVEFORMATEX *) malloc ( sizeof(WAVEFORMATEX) );
662 (*header)->wFormatTag = fmt;
663 (*header)->nChannels = 1;
664 (*header)->nSamplesPerSec = freq;
665 (*header)->wBitsPerSample = 16;
666 (*header)->cbSize = len;
672 PCMWAVEFORMAT PCM_header;
674 unsigned int tag, size, next_chunk;
676 fp = cfopen( filename, "rb" );
678 nprintf(("Error", "Couldn't open '%s'\n", filename ));
682 // Skip the "RIFF" tag and file size (8 bytes)
683 // Skip the "WAVE" tag (4 bytes)
684 cfseek( fp, 12, CF_SEEK_SET );
686 // Now read RIFF tags until the end of file
689 if ( cfread( &tag, sizeof(uint), 1, fp ) != 1 )
692 if ( cfread( &size, sizeof(uint), 1, fp ) != 1 )
695 next_chunk = cftell(fp) + size;
698 case 0x20746d66: // The 'fmt ' tag
699 //nprintf(("Sound", "SOUND => size of fmt block: %d\n", size));
700 cfread( &PCM_header, sizeof(PCMWAVEFORMAT), 1, fp );
701 if ( PCM_header.wf.wFormatTag != WAVE_FORMAT_PCM ) {
702 cbExtra = cfread_short(fp);
705 // Allocate memory for WAVEFORMATEX structure + extra bytes
706 if ( (*header = (WAVEFORMATEX *) malloc ( sizeof(WAVEFORMATEX)+cbExtra )) != NULL ){
707 // Copy bytes from temporary format structure
708 memcpy (*header, &PCM_header, sizeof(PCM_header));
709 (*header)->cbSize = (unsigned short)cbExtra;
711 // Read those extra bytes, append to WAVEFORMATEX structure
713 cfread( ((ubyte *)(*header) + sizeof(WAVEFORMATEX)), cbExtra, 1, fp);
717 Assert(0); // malloc failed
721 case 0x61746164: // the 'data' tag
723 (*dest) = (ubyte *)malloc(size);
724 Assert( *dest != NULL );
725 cfread( *dest, size, 1, fp );
727 default: // unknown, skip it
730 cfseek( fp, next_chunk, CF_SEEK_SET );
739 // ---------------------------------------------------------------------------------------
751 for ( i = 0; i < MAX_DS_SOFTWARE_BUFFERS; i++ ) {
752 if ( ds_software_buffers[i].pdsb == NULL )
756 if ( i == MAX_DS_SOFTWARE_BUFFERS ) {
764 // ---------------------------------------------------------------------------------------
776 for ( i = 0; i < MAX_DS_HARDWARE_BUFFERS; i++ ) {
777 if ( ds_hardware_buffers[i].pdsb == NULL )
781 if ( i == MAX_DS_HARDWARE_BUFFERS ) {
789 // ---------------------------------------------------------------------------------------
790 // Load a DirectSound secondary buffer with sound data. The sounds data for
791 // game sounds are stored in the DirectSound secondary buffers, and are
792 // duplicated as needed and placed in the Channels[] array to be played.
796 // sid => pointer to software id for sound ( output parm)
797 // hid => pointer to hardware id for sound ( output parm)
798 // final_size => pointer to storage to receive uncompressed sound size (output parm)
799 // header => pointer to a WAVEFORMATEX structure
800 // si => sound_info structure, contains details on the sound format
801 // flags => buffer properties ( DS_HARDWARE , DS_3D )
803 // returns: -1 => sound effect could not loaded into a secondary buffer
804 // 0 => sound effect successfully loaded into a secondary buffer
807 // NOTE: this function is slow, especially when sounds are loaded into hardware. Don't call this
808 // function from within gameplay.
810 int ds_load_buffer(int *sid, int *hid, int *final_size, void *header, sound_info *si, int flags)
813 Assert( final_size != NULL );
814 Assert( header != NULL );
815 Assert( si != NULL );
816 Assert( si->data != NULL );
818 // All sounds are required to have a software buffer
819 ALuint pi = *((ALuint*)si->data); // Buffer
823 nprintf(("Sound","SOUND ==> Weird!\n"));
827 ALfloat pos[] = { 0, 0, 0 };
828 ALfloat vel[] = { 0, 0, 0 };
830 alGenSources (1, (ALuint*)hid);
831 alSourcef(*((ALuint*)hid), AL_PITCH, 1.0f);
832 alSourcef(*((ALuint*)hid), AL_GAIN, 1.0f);
833 alSourcefv(*((ALuint*)hid), AL_POSITION, pos);
834 alSourcefv(*((ALuint*)hid), AL_VELOCITY, vel);
836 int i = alGetError();
837 if(i != AL_NO_ERROR) {
838 printf("%s|||errorC!\n", alGetString(i));
844 Assert( final_size != NULL );
845 Assert( header != NULL );
846 Assert( si != NULL );
847 Assert( si->data != NULL );
848 Assert( si->size > 0 );
849 Assert( si->sample_rate > 0);
850 Assert( si->bits > 0 );
851 Assert( si->n_channels > 0 );
852 Assert( si->n_block_align >= 0 );
853 Assert( si->avg_bytes_per_sec > 0 );
855 WAVEFORMATEX *pwfx = (WAVEFORMATEX *)header;
856 DSBUFFERDESC BufferDesc;
857 WAVEFORMATEX WaveFormat;
859 int rc, final_sound_size, DSOUND_load_buffer_result = 0;
860 BYTE *pData, *pData2;
861 DWORD DataSize, DataSize2;
863 // the below two covnert_ variables are only used when the wav format is not
864 // PCM. DirectSound only takes PCM sound data, so we must convert to PCM if required
865 ubyte *convert_buffer = NULL; // storage for converted wav file
866 int convert_len; // num bytes of converted wav file
867 uint src_bytes_used; // number of source bytes actually converted (should always be equal to original size)
869 // Ensure DirectSound initialized
870 if (!ds_initialized) {
871 DSOUND_load_buffer_result = -1;
872 goto DSOUND_load_buffer_done;
875 // Set up buffer information
876 WaveFormat.wFormatTag = (unsigned short)si->format;
877 WaveFormat.nChannels = (unsigned short)si->n_channels;
878 WaveFormat.nSamplesPerSec = si->sample_rate;
879 WaveFormat.wBitsPerSample = (unsigned short)si->bits;
880 WaveFormat.cbSize = 0;
881 WaveFormat.nBlockAlign = (unsigned short)si->n_block_align;
882 WaveFormat.nAvgBytesPerSec = si->avg_bytes_per_sec;
884 final_sound_size = si->size; // assume this format will be used, may be over-ridded by convert_len
886 // Assert(WaveFormat.nChannels == 1);
888 switch ( si->format ) {
889 case WAVE_FORMAT_PCM:
892 case WAVE_FORMAT_ADPCM:
894 nprintf(( "Sound", "SOUND ==> converting sound from ADPCM to PCM\n" ));
895 rc = ACM_convert_ADPCM_to_PCM(pwfx, si->data, si->size, &convert_buffer, 0, &convert_len, &src_bytes_used, 8);
897 DSOUND_load_buffer_result = -1;
898 goto DSOUND_load_buffer_done;
901 if (src_bytes_used != si->size) {
902 Int3(); // ACM conversion failed?
903 DSOUND_load_buffer_result = -1;
904 goto DSOUND_load_buffer_done;
907 final_sound_size = convert_len;
909 // Set up the WAVEFORMATEX structure to have the right PCM characteristics
910 WaveFormat.wFormatTag = WAVE_FORMAT_PCM;
911 WaveFormat.nChannels = (unsigned short)si->n_channels;
912 WaveFormat.nSamplesPerSec = si->sample_rate;
913 WaveFormat.wBitsPerSample = 8;
914 WaveFormat.cbSize = 0;
915 WaveFormat.nBlockAlign = (unsigned short)(( WaveFormat.nChannels * WaveFormat.wBitsPerSample ) / 8);
916 WaveFormat.nAvgBytesPerSec = WaveFormat.nBlockAlign * WaveFormat.nSamplesPerSec;
918 nprintf(( "Sound", "SOUND ==> Coverted sound from ADPCM to PCM successfully\n" ));
922 nprintf(( "Sound", "Unsupported sound encoding\n" ));
923 DSOUND_load_buffer_result = -1;
924 goto DSOUND_load_buffer_done;
928 WaveFormat.wFormatTag = WAVE_FORMAT_PCM; // DirectSound only used PCM wave files
930 // Set up a DirectSound buffer
931 ZeroMemory(&BufferDesc, sizeof(BufferDesc));
932 BufferDesc.dwSize = sizeof(BufferDesc);
933 BufferDesc.dwBufferBytes = final_sound_size;
934 BufferDesc.lpwfxFormat = &WaveFormat;
936 // check if DirectSound3D is enabled and the sound is flagged for 3D
937 if ((ds_using_ds3d()) && (flags & DS_USE_DS3D)) {
938 // if (ds_using_ds3d()) {
939 BufferDesc.dwFlags = DSBCAPS_STATIC | DSBCAPS_GETCURRENTPOSITION2 | DSBCAPS_CTRLVOLUME | DSBCAPS_CTRL3D | DSBCAPS_MUTE3DATMAXDISTANCE;
941 BufferDesc.dwFlags = DSBCAPS_STATIC | DSBCAPS_GETCURRENTPOSITION2 | DSBCAPS_CTRLVOLUME | DSBCAPS_LOCSOFTWARE;
944 // Create a new software buffer using the settings for this wave
945 // All sounds are required to have a software buffer
948 nprintf(("Sound","SOUND ==> No more software secondary buffers available\n"));
951 DSReturn = pDirectSound->CreateSoundBuffer(&BufferDesc, &ds_software_buffers[*sid].pdsb, NULL );
953 if ( DSReturn == DS_OK && ds_software_buffers[*sid].pdsb != NULL ) {
955 ds_software_buffers[*sid].desc = BufferDesc;
956 ds_software_buffers[*sid].wfx = *BufferDesc.lpwfxFormat;
958 // Lock the buffer and copy in the data
959 if ((ds_software_buffers[*sid].pdsb)->Lock(0, final_sound_size, (void**)(&pData), &DataSize, (void**)(&pData2), &DataSize2, 0) == DS_OK) {
961 if ( convert_buffer )
962 memcpy(pData, convert_buffer, final_sound_size); // use converted data (PCM format)
964 memcpy(pData, si->data, final_sound_size);
966 (ds_software_buffers[*sid].pdsb)->Unlock(pData, DataSize, 0, 0);
968 DSOUND_load_buffer_result = 0;
970 // update ram used for sound
971 Snd_sram += final_sound_size;
972 *final_size = final_sound_size;
975 nprintf(("Sound","SOUND => fatal error in DSOUND_load_buffer\n"));
977 DSOUND_load_buffer_result = -1;
980 DSOUND_load_buffer_done:
981 if ( convert_buffer )
982 free( convert_buffer );
983 return DSOUND_load_buffer_result;
987 // ---------------------------------------------------------------------------------------
988 // ds_init_channels()
990 // init the Channels[] array
992 void ds_init_channels()
995 // STUB_FUNCTION; // not needed with openal (CM)
1000 // detect how many channels we can support
1002 ds_get_soundcard_caps(&caps);
1004 // caps.dwSize = sizeof(DSCAPS);
1005 // pDirectSound->GetCaps(&caps);
1007 // minimum 16 channels
1008 MAX_CHANNELS = caps.dwMaxHwMixingStaticBuffers;
1009 int dbg_channels = MAX_CHANNELS;
1010 if (MAX_CHANNELS < 16) {
1014 // allocate the channels array
1015 Channels = (channel*) malloc(sizeof(channel) * MAX_CHANNELS);
1016 if (Channels == NULL) {
1017 Error(LOCATION, "Unable to allocate %d bytes for %d audio channels.", sizeof(channel) * MAX_CHANNELS, MAX_CHANNELS);
1020 // init the channels
1021 for ( i = 0; i < MAX_CHANNELS; i++ ) {
1022 Channels[i].pdsb = NULL;
1023 Channels[i].pds3db = NULL;
1024 Channels[i].vol = 0;
1027 mprintf(("** MAX_CHANNELS set to %d. DS reported %d.\n", MAX_CHANNELS, dbg_channels));
1031 // ---------------------------------------------------------------------------------------
1032 // ds_init_software_buffers()
1034 // init the software buffers
1036 void ds_init_software_buffers()
1039 // STUB_FUNCTION; // not needed with openal (CM)
1044 for ( i = 0; i < MAX_DS_SOFTWARE_BUFFERS; i++ ) {
1045 ds_software_buffers[i].pdsb = NULL;
1050 // ---------------------------------------------------------------------------------------
1051 // ds_init_hardware_buffers()
1053 // init the hardware buffers
1055 void ds_init_hardware_buffers()
1058 // STUB_FUNCTION; // not needed with openal (CM)
1063 for ( i = 0; i < MAX_DS_HARDWARE_BUFFERS; i++ ) {
1064 ds_hardware_buffers[i].pdsb = NULL;
1069 // ---------------------------------------------------------------------------------------
1070 // ds_init_buffers()
1072 // init the both the software and hardware buffers
1074 void ds_init_buffers()
1076 ds_init_software_buffers();
1077 ds_init_hardware_buffers();
1080 // Get the current soundcard capabilities
1082 void ds_get_soundcard_caps(DSCAPS *dscaps)
1085 int n_hbuffers, hram;
1087 dscaps->dwSize = sizeof(DSCAPS);
1089 hr = pDirectSound->GetCaps(dscaps);
1091 nprintf(("Sound","SOUND ==> DirectSound GetCaps() failed with code %s\n.",get_DSERR_text(hr) ));
1095 n_hbuffers = dscaps->dwMaxHwMixingStaticBuffers;
1096 hram = dscaps->dwTotalHwMemBytes;
1098 if ( !(dscaps->dwFlags & DSCAPS_CERTIFIED) ) {
1099 nprintf(("Sound","SOUND ==> Warning: audio driver is not Microsoft certified.\n"));
1103 // ---------------------------------------------------------------------------------------
1106 // init the both the software and hardware buffers
1108 void ds_show_caps(DSCAPS *dscaps)
1110 nprintf(("Sound", "SOUND => Soundcard Capabilities:\n"));
1111 nprintf(("Sound", "================================\n"));
1112 nprintf(("Sound", "Number of primary buffers: %d\n", dscaps->dwPrimaryBuffers ));
1113 nprintf(("Sound", "Number of total hw mixing buffers: %d\n", dscaps->dwMaxHwMixingAllBuffers ));
1114 nprintf(("Sound", "Number of total hw mixing static buffers: %d\n", dscaps->dwMaxHwMixingStaticBuffers ));
1115 nprintf(("Sound", "Number of total hw mixing streaming buffers: %d\n", dscaps->dwMaxHwMixingStreamingBuffers ));
1116 nprintf(("Sound", "Number of free hw mixing buffers: %d\n", dscaps->dwFreeHwMixingAllBuffers ));
1117 nprintf(("Sound", "Number of free hw mixing static buffers: %d\n", dscaps->dwFreeHwMixingStaticBuffers ));
1118 nprintf(("Sound", "Number of free hw mixing streaming buffers: %d\n", dscaps->dwFreeHwMixingStreamingBuffers ));
1119 nprintf(("Sound", "Number of hw 3D buffers: %d\n", dscaps->dwMaxHw3DAllBuffers ));
1120 nprintf(("Sound", "Number of hw 3D static buffers: %d\n", dscaps->dwMaxHw3DStaticBuffers ));
1121 nprintf(("Sound", "Number of hw 3D streaming buffers: %d\n", dscaps->dwMaxHw3DStreamingBuffers ));
1122 nprintf(("Sound", "Number of free hw 3D buffers: %d\n", dscaps->dwFreeHw3DAllBuffers ));
1123 nprintf(("Sound", "Number of free hw static 3D buffers: %d\n", dscaps->dwFreeHw3DStaticBuffers ));
1124 nprintf(("Sound", "Number of free hw streaming 3D buffers: %d\n", dscaps->dwFreeHw3DStreamingBuffers ));
1125 nprintf(("Sound", "Number of total hw bytes: %d\n", dscaps->dwTotalHwMemBytes ));
1126 nprintf(("Sound", "Number of free hw bytes: %d\n", dscaps->dwFreeHwMemBytes ));
1127 nprintf(("Sound", "================================\n"));
1131 // Fill in the waveformat struct with the primary buffer characteristics.
1132 void ds_get_primary_format(WAVEFORMATEX *wfx)
1137 // Set 16 bit / 22KHz / mono
1138 wfx->wFormatTag = WAVE_FORMAT_PCM;
1140 wfx->nSamplesPerSec = 22050;
1141 wfx->wBitsPerSample = 16;
1143 wfx->nBlockAlign = (unsigned short)(wfx->nChannels * (wfx->wBitsPerSample / 8));
1144 wfx->nAvgBytesPerSec = wfx->nBlockAlign * wfx->nSamplesPerSec;
1147 // obtain the function pointers from the dsound.dll
1148 void ds_dll_get_functions()
1150 pfn_DirectSoundCreate = (HRESULT(__stdcall *)(LPGUID lpGuid, LPDIRECTSOUND *ppDS, IUnknown FAR *pUnkOuter))GetProcAddress(Ds_dll_handle,"DirectSoundCreate");
1151 pfn_DirectSoundCaptureCreate = (HRESULT(__stdcall *)(LPGUID lpGuid, LPDIRECTSOUNDCAPTURE *lplpDSC, IUnknown FAR *pUnkOuter))GetProcAddress(Ds_dll_handle,"DirectSoundCaptureCreate");
1155 // Load the dsound.dll, and get funtion pointers
1156 // exit: 0 -> dll loaded successfully
1157 // !0 -> dll could not be loaded
1163 if ( !Ds_dll_loaded ) {
1164 Ds_dll_handle = LoadLibrary("dsound.dll");
1165 if ( !Ds_dll_handle ) {
1168 ds_dll_get_functions();
1181 HINSTANCE a3d_handle;
1184 a3d_handle = LoadLibrary("a3d.dll");
1188 FreeLibrary(a3d_handle);
1192 Ds_must_call_couninitialize = 1;
1194 hr = CoCreateInstance(CLSID_A3d_Def, NULL, CLSCTX_INPROC_SERVER, IID_IDirectSound, (void**)&pDirectSound);
1199 Assert(pDirectSound != NULL);
1200 hr = pDirectSound->QueryInterface(IID_IA3d2_Def, (void**)&pIA3d2);
1205 A3DCAPS_SOFTWARE swCaps;
1207 // Get Dll Software CAP to get DLL version number
1208 ZeroMemory(&swCaps,sizeof(swCaps));
1210 swCaps.dwSize = sizeof(swCaps);
1211 pIA3d2->GetSoftwareCaps(&swCaps);
1213 // Compare version from a3d.dll to header version only return A3D_OK if dll version >= to header version
1214 if (swCaps.dwVersion < A3D_CURRENT_VERSION) {
1215 pDirectSound->Release();
1216 pDirectSound = NULL;
1221 // verify this is authentic A3D
1222 int aureal_verified;
1223 aureal_verified = VerifyAurealA3D();
1225 if (aureal_verified == FALSE) {
1226 // This is fake A3D!!! Ignore
1227 pDirectSound->Release();
1228 pDirectSound = NULL;
1232 // Register our version for backwards compatibility with newer A3d.dll
1233 pIA3d2->RegisterVersion(A3D_CURRENT_VERSION);
1235 hr = pDirectSound->Initialize(NULL);
1237 pDirectSound->Release();
1238 pDirectSound = NULL;
1242 pIA3d2->SetResourceManagerMode(A3D_RESOURCE_MODE_DYNAMIC_LOOPERS);
1248 // Initialize the property set interface.
1250 // returns: 0 if successful, otherwise -1. If successful, the global pPropertySet will
1251 // set to a non-NULL value.
1253 int ds_init_property_set()
1260 // Create the secondary buffer required for EAX initialization
1262 wf.wFormatTag = WAVE_FORMAT_PCM;
1264 wf.nSamplesPerSec = 22050;
1265 wf.wBitsPerSample = 16;
1267 wf.nBlockAlign = (unsigned short)(wf.nChannels * (wf.wBitsPerSample / 8));
1268 wf.nAvgBytesPerSec = wf.nBlockAlign * wf.nSamplesPerSec;
1271 ZeroMemory(&dsbd, sizeof(dsbd));
1272 dsbd.dwSize = sizeof(dsbd);
1273 dsbd.dwFlags = DSBCAPS_CTRLDEFAULT | DSBCAPS_GETCURRENTPOSITION2 | DSBCAPS_STATIC | DSBCAPS_CTRL3D | DSBCAPS_MUTE3DATMAXDISTANCE;
1274 dsbd.dwBufferBytes = 3 * wf.nAvgBytesPerSec;
1275 dsbd.lpwfxFormat = &wf;
1277 // Create a new buffer using the settings for this wave
1278 hr = pDirectSound->CreateSoundBuffer(&dsbd, &Ds_property_set_pdsb, NULL);
1280 pPropertySet = NULL;
1284 // Get the 3D interface from the secondary buffer, which is used to query the EAX interface
1285 hr = Ds_property_set_pdsb->QueryInterface(IID_IDirectSound3DBuffer, (void**)&Ds_property_set_pds3db);
1287 Ds_property_set_pds3db = NULL;
1291 Assert(Ds_property_set_pds3db != NULL);
1292 hr = Ds_property_set_pds3db->QueryInterface(IID_IKsPropertySet, (void**)&pPropertySet);
1293 if ((FAILED(hr)) || (pPropertySet == NULL)) {
1301 // ---------------------------------------------------------------------------------------
1304 // returns: -1 => init failed
1305 // 0 => init success
1306 int ds_init(int use_a3d, int use_eax)
1309 // NOTE: A3D and EAX are unused in OpenAL
1310 const ALubyte *initStr = (const ALubyte *)"\'( (sampling-rate 22050 ))";
1311 int attr[] = { ALC_FREQUENCY, 22050, ALC_SYNC, AL_FALSE, 0 };
1317 nprintf(( "Sound", "SOUND ==> Initializing DirectSound...\n" ));
1320 ds_sound_device = alcOpenDevice (initStr);
1322 // Create Sound Device
1323 ds_sound_context = alcCreateContext (ds_sound_device, attr);
1324 alcMakeContextCurrent (ds_sound_context);
1326 if (alGetError() != AL_NO_ERROR) {
1327 nprintf(("Sound", "SOUND ==> Cannot initiate OpenAL\n"));
1331 // Get the primary buffer format
1332 //ds_get_primary_format(&wave_format);
1334 // Initialize DirectSound3D. Since software performance of DirectSound3D is unacceptably
1335 // slow, we require the voice manger (a DirectSound extension) to be present. The
1336 // exception is when A3D is being used, since A3D has a resource manager built in.
1337 if (Ds_use_ds3d && ds3d_init(0) != 0)
1340 ds_build_vol_lookup();
1346 WAVEFORMATEX wave_format;
1347 DSBUFFERDESC BufferDesc;
1349 nprintf(( "Sound", "SOUND ==> Initializing DirectSound...\n" ));
1351 hwnd = (HWND)os_get_window();
1352 if ( hwnd == NULL ) {
1353 nprintf(( "Sound", "SOUND ==> No window handle, so no sound...\n" ));
1357 if ( ds_dll_load() == -1 ) {
1361 pDirectSound = NULL;
1363 Ds_use_a3d = use_a3d;
1364 Ds_use_eax = use_eax;
1366 if (Ds_use_a3d || Ds_use_eax) {
1370 if (Ds_use_a3d && Ds_use_eax) {
1375 // If we want A3D, ensure a3d.dll exists
1376 if (Ds_use_a3d == 1) {
1377 if (ds_init_a3d() != 0) {
1384 if (Ds_use_a3d == 0) {
1385 if (!pfn_DirectSoundCreate) {
1386 nprintf(( "Sound", "SOUND ==> Could not get DirectSoundCreate function pointer\n" ));
1390 hr = pfn_DirectSoundCreate(NULL, &pDirectSound, NULL);
1396 // Set up DirectSound for exclusive mode, so we can change the primary buffer if we want to.
1397 hr = pDirectSound->SetCooperativeLevel(hwnd, DSSCL_EXCLUSIVE);
1399 nprintf(("Sound","SOUND ==> DirectSound pDirectSound->SetCooperativeLevel failed with code %s\n.",get_DSERR_text(hr) ));
1400 pDirectSound = NULL;
1404 // Create the primary buffer
1405 ZeroMemory(&BufferDesc, sizeof(BufferDesc));
1406 BufferDesc.dwSize = sizeof(BufferDesc);
1408 ds_get_soundcard_caps(&Soundcard_caps);
1411 BufferDesc.dwFlags = DSBCAPS_PRIMARYBUFFER | DSBCAPS_CTRL3D;
1413 hr = pDirectSound->CreateSoundBuffer(&BufferDesc, &pPrimaryBuffer, 0);
1415 nprintf(("Sound","SOUND ==> Primary Buffer create failed with DSBCAPS_CTRL3D property... disabling DirectSound3D\n"));
1420 nprintf(("Sound","SOUND ==> Primary Buffer created with DirectSound3D enabled\n"));
1424 // If not using DirectSound3D, then create a normal primary buffer
1425 if (Ds_use_ds3d == 0) {
1426 BufferDesc.dwFlags = DSBCAPS_PRIMARYBUFFER;
1427 hr = pDirectSound->CreateSoundBuffer(&BufferDesc, &pPrimaryBuffer, 0);
1429 nprintf(("Sound","SOUND ==> Primary Buffer create failed with error: %s\n",get_DSERR_text(hr) ));
1430 pDirectSound = NULL;
1434 nprintf(("Sound","SOUND ==> Primary Buffer created with without DirectSound3D enabled\n"));
1438 // Get the primary buffer format
1439 ds_get_primary_format(&wave_format);
1441 hr = pPrimaryBuffer->SetFormat(&wave_format);
1443 nprintf(("Sound","SOUND ==> pPrimaryBuffer->SetFormat() failed with code %s\n",get_DSERR_text(hr) ));
1446 pPrimaryBuffer->GetFormat(&wave_format, sizeof(wave_format), NULL);
1447 nprintf(("Sound","SOUND ==> Primary Buffer forced to: rate: %d Hz bits: %d n_channels: %d\n",
1448 wave_format.nSamplesPerSec, wave_format.wBitsPerSample, wave_format.nChannels));
1450 // start the primary buffer playing. This will reduce sound latency when playing a sound
1451 // if no other sounds are playing.
1452 hr = pPrimaryBuffer->Play(0, 0, DSBPLAY_LOOPING);
1454 nprintf(("Sound","SOUND ==> pPrimaryBuffer->Play() failed with code %s\n",get_DSERR_text(hr) ));
1457 // Initialize DirectSound3D. Since software performance of DirectSound3D is unacceptably
1458 // slow, we require the voice manger (a DirectSound extension) to be present. The
1459 // exception is when A3D is being used, since A3D has a resource manager built in.
1461 int vm_required = 1; // voice manager
1462 if (Ds_use_a3d == 1) {
1466 if (ds3d_init(vm_required) != 0) {
1472 if (Ds_use_eax == 1) {
1473 ds_init_property_set();
1474 if (ds_eax_init() != 0) {
1479 ds_build_vol_lookup();
1483 ds_show_caps(&Soundcard_caps);
1489 // ---------------------------------------------------------------------------------------
1492 // returns the text equivalent for the a DirectSound DSERR_ code
1494 char *get_DSERR_text(int DSResult)
1498 return "Linux rocks";
1500 switch( DSResult ) {
1506 case DSERR_ALLOCATED:
1507 return "DSERR_ALLOCATED";
1510 case DSERR_ALREADYINITIALIZED:
1511 return "DSERR_ALREADYINITIALIZED";
1514 case DSERR_BADFORMAT:
1515 return "DSERR_BADFORMAT";
1518 case DSERR_BUFFERLOST:
1519 return "DSERR_BUFFERLOST";
1522 case DSERR_CONTROLUNAVAIL:
1523 return "DSERR_CONTROLUNAVAIL";
1527 return "DSERR_GENERIC";
1530 case DSERR_INVALIDCALL:
1531 return "DSERR_INVALIDCALL";
1534 case DSERR_INVALIDPARAM:
1535 return "DSERR_INVALIDPARAM";
1538 case DSERR_NOAGGREGATION:
1539 return "DSERR_NOAGGREGATION";
1542 case DSERR_NODRIVER:
1543 return "DSERR_NODRIVER";
1546 case DSERR_OUTOFMEMORY:
1547 return "DSERR_OUTOFMEMORY";
1550 case DSERR_OTHERAPPHASPRIO:
1551 return "DSERR_OTHERAPPHASPRIO";
1554 case DSERR_PRIOLEVELNEEDED:
1555 return "DSERR_PRIOLEVELNEEDED";
1558 case DSERR_UNINITIALIZED:
1559 return "DSERR_UNINITIALIZED";
1562 case DSERR_UNSUPPORTED:
1563 return "DSERR_UNSUPPORTED";
1574 // ---------------------------------------------------------------------------------------
1575 // ds_close_channel()
1577 // Free a single channel
1579 void ds_close_channel(int i)
1586 // If a 3D interface exists, free it
1587 if ( Channels[i].pds3db != NULL ) {
1590 Channels[i].pds3db = NULL;
1593 while(++attempts < 10) {
1594 hr = Channels[i].pds3db->Release();
1595 if ( hr == DS_OK ) {
1598 // nprintf(("Sound", "SOUND ==> Channels[channel].pds3db->Release() failed with return value %s\n", get_DSERR_text(second_hr) ));
1602 Channels[i].pds3db = NULL;
1606 if ( Channels[i].pdsb != NULL ) {
1607 // If a 2D interface exists, free it
1608 if ( Channels[i].pdsb != NULL ) {
1610 while(++attempts < 10) {
1611 hr = Channels[i].pdsb->Release();
1612 if ( hr == DS_OK ) {
1615 nprintf(("Sound", "SOUND ==> Channels[channel].pdsb->Release() failed with return value %s\n", get_DSERR_text(hr) ));
1620 Channels[i].pdsb = NULL;
1627 // ---------------------------------------------------------------------------------------
1628 // ds_close_all_channels()
1630 // Free all the channel buffers
1632 void ds_close_all_channels()
1636 for (i = 0; i < MAX_CHANNELS; i++) {
1637 ds_close_channel(i);
1641 // ---------------------------------------------------------------------------------------
1642 // ds_unload_buffer()
1645 void ds_unload_buffer(int sid, int hid)
1653 if ( ds_software_buffers[sid].pdsb != NULL ) {
1654 hr = ds_software_buffers[sid].pdsb->Release();
1655 if ( hr != DS_OK ) {
1657 nprintf(("Sound", "SOUND ==> ds_software_buffers[sid]->Release() failed with return value %s\n", get_DSERR_text(hr) ));
1659 ds_software_buffers[sid].pdsb = NULL;
1664 if ( ds_hardware_buffers[hid].pdsb != NULL ) {
1665 hr = ds_hardware_buffers[hid].pdsb->Release();
1666 if ( hr != DS_OK ) {
1668 nprintf(("Sound", "SOUND ==> ds_hardware_buffers[hid]->Release() failed with return value %s\n", get_DSERR_text(hr) ));
1670 ds_hardware_buffers[hid].pdsb = NULL;
1676 // ---------------------------------------------------------------------------------------
1677 // ds_close_software_buffers()
1680 void ds_close_software_buffers()
1688 for (i = 0; i < MAX_DS_SOFTWARE_BUFFERS; i++) {
1689 if ( ds_software_buffers[i].pdsb != NULL ) {
1690 hr = ds_software_buffers[i].pdsb->Release();
1691 if ( hr != DS_OK ) {
1693 nprintf(("Sound", "SOUND ==> ds_software_buffers[i]->Release() failed with return value %s\n", get_DSERR_text(hr) ));
1695 ds_software_buffers[i].pdsb = NULL;
1701 // ---------------------------------------------------------------------------------------
1702 // ds_close_hardware_buffers()
1705 void ds_close_hardware_buffers()
1713 for (i = 0; i < MAX_DS_HARDWARE_BUFFERS; i++) {
1714 if ( ds_hardware_buffers[i].pdsb != NULL ) {
1715 hr = ds_hardware_buffers[i].pdsb->Release();
1716 if ( hr != DS_OK ) {
1718 nprintf(("Sound", "SOUND ==> ds_hardware_buffers[i]->Release() failed with return value %s\n", get_DSERR_text(hr) ));
1720 ds_hardware_buffers[i].pdsb = NULL;
1726 // ---------------------------------------------------------------------------------------
1727 // ds_close_buffers()
1729 // Free the channel buffers
1731 void ds_close_buffers()
1733 ds_close_software_buffers();
1734 ds_close_hardware_buffers();
1737 // ---------------------------------------------------------------------------------------
1740 // Close the DirectSound system
1744 ds_close_all_channels();
1750 if (pPropertySet != NULL) {
1751 pPropertySet->Release();
1752 pPropertySet = NULL;
1755 if (Ds_property_set_pdsb != NULL) {
1756 Ds_property_set_pdsb->Release();
1757 Ds_property_set_pdsb = NULL;
1760 if (Ds_property_set_pds3db != NULL) {
1761 Ds_property_set_pds3db->Release();
1762 Ds_property_set_pds3db = NULL;
1765 if (pPrimaryBuffer) {
1766 pPrimaryBuffer->Release();
1767 pPrimaryBuffer = NULL;
1776 pDirectSound->Release();
1777 pDirectSound = NULL;
1780 if ( Ds_dll_loaded ) {
1781 FreeLibrary(Ds_dll_handle);
1785 if (Ds_must_call_couninitialize == 1) {
1789 // free the Channels[] array, since it was dynamically allocated
1795 // ---------------------------------------------------------------------------------------
1796 // ds_get_3d_interface()
1798 // Get the 3d interface for a secondary buffer.
1800 // If the secondary buffer wasn't created with a DSBCAPS_CTRL3D flag, then no 3d interface
1804 void ds_get_3d_interface(LPDIRECTSOUNDBUFFER pdsb, LPDIRECTSOUND3DBUFFER *ppds3db)
1809 dsbc.dwSize = sizeof(dsbc);
1810 DSResult = pdsb->GetCaps(&dsbc);
1811 if ( DSResult == DS_OK && dsbc.dwFlags & DSBCAPS_CTRL3D ) {
1812 DSResult = pdsb->QueryInterface( IID_IDirectSound3DBuffer, (void**)ppds3db );
1813 if ( DSResult != DS_OK ) {
1814 nprintf(("SOUND","Could not obtain 3D interface for hardware buffer: %s\n", get_DSERR_text(DSResult) ));
1821 // ---------------------------------------------------------------------------------------
1822 // ds_get_free_channel()
1824 // Find a free channel to play a sound on. If no free channels exists, free up one based
1825 // on volume levels.
1827 // input: new_volume => volume in DS units for sound to play at
1828 // snd_id => which kind of sound to play
1829 // priority => DS_MUST_PLAY
1834 // returns: channel number to play sound on
1835 // -1 if no channel could be found
1837 // NOTE: snd_id is needed since we limit the number of concurrent samples
1840 #define DS_MAX_SOUND_INSTANCES 2
1842 int ds_get_free_channel(int new_volume, int snd_id, int priority)
1848 int i, first_free_channel, limit;
1849 int lowest_vol = 0, lowest_vol_index = -1;
1850 int instance_count; // number of instances of sound already playing
1851 int lowest_instance_vol, lowest_instance_vol_index;
1852 unsigned long status;
1857 lowest_instance_vol = 99;
1858 lowest_instance_vol_index = -1;
1859 first_free_channel = -1;
1861 // Look for a channel to use to play this sample
1862 for ( i = 0; i < MAX_CHANNELS; i++ ) {
1864 if ( chp->pdsb == NULL ) {
1865 if ( first_free_channel == -1 )
1866 first_free_channel = i;
1870 hr = chp->pdsb->GetStatus(&status);
1871 if ( hr != DS_OK ) {
1872 nprintf(("Sound", "SOUND ==> GetStatus failed with return value %s\n", get_DSERR_text(hr) ));
1875 if ( !(status & DSBSTATUS_PLAYING) ) {
1876 if ( first_free_channel == -1 )
1877 first_free_channel = i;
1878 ds_close_channel(i);
1882 if ( chp->snd_id == snd_id ) {
1884 if ( chp->vol < lowest_instance_vol && chp->looping == FALSE ) {
1885 lowest_instance_vol = chp->vol;
1886 lowest_instance_vol_index = i;
1890 if ( chp->vol < lowest_vol && chp->looping == FALSE ) {
1891 lowest_vol_index = i;
1892 lowest_vol = chp->vol;
1897 // determine the limit of concurrent instances of this sound
1908 case DS_LIMIT_THREE:
1918 // If we've exceeded the limit, then maybe stop the duplicate if it is lower volume
1919 if ( instance_count >= limit ) {
1920 // If there is a lower volume duplicate, stop it.... otherwise, don't play the sound
1921 if ( lowest_instance_vol_index >= 0 && (Channels[lowest_instance_vol_index].vol <= new_volume) ) {
1922 ds_close_channel(lowest_instance_vol_index);
1923 first_free_channel = lowest_instance_vol_index;
1925 first_free_channel = -1;
1928 // there is no limit barrier to play the sound, so see if we've ran out of channels
1929 if ( first_free_channel == -1 ) {
1930 // stop the lowest volume instance to play our sound if priority demands it
1931 if ( lowest_vol_index != -1 && priority == DS_MUST_PLAY ) {
1932 // Check if the lowest volume playing is less than the volume of the requested sound.
1933 // If so, then we are going to trash the lowest volume sound.
1934 if ( Channels[lowest_vol_index].vol <= new_volume ) {
1935 ds_close_channel(lowest_vol_index);
1936 first_free_channel = lowest_vol_index;
1942 return first_free_channel;
1947 // ---------------------------------------------------------------------------------------
1950 // Find a free channel to play a sound on. If no free channels exists, free up one based
1951 // on volume levels.
1953 // returns: 0 => dup was successful
1954 // -1 => dup failed (Channels[channel].pdsb will be NULL)
1957 int ds_channel_dup(LPDIRECTSOUNDBUFFER pdsb, int channel, int use_ds3d)
1961 // Duplicate the master buffer into a channel buffer.
1962 DSResult = pDirectSound->DuplicateSoundBuffer(pdsb, &Channels[channel].pdsb );
1963 if ( DSResult != DS_OK ) {
1964 nprintf(("Sound", "SOUND ==> DuplicateSoundBuffer failed with return value %s\n", get_DSERR_text(DSResult) ));
1965 Channels[channel].pdsb = NULL;
1969 // get the 3d interface for the buffer if it exists
1971 if (Channels[channel].pds3db == NULL) {
1972 ds_get_3d_interface(Channels[channel].pdsb, &Channels[channel].pds3db);
1980 // ---------------------------------------------------------------------------------------
1981 // ds_restore_buffer()
1984 void ds_restore_buffer(LPDIRECTSOUNDBUFFER pdsb)
1988 Int3(); // get Alan, he wants to see this
1989 hr = pdsb->Restore();
1990 if ( hr != DS_OK ) {
1991 nprintf(("Sound", "Sound ==> Lost a buffer, tried restoring but got %s\n", get_DSERR_text(hr) ));
1996 // Create a direct sound buffer in software, without locking any data in
1997 int ds_create_buffer(int frequency, int bits_per_sample, int nchannels, int nseconds)
2008 if (!ds_initialized) {
2014 nprintf(("Sound","SOUND ==> No more software secondary buffers available\n"));
2018 // Set up buffer format
2019 wfx.wFormatTag = WAVE_FORMAT_PCM;
2020 wfx.nChannels = (unsigned short)nchannels;
2021 wfx.nSamplesPerSec = frequency;
2022 wfx.wBitsPerSample = (unsigned short)bits_per_sample;
2024 wfx.nBlockAlign = (unsigned short)(wfx.nChannels * (wfx.wBitsPerSample / 8));
2025 wfx.nAvgBytesPerSec = wfx.nBlockAlign * wfx.nSamplesPerSec;
2027 memset(&dsbd, 0, sizeof(DSBUFFERDESC));
2028 dsbd.dwSize = sizeof(DSBUFFERDESC);
2029 dsbd.dwBufferBytes = wfx.nAvgBytesPerSec * nseconds;
2030 dsbd.lpwfxFormat = &wfx;
2031 dsbd.dwFlags = DSBCAPS_STATIC | DSBCAPS_GETCURRENTPOSITION2 | DSBCAPS_CTRLDEFAULT | DSBCAPS_LOCSOFTWARE;
2033 dsrval = pDirectSound->CreateSoundBuffer(&dsbd, &ds_software_buffers[sid].pdsb, NULL);
2034 if ( dsrval != DS_OK ) {
2038 ds_software_buffers[sid].desc = dsbd;
2043 // Lock data into an existing buffer
2044 int ds_lock_data(int sid, unsigned char *data, int size)
2050 LPDIRECTSOUNDBUFFER pdsb;
2052 void *buffer_data, *buffer_data2;
2053 DWORD buffer_size, buffer_size2;
2056 pdsb = ds_software_buffers[sid].pdsb;
2058 memset(&caps, 0, sizeof(DSBCAPS));
2059 caps.dwSize = sizeof(DSBCAPS);
2060 dsrval = pdsb->GetCaps(&caps);
2061 if ( dsrval != DS_OK ) {
2065 pdsb->SetCurrentPosition(0);
2067 // lock the entire buffer
2068 dsrval = pdsb->Lock(0, caps.dwBufferBytes, &buffer_data, &buffer_size, &buffer_data2, &buffer_size2, 0 );
2069 if ( dsrval != DS_OK ) {
2073 // first clear it out with silence
2074 memset(buffer_data, 0x80, buffer_size);
2075 memcpy(buffer_data, data, size);
2077 dsrval = pdsb->Unlock(buffer_data, buffer_size, 0, 0);
2078 if ( dsrval != DS_OK ) {
2086 // Stop a buffer from playing directly
2087 void ds_stop_easy(int sid)
2093 LPDIRECTSOUNDBUFFER pdsb;
2096 pdsb = ds_software_buffers[sid].pdsb;
2097 dsrval = pdsb->Stop();
2101 // Play a sound without the usual baggage (used for playing back real-time voice)
2104 // sid => software id of sound
2105 // volume => volume of sound effect in DirectSound units
2106 int ds_play_easy(int sid, int volume)
2112 LPDIRECTSOUNDBUFFER pdsb;
2115 pdsb = ds_software_buffers[sid].pdsb;
2117 pdsb->SetVolume(volume);
2118 dsrval=pdsb->Play(0, 0, 0);
2119 if ( dsrval != DS_OK ) {
2127 //extern void HUD_add_to_scrollback(char *text, int source);
2128 //extern void HUD_printf(char *format, ...);
2130 // ---------------------------------------------------------------------------------------
2131 // Play a DirectSound secondary buffer.
2135 // sid => software id of sound
2136 // hid => hardware id of sound ( -1 if not in hardware )
2137 // snd_id => what kind of sound this is
2138 // priority => DS_MUST_PLAY
2142 // volume => volume of sound effect in DirectSound units
2143 // pan => pan of sound in DirectSound units
2144 // looping => whether the sound effect is looping or not
2146 // returns: -1 => sound effect could not be started
2147 // >=0 => sig for sound effect successfully started
2149 int ds_play(int sid, int hid, int snd_id, int priority, int volume, int pan, int looping, bool is_voice_msg)
2155 alSourcei (hid, AL_BUFFER, sid);
2156 alSourcei (hid, AL_LOOPING, (looping) ? AL_TRUE : AL_FALSE);
2157 alSourcei (hid, AL_SOURCE_RELATIVE, AL_TRUE);
2159 // set pan, volume, etc
2163 nprintf(("Sound","SOUND ==> Playing sound %d looping\n", sid));
2164 } else nprintf(("Sound", "SOUND ==> Playing sound %d not looping\n", sid));
2166 int i = alGetError();
2167 if(i != AL_NO_ERROR) {
2168 printf("%s|||error!\n", alGetString(i));
2177 if (!ds_initialized)
2180 channel = ds_get_free_channel(volume, snd_id, priority);
2183 if ( Channels[channel].pdsb != NULL ) {
2187 // First check if the sound is in hardware, and try to duplicate from there
2190 if ( ds_channel_dup(ds_hardware_buffers[hid].pdsb, channel, 0) == 0 ) {
2191 // nprintf(("Sound", "SOUND ==> Played sound in hardware..\n"));
2195 // Channel will be NULL if hardware dup failed, or there was no hardware dup attempted
2196 if ( Channels[channel].pdsb == NULL ) {
2197 if ( ds_channel_dup(ds_software_buffers[sid].pdsb, channel, 0) == 0 ) {
2198 // nprintf(("Sound", "SOUND ==> Played sound in software..\n"));
2202 if ( Channels[channel].pdsb == NULL ) {
2206 if ( ds_using_ds3d() ) {
2207 if ( ds_is_3d_buffer(Channels[channel].pdsb) ) {
2208 if (Channels[channel].pds3db == NULL) {
2209 ds_get_3d_interface(Channels[channel].pdsb, &Channels[channel].pds3db);
2211 if ( Channels[channel].pds3db ) {
2212 Channels[channel].pds3db->SetMode(DS3DMODE_DISABLE,DS3D_IMMEDIATE);
2218 Channels[channel].vol = volume;
2219 Channels[channel].looping = looping;
2220 Channels[channel].priority = priority;
2221 Channels[channel].pdsb->SetPan(pan);
2222 Channels[channel].pdsb->SetVolume(volume);
2223 Channels[channel].is_voice_msg = is_voice_msg;
2227 ds_flags |= DSBPLAY_LOOPING;
2229 DSResult = Channels[channel].pdsb->Play(0, 0, ds_flags );
2232 if (Stop_logging_sounds == false) {
2234 sprintf(buf, "channel %d, address: %x, ds_flags: %d", channel, Channels[channel].pdsb, ds_flags);
2235 HUD_add_to_scrollback(buf, 3);
2239 if ( DSResult == DSERR_BUFFERLOST ) {
2240 ds_restore_buffer(Channels[channel].pdsb);
2241 DSResult = Channels[channel].pdsb->Play(0, 0, ds_flags );
2244 if ( DSResult != DS_OK ) {
2245 nprintf(("Sound", "Sound ==> Play failed with return value %s\n", get_DSERR_text(DSResult) ));
2250 // nprintf(( "Sound", "SOUND ==> Not playing sound requested at volume %.2f\n", ds_get_percentage_vol(volume) ));
2254 Channels[channel].snd_id = snd_id;
2255 Channels[channel].sig = channel_next_sig++;
2256 if (channel_next_sig < 0 ) {
2257 channel_next_sig = 1;
2261 if (Stop_logging_sounds == false) {
2264 sprintf(buf, "VOICE sig: %d, sid: %d, snd_id: %d, ch: %d", Channels[channel].sig, sid, snd_id, channel);
2265 HUD_add_to_scrollback(buf, 3);
2270 Channels[channel].last_position = 0;
2272 // make sure there aren't any looping voice messages
2273 for (int i=0; i<MAX_CHANNELS; i++) {
2274 if (Channels[i].is_voice_msg == true) {
2275 if (Channels[i].pdsb == NULL) {
2279 DWORD current_position = ds_get_play_position(i);
2280 if (current_position != 0) {
2281 if (current_position < Channels[i].last_position) {
2282 ds_close_channel(i);
2284 Channels[i].last_position = current_position;
2290 return Channels[channel].sig;
2295 // ---------------------------------------------------------------------------------------
2298 // Return the channel number that is playing the sound identified by sig. If that sound is
2299 // not playing, return -1.
2301 int ds_get_channel(int sig)
2308 for ( i = 0; i < MAX_CHANNELS; i++ ) {
2309 if ( Channels[i].pdsb && Channels[i].sig == sig ) {
2310 if ( ds_is_channel_playing(i) == TRUE ) {
2319 // ---------------------------------------------------------------------------------------
2320 // ds_is_channel_playing()
2323 int ds_is_channel_playing(int channel)
2330 unsigned long status;
2332 if ( !Channels[channel].pdsb ) {
2336 hr = Channels[channel].pdsb->GetStatus(&status);
2337 if ( hr != DS_OK ) {
2338 nprintf(("Sound", "SOUND ==> GetStatus failed with return value %s\n", get_DSERR_text(hr) ));
2342 if ( status & DSBSTATUS_PLAYING )
2349 // ---------------------------------------------------------------------------------------
2350 // ds_stop_channel()
2353 void ds_stop_channel(int channel)
2355 ds_close_channel(channel);
2358 // ---------------------------------------------------------------------------------------
2359 // ds_stop_channel_all()
2362 void ds_stop_channel_all()
2369 for ( i=0; i<MAX_CHANNELS; i++ ) {
2370 if ( Channels[i].pdsb != NULL ) {
2377 // ---------------------------------------------------------------------------------------
2380 // Set the volume for a channel. The volume is expected to be in DirectSound units
2382 // If the sound is a 3D sound buffer, this is like re-establishing the maximum
2385 void ds_set_volume( int channel, int vol )
2391 unsigned long status;
2393 hr = Channels[channel].pdsb->GetStatus(&status);
2394 if ( hr != DS_OK ) {
2395 nprintf(("Sound", "SOUND ==> GetStatus failed with return value %s\n", get_DSERR_text(hr) ));
2399 if ( status & DSBSTATUS_PLAYING ) {
2400 Channels[channel].pdsb->SetVolume(vol);
2405 // ---------------------------------------------------------------------------------------
2408 // Set the pan for a channel. The pan is expected to be in DirectSound units
2410 void ds_set_pan( int channel, int pan )
2416 unsigned long status;
2418 hr = Channels[channel].pdsb->GetStatus(&status);
2419 if ( hr != DS_OK ) {
2420 nprintf(("Sound", "SOUND ==> GetStatus failed with return value %s\n", get_DSERR_text(hr) ));
2424 if ( status & DSBSTATUS_PLAYING ) {
2425 Channels[channel].pdsb->SetPan(pan);
2430 // ---------------------------------------------------------------------------------------
2433 // Get the pitch of a channel
2435 int ds_get_pitch(int channel)
2441 unsigned long status, pitch = 0;
2444 hr = Channels[channel].pdsb->GetStatus(&status);
2446 if ( hr != DS_OK ) {
2447 nprintf(("Sound", "SOUND ==> GetStatus failed with return value %s\n", get_DSERR_text(hr) ));
2451 if ( status & DSBSTATUS_PLAYING ) {
2452 hr = Channels[channel].pdsb->GetFrequency(&pitch);
2453 if ( hr != DS_OK ) {
2454 nprintf(("Sound", "SOUND ==> GetFrequency failed with return value %s\n", get_DSERR_text(hr) ));
2463 // ---------------------------------------------------------------------------------------
2466 // Set the pitch of a channel
2468 void ds_set_pitch(int channel, int pitch)
2473 unsigned long status;
2476 hr = Channels[channel].pdsb->GetStatus(&status);
2477 if ( hr != DS_OK ) {
2478 nprintf(("Sound", "SOUND ==> GetStatus failed with return value %s\n", get_DSERR_text(hr) ));
2482 if ( pitch < MIN_PITCH )
2485 if ( pitch > MAX_PITCH )
2488 if ( status & DSBSTATUS_PLAYING ) {
2489 Channels[channel].pdsb->SetFrequency((unsigned long)pitch);
2494 // ---------------------------------------------------------------------------------------
2495 // ds_chg_loop_status()
2498 void ds_chg_loop_status(int channel, int loop)
2503 unsigned long status;
2506 hr = Channels[channel].pdsb->GetStatus(&status);
2507 if ( hr != DS_OK ) {
2508 nprintf(("Sound", "SOUND ==> GetStatus failed with return value %s\n", get_DSERR_text(hr) ));
2512 if ( !(status & DSBSTATUS_PLAYING) )
2513 return; // sound is not playing anymore
2515 if ( status & DSBSTATUS_LOOPING ) {
2517 return; // we are already looping
2519 // stop the sound from looping
2520 hr = Channels[channel].pdsb->Play(0,0,0);
2525 return; // the sound is already not looping
2527 // start the sound looping
2528 hr = Channels[channel].pdsb->Play(0,0,DSBPLAY_LOOPING);
2534 // ---------------------------------------------------------------------------------------
2537 // Starts a ds3d sound playing
2541 // sid => software id for sound to play
2542 // hid => hardware id for sound to play (-1 if not in hardware)
2543 // snd_id => identifies what type of sound is playing
2544 // pos => world pos of sound
2545 // vel => velocity of object emitting sound
2546 // min => distance at which sound doesn't get any louder
2547 // max => distance at which sound becomes inaudible
2548 // looping => boolean, whether to loop the sound or not
2549 // max_volume => volume (-10000 to 0) for 3d sound at maximum
2550 // estimated_vol => manual estimated volume
2551 // priority => DS_MUST_PLAY
2556 // returns: 0 => sound started successfully
2557 // -1 => sound could not be played
2559 int ds3d_play(int sid, int hid, int snd_id, vector *pos, vector *vel, int min, int max, int looping, int max_volume, int estimated_vol, int priority )
2568 if (!ds_initialized)
2571 channel = ds_get_free_channel(estimated_vol, snd_id, priority);
2574 Assert(Channels[channel].pdsb == NULL);
2576 // First check if the sound is in hardware, and try to duplicate from there
2579 if ( ds_is_3d_buffer(ds_hardware_buffers[hid].pdsb) == FALSE ) {
2580 nprintf(("Sound", "SOUND ==> Tried to play non-3d buffer in ds3d_play()..\n"));
2584 if ( ds_channel_dup(ds_hardware_buffers[hid].pdsb, channel, 1) == 0 ) {
2585 nprintf(("Sound", "SOUND ==> Played sound using DirectSound3D in hardware..\n"));
2589 // Channel will be NULL if hardware dup failed, or there was no hardware dup attempted
2590 if ( Channels[channel].pdsb == NULL ) {
2593 if ( ds_is_3d_buffer(ds_software_buffers[sid].pdsb) == FALSE ) {
2594 nprintf(("Sound", "SOUND ==> Tried to play non-3d buffer in ds3d_play()..\n"));
2599 if ( ds_channel_dup(ds_software_buffers[sid].pdsb, channel, 1) == 0 ) {
2600 // nprintf(("Sound", "SOUND ==> Played sound using DirectSound3D \n"));
2604 if ( Channels[channel].pdsb == NULL ) {
2609 desc = ds_software_buffers[sid].desc;
2610 desc.lpwfxFormat = &ds_software_buffers[sid].wfx;
2612 // duplicate buffer failed, so call CreateBuffer instead
2614 hr = pDirectSound->CreateSoundBuffer(&desc, &Channels[channel].pdsb, NULL );
2616 if ( (hr == DS_OK) && (Channels[channel].pdsb) ) {
2617 BYTE *pdest, *pdest2;
2619 DWORD src_ds_size, dest_ds_size, not_used;
2622 if ( ds_get_size(sid, &src_size) != 0 ) {
2624 Channels[channel].pdsb->Release();
2628 // lock the src buffer
2629 hr = ds_software_buffers[sid].pdsb->Lock(0, src_size, (void**)&psrc, &src_ds_size, (void**)&psrc2, ¬_used, 0);
2630 if ( hr != DS_OK ) {
2631 mprintf(("err: %s\n", get_DSERR_text(hr)));
2633 Channels[channel].pdsb->Release();
2637 if ( Channels[channel].pdsb->Lock(0, src_ds_size, (void**)(&pdest), &dest_ds_size, (void**)&pdest2, ¬_used, 0) == DS_OK) {
2638 memcpy(pdest, psrc, src_ds_size);
2639 Channels[channel].pdsb->Unlock(pdest, dest_ds_size, 0, 0);
2640 ds_get_3d_interface(Channels[channel].pdsb, &Channels[channel].pds3db);
2642 Channels[channel].pdsb->Release();
2649 Assert(Channels[channel].pds3db );
2650 Channels[channel].pds3db->SetMode(DS3DMODE_NORMAL,DS3D_IMMEDIATE);
2652 // set up 3D sound data here
2653 ds3d_update_buffer(channel, i2fl(min), i2fl(max), pos, vel);
2655 Channels[channel].vol = estimated_vol;
2656 Channels[channel].looping = looping;
2658 // sets the maximum "inner cone" volume
2659 Channels[channel].pdsb->SetVolume(max_volume);
2663 ds_flags |= DSBPLAY_LOOPING;
2666 hr = Channels[channel].pdsb->Play(0, 0, ds_flags );
2668 if ( hr == DSERR_BUFFERLOST ) {
2669 ds_restore_buffer(Channels[channel].pdsb);
2670 hr = Channels[channel].pdsb->Play(0, 0, ds_flags );
2673 if ( hr != DS_OK ) {
2674 nprintf(("Sound", "Sound ==> Play failed with return value %s\n", get_DSERR_text(hr) ));
2675 if ( Channels[channel].pdsb ) {
2677 while(++attempts < 10) {
2678 hr = Channels[channel].pdsb->Release();
2679 if ( hr == DS_OK ) {
2682 nprintf(("Sound","SOUND ==> DirectSound Release() failed with code %s\n.",get_DSERR_text(hr) ));
2686 Channels[channel].pdsb = NULL;
2692 nprintf(( "Sound", "SOUND ==> Not playing requested 3D sound\n"));
2696 Channels[channel].snd_id = snd_id;
2697 Channels[channel].sig = channel_next_sig++;
2698 if (channel_next_sig < 0 ) {
2699 channel_next_sig = 1;
2701 return Channels[channel].sig;
2705 void ds_set_position(int channel, DWORD offset)
2710 // set the position of the sound buffer
2711 Channels[channel].pdsb->SetCurrentPosition(offset);
2715 DWORD ds_get_play_position(int channel)
2722 if ( Channels[channel].pdsb ) {
2723 Channels[channel].pdsb->GetCurrentPosition((LPDWORD)&play,(LPDWORD)&write);
2732 DWORD ds_get_write_position(int channel)
2739 if ( Channels[channel].pdsb ) {
2740 Channels[channel].pdsb->GetCurrentPosition((LPDWORD)&play,(LPDWORD)&write);
2749 int ds_get_channel_size(int channel)
2759 if ( Channels[channel].pdsb ) {
2760 memset(&caps, 0, sizeof(DSBCAPS));
2761 caps.dwSize = sizeof(DSBCAPS);
2762 dsrval = Channels[channel].pdsb->GetCaps(&caps);
2763 if ( dsrval != DS_OK ) {
2766 size = caps.dwBufferBytes;
2775 // Returns the number of channels that are actually playing
2776 int ds_get_number_channels()
2785 for ( i = 0; i < MAX_CHANNELS; i++ ) {
2786 if ( Channels[i].pdsb ) {
2787 if ( ds_is_channel_playing(i) == TRUE ) {
2797 // retreive raw data from a sound buffer
2798 int ds_get_data(int sid, char *data)
2804 LPDIRECTSOUNDBUFFER pdsb;
2810 pdsb = ds_software_buffers[sid].pdsb;
2812 memset(&caps, 0, sizeof(DSBCAPS));
2813 caps.dwSize = sizeof(DSBCAPS);
2814 dsrval = pdsb->GetCaps(&caps);
2815 if ( dsrval != DS_OK ) {
2819 // lock the entire buffer
2820 dsrval = pdsb->Lock(0, caps.dwBufferBytes, &buffer_data, &buffer_size, 0, 0, 0);
2821 if ( dsrval != DS_OK ) {
2825 memcpy(data, buffer_data, buffer_size);
2827 dsrval = pdsb->Unlock(buffer_data, buffer_size, 0, 0);
2828 if ( dsrval != DS_OK ) {
2836 // return the size of the raw sound data
2837 int ds_get_size(int sid, int *size)
2843 LPDIRECTSOUNDBUFFER pdsb;
2847 pdsb = ds_software_buffers[sid].pdsb;
2849 memset(&caps, 0, sizeof(DSBCAPS));
2850 caps.dwSize = sizeof(DSBCAPS);
2851 dsrval = pdsb->GetCaps(&caps);
2852 if ( dsrval != DS_OK ) {
2856 *size = caps.dwBufferBytes;
2866 // Return the primary buffer interface. Note that we cast to a uint to avoid
2867 // having to include dsound.h (and thus windows.h) in ds.h.
2869 uint ds_get_primary_buffer_interface()
2875 return (uint)pPrimaryBuffer;
2879 // Return the DirectSound Interface.
2881 uint ds_get_dsound_interface()
2887 return (uint)pDirectSound;
2891 uint ds_get_property_set_interface()
2897 return (uint)pPropertySet;
2901 // --------------------
2903 // EAX Functions below
2905 // --------------------
2907 // Set the master volume for the reverb added to all sound sources.
2909 // volume: volume, range from 0 to 1.0
2911 // returns: 0 if the volume is set successfully, otherwise return -1
2913 int ds_eax_set_volume(float volume)
2921 if (Ds_eax_inited == 0) {
2925 Assert(Ds_eax_reverb);
2927 CAP(volume, 0.0f, 1.0f);
2929 hr = Ds_eax_reverb->Set(DSPROPSETID_EAX_ReverbProperties_Def, DSPROPERTY_EAX_VOLUME, NULL, 0, &volume, sizeof(float));
2930 if (SUCCEEDED(hr)) {
2938 // Set the decay time for the EAX environment (ie all sound sources)
2940 // seconds: decay time in seconds
2942 // returns: 0 if decay time is successfully set, otherwise return -1
2944 int ds_eax_set_decay_time(float seconds)
2952 if (Ds_eax_inited == 0) {
2956 Assert(Ds_eax_reverb);
2958 CAP(seconds, 0.1f, 20.0f);
2960 hr = Ds_eax_reverb->Set(DSPROPSETID_EAX_ReverbProperties_Def, DSPROPERTY_EAX_DECAYTIME, NULL, 0, &seconds, sizeof(float));
2961 if (SUCCEEDED(hr)) {
2969 // Set the damping value for the EAX environment (ie all sound sources)
2971 // damp: damp value from 0 to 2.0
2973 // returns: 0 if the damp value is successfully set, otherwise return -1
2975 int ds_eax_set_damping(float damp)
2983 if (Ds_eax_inited == 0) {
2987 Assert(Ds_eax_reverb);
2989 CAP(damp, 0.0f, 2.0f);
2991 hr = Ds_eax_reverb->Set(DSPROPSETID_EAX_ReverbProperties_Def, DSPROPERTY_EAX_DAMPING, NULL, 0, &damp, sizeof(float));
2992 if (SUCCEEDED(hr)) {
3000 // Set up the environment type for all sound sources.
3002 // envid: value from the EAX_ENVIRONMENT_* enumeration in ds_eax.h
3004 // returns: 0 if the environment is set successfully, otherwise return -1
3006 int ds_eax_set_environment(unsigned long envid)
3014 if (Ds_eax_inited == 0) {
3018 Assert(Ds_eax_reverb);
3020 hr = Ds_eax_reverb->Set(DSPROPSETID_EAX_ReverbProperties_Def, DSPROPERTY_EAX_ENVIRONMENT, NULL, 0, &envid, sizeof(unsigned long));
3021 if (SUCCEEDED(hr)) {
3029 // Set up a predefined environment for EAX
3031 // envid: value from teh EAX_ENVIRONMENT_* enumeration
3033 // returns: 0 if successful, otherwise return -1
3035 int ds_eax_set_preset(unsigned long envid)
3043 if (Ds_eax_inited == 0) {
3047 Assert(Ds_eax_reverb);
3048 Assert(envid < EAX_ENVIRONMENT_COUNT);
3050 hr = Ds_eax_reverb->Set(DSPROPSETID_EAX_ReverbProperties_Def, DSPROPERTY_EAX_ALL, NULL, 0, &Ds_eax_presets[envid], sizeof(EAX_REVERBPROPERTIES));
3051 if (SUCCEEDED(hr)) {
3060 // Set up all the parameters for an environment
3062 // id: value from teh EAX_ENVIRONMENT_* enumeration
3063 // volume: volume for the environment (0 to 1.0)
3064 // damping: damp value for the environment (0 to 2.0)
3065 // decay: decay time in seconds (0.1 to 20.0)
3067 // returns: 0 if successful, otherwise return -1
3069 int ds_eax_set_all(unsigned long id, float vol, float damping, float decay)
3077 if (Ds_eax_inited == 0) {
3081 Assert(Ds_eax_reverb);
3082 Assert(id < EAX_ENVIRONMENT_COUNT);
3084 EAX_REVERBPROPERTIES er;
3086 er.environment = id;
3088 er.fDecayTime_sec = decay;
3089 er.fDamping = damping;
3091 hr = Ds_eax_reverb->Set(DSPROPSETID_EAX_ReverbProperties_Def, DSPROPERTY_EAX_ALL, NULL, 0, &er, sizeof(EAX_REVERBPROPERTIES));
3092 if (SUCCEEDED(hr)) {
3100 // Get up the parameters for the current environment
3102 // er: (output) hold environment parameters
3104 // returns: 0 if successful, otherwise return -1
3106 int ds_eax_get_all(EAX_REVERBPROPERTIES *er)
3113 unsigned long outsize;
3115 if (Ds_eax_inited == 0) {
3119 Assert(Ds_eax_reverb);
3121 hr = Ds_eax_reverb->Get(DSPROPSETID_EAX_ReverbProperties_Def, DSPROPERTY_EAX_ALL, NULL, 0, er, sizeof(EAX_REVERBPROPERTIES), &outsize);
3122 if (SUCCEEDED(hr)) {
3130 // Close down EAX, freeing any allocated resources
3137 if (Ds_eax_inited == 0) {
3147 // returns: 0 if initialization is successful, otherwise return -1
3155 unsigned long driver_support = 0;
3157 if (Ds_eax_inited) {
3161 Assert(Ds_eax_reverb == NULL);
3163 Ds_eax_reverb = (LPKSPROPERTYSET)ds_get_property_set_interface();
3164 if (Ds_eax_reverb == NULL) {
3168 // check if the listener property is supported by the audio driver
3169 hr = Ds_eax_reverb->QuerySupport(DSPROPSETID_EAX_ReverbProperties_Def, DSPROPERTY_EAX_ALL, &driver_support);
3171 nprintf(("Sound", "QuerySupport for the EAX Listener property set failed.. disabling EAX\n"));
3172 goto ds_eax_init_failed;
3175 if ((driver_support & (KSPROPERTY_SUPPORT_GET | KSPROPERTY_SUPPORT_SET)) != (KSPROPERTY_SUPPORT_GET | KSPROPERTY_SUPPORT_SET)) {
3176 goto ds_eax_init_failed;
3179 ds_eax_set_all(EAX_ENVIRONMENT_GENERIC, 0.0f, 0.0f, 0.0f);
3185 if (Ds_eax_reverb != NULL) {
3186 Ds_eax_reverb->Release();
3187 Ds_eax_reverb = NULL;
3196 int ds_eax_is_inited()
3202 return Ds_eax_inited;
3212 if (Ds_use_a3d == 0) {
3220 // Called once per game frame to make sure voice messages aren't looping
3229 for (int i=0; i<MAX_CHANNELS; i++) {
3231 if (cp->is_voice_msg == true) {
3232 if (cp->pdsb == NULL) {
3236 DWORD current_position = ds_get_play_position(i);
3237 if (current_position != 0) {
3238 if (current_position < cp->last_position) {
3239 ds_close_channel(i);
3241 cp->last_position = current_position;