2 * $Logfile: /Freespace2/code/Sound/Sound.cpp $
10 * Revision 1.3 2002/05/27 00:40:47 theoddone33
11 * Fix net_addr vs net_addr_t
13 * Revision 1.2 2002/05/07 03:16:52 theoddone33
14 * The Great Newline Fix
16 * Revision 1.1.1.1 2002/05/03 03:28:10 root
20 * 9 9/12/99 8:09p Dave
21 * Fixed problem where skip-training button would cause mission messages
22 * not to get paged out for the current mission.
24 * 8 8/27/99 6:38p Alanl
25 * crush the blasted repeating messages bug
27 * 7 8/22/99 11:06p Alanl
28 * don't convert priority in snd_play_3d
30 * 6 8/04/99 9:48p Alanl
31 * fix bug with setting 3D properties on a 2D sound buffer
33 * 5 6/18/99 5:16p Dave
34 * Added real beam weapon lighting. Fixed beam weapon sounds. Added MOTD
35 * dialog to PXO screen.
37 * 4 5/23/99 8:11p Alanl
38 * Added support for EAX
40 * 3 1/29/99 12:47a Dave
41 * Put in sounds for beam weapon. A bunch of interface screens (tech
44 * 2 10/07/98 10:54a Dave
47 * 1 10/07/98 10:51a Dave
49 * 77 6/13/98 6:02p Hoffoss
50 * Externalized all new (or forgot to be added) strings to all the code.
52 * 76 5/23/98 9:27p Lawrance
53 * Change ACM failure message to use a message box, not a Warning()
55 * 75 5/15/98 3:36p John
56 * Fixed bug with new graphics window code and standalone server. Made
57 * hwndApp not be a global anymore.
59 * 74 5/12/98 5:39p Lawrance
60 * Increase MAX_SOUNDS to 175.. to account for missions with lots of voice
62 * 73 5/12/98 2:43p Lawrance
63 * Make snd_time_remaining() work for arbitrary format
65 * 72 5/11/98 2:02p Andsager
68 * 71 5/11/98 1:56p Andsager
69 * increase min_range in snd_play_3d when range_factor is not 1.0
71 * 70 5/10/98 3:49p Sandeep
72 * Fix problem with having the audio streaming while trying to close down
75 * 69 5/09/98 10:48p Lawrance
76 * Default voice volume to 0.7
78 * 68 5/05/98 4:49p Lawrance
79 * Put in code to authenticate A3D, improve A3D support
81 * 67 4/25/98 12:01p Lawrance
82 * try to init sound for 5 seconds... to overcome conflicts with launch
85 * 66 4/20/98 12:03a Lawrance
86 * Allow prioritizing of CTRL3D buffers
88 * 65 4/19/98 9:30p Lawrance
89 * Use Aureal_enabled flag
91 * 64 4/18/98 9:12p Lawrance
92 * Added Aureal support.
94 * 63 4/14/98 3:29p John
97 * 62 4/13/98 5:04p Lawrance
98 * Write functions to determine how many milliseconds are left in a sound
100 * 61 4/09/98 5:53p Lawrance
101 * Make DirectSound init more robust
103 * 60 4/01/98 9:21p John
104 * Made NDEBUG, optimized build with no warnings or errors.
106 * 59 3/29/98 12:56a Lawrance
107 * preload the warp in and explosions sounds before a mission.
109 * 58 3/25/98 6:10p Lawrance
110 * Work on DirectSound3D
112 * 57 3/24/98 4:28p Lawrance
113 * Make DirectSound3D support more robust
115 * 56 3/23/98 10:32a Lawrance
116 * Add functions for extracting raw sound data
118 * 55 3/21/98 3:34p Lawrance
119 * Allow 3d sounds to have their ranges modified dynamically
121 * 54 3/19/98 5:36p Lawrance
122 * Add some sound debug functions to see how many sounds are playing, and
123 * to start/stop random looping sounds.
125 * 53 3/17/98 5:55p Lawrance
126 * Support object-linked sounds for asteroids.
128 * 52 2/20/98 8:32p Lawrance
129 * Add radius parm to sound_play_3d()
131 * 51 2/18/98 5:49p Lawrance
132 * Even if the ADPCM codec is unavailable, allow game to continue.
134 * 50 2/15/98 4:43p Lawrance
135 * work on real-time voice
137 * 49 2/06/98 7:30p John
138 * Added code to monitor the number of channels of sound actually playing.
140 * 48 2/05/98 9:21p John
141 * Some new Direct3D code. Added code to monitor a ton of stuff in the
144 * 47 1/31/98 5:57p Lawrance
145 * remove debug code that was stopping any sounds from playing
147 * 46 1/31/98 5:48p Lawrance
148 * Start on real-time voice recording
150 * 45 1/19/98 11:37p Lawrance
151 * Fixing Optimization build warnings
153 * 44 1/13/98 5:36p Lawrance
154 * Reduce default sound volume to 0.9.
156 * 43 1/11/98 11:14p Lawrance
157 * Preload sounds that we expect will get played.
159 * 42 1/10/98 1:14p John
160 * Added explanation to debug console commands
162 * 41 1/07/98 11:08a Lawrance
163 * pass priority to snd_play_raw()
165 * 40 12/21/97 4:33p John
166 * Made debug console functions a class that registers itself
167 * automatically, so you don't need to add the function to
168 * debugfunctions.cpp.
170 * 39 12/05/97 5:19p Lawrance
171 * re-do sound priorities to make more general and extensible
173 * 38 12/04/97 10:21a Lawrance
174 * if a 3D sound has priority, only play if above a minimum volume level
176 * 37 11/20/97 5:36p Dave
177 * Hooked in a bunch of main hall changes (including sound). Made it
178 * possible to reposition (rewind/ffwd)
179 * sound buffer pointers. Fixed animation direction change framerate
182 * 36 11/20/97 1:06a Lawrance
183 * Add Master_voice_volume, make voices play back at correctly scaled
186 * 35 11/12/97 4:40p Dave
187 * Put in multiplayer campaign support parsing, loading and saving. Made
188 * command-line variables better named. Changed some things on the initial
189 * pilot select screen.
191 * 34 10/14/97 11:33p Lawrance
192 * get RSX implemented
194 * 33 10/13/97 7:41p Lawrance
195 * store duration of sound
197 * 32 10/06/97 4:12p Lawrance
198 * fix volume bug with 3d sounds
200 * 31 10/01/97 5:55p Lawrance
201 * change call to snd_play_3d() to allow for arbitrary listening position
203 * 30 9/09/97 3:39p Sandeep
204 * warning level 4 bugs
206 * 29 9/03/97 5:03p Lawrance
207 * add support for -nosound command line parm
209 * 28 7/31/97 11:16a Dan
210 * Add some Asserts() to check validity of vectors send to DirectSound3D
212 * 27 7/28/97 11:39a Lawrance
213 * allow individual volume scaling on 3D buffers
215 * 26 7/17/97 9:53a Lawrance
216 * if a sound is supposed to use DirectSound3D, ensure it does when
219 * 25 7/17/97 9:32a John
220 * made all directX header files name start with a v
222 * 24 7/15/97 11:15a Lawrance
223 * limit the max instances of simultaneous sound effects, implement
224 * priorities to force critical sounds
226 * 23 7/13/97 5:52p Lawrance
227 * allow snd_set_volume() to set volume at any level
229 * 22 6/13/97 4:44p Lawrance
230 * added another sound hook in ship selection
232 * 21 6/09/97 11:50p Lawrance
233 * integrating DirectSound3D
235 * 20 6/05/97 11:25a Lawrance
236 * use sound signatures to ensure correct sound is loaded
238 * 19 6/05/97 1:36a Lawrance
239 * using a new interface to play sounds
241 * 18 6/05/97 1:08a Lawrance
242 * new sound play interface
244 * 17 6/03/97 9:23a Lawrance
245 * fix bug that caused when sound not found
247 * 16 6/02/97 1:45p Lawrance
248 * implementing hardware mixing
250 * 15 5/29/97 4:01p Lawrance
251 * don't fail sound init if dsound3d fails init
253 * 14 5/29/97 3:32p Lawrance
254 * added call to snd_do_frame()
256 * 13 5/29/97 12:04p Lawrance
257 * split off acm, direct sound, and direct sound 3d portions to separate
260 * 12 5/21/97 3:55p Lawrance
261 * when reclaiming sound channels, never stop a looping sound
263 * 11 5/19/97 4:32p Lawrance
264 * remove misleading nprintf
266 * 10 5/15/97 9:05a Lawrance
267 * If no sound channels, take away the lowest volume sound (if that volume
268 * is less than requested sound fx volume)
270 * 9 5/12/97 10:32a Lawrance
273 * 8 5/09/97 4:51p Lawrance
276 * 7 5/09/97 4:34p Lawrance
279 * 6 5/07/97 3:29p Lawrance
280 * make volume conversion use a lookup table, fix errors in volume
283 * 5 5/07/97 11:33a Lawrance
284 * improve snd_chg_loop_status()
286 * 4 5/06/97 9:36a Lawrance
287 * added support for min and max distances for 3d sounds
289 * 3 5/02/97 4:36p Lawrance
290 * send correct volume scaling when playing a 3D sound
292 * 2 4/28/97 5:13p John
293 * more moving sound/movie code out of osapi.
305 #include "3dinternal.h"
307 #include "audiostr.h"
313 #include "alphacolors.h"
322 #define SND_F_USED (1<<0) // Sounds[] element is used
324 typedef struct sound {
325 int sid; // software id
326 int hid; // hardware id, -1 if sound is not in hardware
327 char filename[MAX_FILENAME_LEN];
331 int uncompressed_size; // size (in bytes) of sound (uncompressed)
335 sound Sounds[MAX_SOUNDS];
337 int Sound_enabled = TRUE; // global flag to turn sound on/off
338 int Snd_sram; // mem (in bytes) used up by storing sounds in system memory
339 int Snd_hram; // mem (in bytes) used up by storing sounds in soundcard memory
340 float Master_sound_volume = 1.0f; // range is 0 -> 1, used for non-music sound fx
341 float Master_voice_volume = 0.7f; // range is 0 -> 1, used for all voice playback
343 // min volume to play a sound after all volume processing (range is 0.0 -> 1.0)
344 #define MIN_SOUND_VOLUME 0.10f
346 static int snd_next_sig = 1;
348 // convert the game level sound priorities to the DirectSound priority descriptions
349 int ds_priority(int priority)
355 case SND_PRIORITY_MUST_PLAY:
357 case SND_PRIORITY_SINGLE_INSTANCE:
359 case SND_PRIORITY_DOUBLE_INSTANCE:
361 case SND_PRIORITY_TRIPLE_INSTANCE:
362 return DS_LIMIT_THREE;
374 // flag all Sounds[] as free
375 for (i=0; i<MAX_SOUNDS; i++ ) {
376 Sounds[i].flags &= ~SND_F_USED;
381 // reset how much storage sounds are taking up in memory
386 // ---------------------------------------------------------------------------------------
387 // Initialize the game sound system
389 // Initialize the game sound system. Depending on what sound library is being used,
390 // call the appropriate low-level initiailizations
392 // returns: 1 => init success
395 int snd_init(int use_a3d, int use_eax)
399 if ( Cmdline_freespace_no_sound )
402 if (ds_initialized) {
403 nprintf(( "Sound", "SOUND => Direct Sound is already initialized!\n" ));
411 // Connect to DirectSound
413 int gave_warning = 0;
415 rval = ds_init(use_a3d, use_eax);
418 nprintf(( "Sound", "SOUND ==> Error initializing DirectSound, trying again in 1 second.\n"));
424 if ( num_tries++ > 5 ) {
425 if ( !gave_warning ) {
426 MessageBox(NULL, XSTR("DirectSound could not be initialized. If you are running any applications playing sound in the background, you should stop them before continuing.",971), NULL, MB_OK);
434 // Init the Audio Compression Manager
435 if ( ACM_init() == -1 ) {
436 HWND hwnd = (HWND)os_get_window();
437 MessageBox(hwnd, XSTR("Could not properly initialize the Microsoft ADPCM codec.\n\nPlease see the readme.txt file for detailed instructions on installing the Microsoft ADPCM codec.",972), NULL, MB_OK);
438 // Warning(LOCATION, "Could not properly initialize the Microsoft ADPCM codec.\nPlease see the readme.txt file for detailed instructions on installing the Microsoft ADPCM codec.");
441 // Init the audio streaming stuff
448 // Warning(LOCATION, "Sound system was unable to be initialized. If you continue, sound will be disabled.\n");
449 nprintf(( "Sound", "SOUND => Direct Sound init unsuccessful, continuing without sound.\n" ));
458 CFILE *out = cfopen("sounds.txt", "wt", CFILE_NORMAL, CF_TYPE_DATA);
463 cfwrite_string("Sounds loaded :\n", out);
465 // spew info for all sounds
466 for(idx=0; idx<MAX_SOUNDS; idx++){
467 if(!(Sounds[idx].flags & SND_F_USED)){
471 sprintf(txt, "%s (%ds)\n", Sounds[idx].filename, Sounds[idx].info.duration);
472 cfwrite_string(txt, out);
485 Sound_spew = !Sound_spew;
487 dc_printf("Sound debug info ON");
489 dc_printf("Sound debug info OFF");
492 void snd_spew_debug_info()
495 int message_sounds = 0;
496 int interface_sounds = 0;
504 // count up game, interface and message sounds
505 for(int idx=0; idx<MAX_SOUNDS; idx++){
506 if(!Sounds[idx].flags & SND_F_USED){
512 // what kind of sound is this
513 for(s_idx=0; s_idx<MAX_GAME_SOUNDS; s_idx++){
514 if(!stricmp(Snds[s_idx].filename, Sounds[idx].filename)){
521 for(s_idx=0; s_idx<MAX_GAME_SOUNDS; s_idx++){
522 if(!stricmp(Snds_iface[s_idx].filename, Sounds[idx].filename)){
535 gr_set_color_fast(&Color_normal);
536 gr_printf(30, 100, "Game sounds : %d\n", game_sounds);
537 gr_printf(30, 110, "Interface sounds : %d\n", interface_sounds);
538 gr_printf(30, 120, "Message sounds : %d\n", message_sounds);
539 gr_printf(30, 130, "Total sounds : %d\n", game_sounds + interface_sounds + message_sounds);
542 // ---------------------------------------------------------------------------------------
545 // Load a sound into memory and prepare it for playback. The sound will reside in memory as
546 // a single instance, and can be played multiple times simultaneously. Through the magic of
547 // DirectSound, only 1 copy of the sound is used.
549 // parameters: gs => file of sound to load
550 // allow_hardware_load => whether to try to allocate in hardware
552 // returns: success => index of sound in Sounds[] array
555 //int snd_load( char *filename, int hardware, int use_ds3d, int *sig)
556 int snd_load( game_snd *gs, int allow_hardware_load )
561 WAVEFORMATEX *header = NULL;
563 if ( gs->filename == NULL || gs->filename[0] == 0 )
566 for (n=0; n<MAX_SOUNDS; n++ ) {
567 if (!(Sounds[n].flags & SND_F_USED))
569 else if ( !stricmp( Sounds[n].filename, gs->filename )) {
570 gs->sig = Sounds[n].sig;
575 if ( n == MAX_SOUNDS ) {
587 if ( !ds_initialized )
592 if ( ds_parse_wave(gs->filename, &si->data, &si->size, &header) == -1 )
595 si->format = header->wFormatTag; // 16-bit flag (wFormatTag)
596 si->n_channels = header->nChannels; // 16-bit channel count (nChannels)
597 si->sample_rate = header->nSamplesPerSec; // 32-bit sample rate (nSamplesPerSec)
598 si->avg_bytes_per_sec = header->nAvgBytesPerSec; // 32-bit average bytes per second (nAvgBytesPerSec)
599 si->n_block_align = header->nBlockAlign; // 16-bit block alignment (nBlockAlign)
600 si->bits = header->wBitsPerSample; // Read 16-bit bits per sample
602 snd->duration = fl2i(1000.0f * (si->size / (si->bits/8.0f)) / si->sample_rate);
605 if ( allow_hardware_load ) {
611 if ( (gs->flags&GAME_SND_USE_DS3D) ) {
615 rc = ds_load_buffer(&snd->sid, &snd->hid, &snd->uncompressed_size, header, si, type);
618 free(si->data); // don't want to keep this around
623 strncpy( snd->filename, gs->filename, MAX_FILENAME_LEN );
624 snd->flags = SND_F_USED;
626 snd->sig = snd_next_sig++;
627 if (snd_next_sig < 0 ) snd_next_sig = 1;
628 gs->id_sig = snd->sig;
631 nprintf(("Sound", "Loaded %s\n", gs->filename));
635 // ---------------------------------------------------------------------------------------
638 // Unload a sound from memory. This will release the storage, and the sound must be re-loaded via
639 // sound_load() before it can be played again.
641 int snd_unload( int n )
646 if ( (n < 0) || ( n >= MAX_SOUNDS) )
649 if ( !(Sounds[n].flags & SND_F_USED) )
652 ds_unload_buffer(Sounds[n].sid, Sounds[n].hid);
653 if ( Sounds[n].sid != -1 ) {
654 Snd_sram -= Sounds[n].uncompressed_size;
656 if ( Sounds[n].hid != -1 ) {
657 Snd_hram -= Sounds[n].uncompressed_size;
660 Sounds[n].flags &= ~SND_F_USED;
665 // ---------------------------------------------------------------------------------------
668 // Unload all sounds from memory. This will release the storage, and the sound must be re-loaded via
669 // sound_load() before it can be played again.
671 void snd_unload_all()
674 for (i=0; i<MAX_SOUNDS; i++ ) {
675 if ( Sounds[i].flags & SND_F_USED )
680 // ---------------------------------------------------------------------------------------
683 // This is the companion function to snd_init()... it closes down the game sound system.
688 if (!ds_initialized) return;
689 snd_unload_all(); // free the sound data stored in DirectSound secondary buffers
690 ACM_close(); // Close the Audio Compression Manager (ACM)
691 ds3d_close(); // Close DirectSound3D
692 dscap_close(); // Close DirectSoundCapture
693 ds_close(); // Close DirectSound off
696 // ---------------------------------------------------------------------------------------
699 // Allow a sound to be played directly from the index in Sounds[]. This bypasses the
700 // normal game sound management system.
702 // returns: -1 => sound could not be played
703 // n => handle for instance of sound
705 int snd_play_raw( int soundnum, float pan, float vol_scale, int priority )
711 gs.id_sig = Sounds[soundnum].sig;
713 gs.default_volume = 1.0f;
714 // gs.flags = GAME_SND_VOICE | GAME_SND_USE_DS3D;
715 gs.flags = GAME_SND_VOICE;
717 rval = snd_play(&gs, 0.0f, vol_scale, priority, true);
721 MONITOR( NumSoundsStarted );
722 MONITOR( NumSoundsLoaded );
724 // ---------------------------------------------------------------------------------------
727 // NOTE: vol_scale parameter is the multiplicative scaling applied to the default volume
728 // (vol_scale is a default parameter with a default value of 1.0f)
730 // input: gs => game-level sound description
731 // pan => -1 (full left) to 1.0 (full right), this is a default parm
732 // vol_scale => factor to scale default volume by (applied before global sound volume applied)
733 // priority => SND_PRIORITY_MUST_PLAY
734 // SND_PRIORITY_SINGLE_INSTANCE (default value)
735 // SND_PRIORITY_DOUBLE_INSTANCE
736 // SND_PRIORITY_TRIPLE_INSTANCE
738 // returns: -1 => sound could not be played
739 // n => handle for instance of sound
741 int snd_play( game_snd *gs, float pan, float vol_scale, int priority, bool is_voice_msg )
751 Assert( gs != NULL );
753 MONITOR_INC( NumSoundsStarted, 1 );
755 if ( gs->id == -1 ) {
756 gs->id = snd_load(gs);
757 MONITOR_INC( NumSoundsLoaded, 1);
758 } else if ( gs->id_sig != Sounds[gs->id].sig ) {
759 gs->id = snd_load(gs);
765 volume = gs->default_volume * vol_scale;
766 if ( gs->flags&GAME_SND_VOICE ) {
767 volume *= Master_voice_volume;
769 volume *= Master_sound_volume;
774 snd = &Sounds[gs->id];
776 if ( !(snd->flags & SND_F_USED) )
782 if ( volume > MIN_SOUND_VOLUME ) {
783 handle = ds_play( snd->sid, snd->hid, gs->id_sig, ds_priority(priority), ds_convert_volume(volume), fl2i(pan*MAX_PAN), 0, is_voice_msg);
789 MONITOR( Num3DSoundsStarted );
790 MONITOR( Num3DSoundsLoaded );
792 // ---------------------------------------------------------------------------------------
795 // NOTE: vol_scale parameter is the multiplicative scaling applied to the default volume
796 // (vol_scale is a default parameter with a default value of 1.0f)
798 // input: gs => game-level sound description
799 // source_pos => global pos of where the sound is
800 // listen_pos => global pos of where listener is
801 // radius => optional parameter, this specifes distance at which to apply min/max distances
802 // source_vel => velocity of the source playing the sound (used for DirectSound3D only)
803 // looping => flag to indicate the sound should loop (default value 0)
804 // vol_scale => factor to scale the static volume by (applied before attenuation)
805 // priority => SND_PRIORITY_MUST_PLAY
806 // SND_PRIORITY_SINGLE_INSTANCE (default value)
807 // SND_PRIORITY_DOUBLE_INSTANCE
808 // SND_PRIORITY_TRIPLE_INSTANCE
809 // sound_fvec => forward vector of where sound is emitting from (RSX use only)
810 // range_factor => factor N, which increases distance sound is heard by N times (default value 1)
812 // returns: -1 => sound could not be played
813 // n => handle for instance of sound
815 int snd_play_3d(game_snd *gs, vector *source_pos, vector *listen_pos, float radius, vector *source_vel, int looping, float vol_scale, int priority, vector *sound_fvec, float range_factor, int force )
817 int handle, min_range, max_range;
818 vector vector_to_sound;
820 float volume, distance, pan, max_volume;
822 if ( !Sound_enabled )
827 MONITOR_INC( Num3DSoundsStarted, 1 );
829 if ( gs->id == -1 ) {
830 gs->id = snd_load(gs);
831 MONITOR_INC( Num3DSoundsLoaded, 1 );
832 }else if ( gs->id_sig != Sounds[gs->id].sig ) {
833 gs->id = snd_load(gs);
839 snd = &Sounds[gs->id];
841 if ( !(snd->flags & SND_F_USED) )
846 min_range = fl2i( (gs->min + radius) * range_factor);
847 max_range = fl2i( (gs->max + radius) * range_factor + 0.5f);
852 // DirectSound3D will not cut off sounds, no matter how quite they become.. so manually
853 // prevent sounds from playing past the max distance.
854 distance = vm_vec_normalized_dir_quick( &vector_to_sound, source_pos, listen_pos );
855 max_volume = gs->default_volume * vol_scale;
856 if ( (distance > max_range) && !force){
860 if ( distance <= min_range ) {
864 volume = max_volume - max_volume*(distance/max_range);
867 if ( volume > 1.0f ){
871 if ( priority == SND_PRIORITY_MUST_PLAY ) {
872 if ( volume < 0.3 ) {
873 priority = SND_PRIORITY_DOUBLE_INSTANCE;
877 volume *= Master_sound_volume;
878 if ( (volume < MIN_SOUND_VOLUME) && !force) {
882 int play_using_ds3d = 0;
884 if (ds_using_ds3d()) {
885 if ( ds_is_3d_buffer(snd->sid) ) {
890 if ( play_using_ds3d ) {
891 // play through DirectSound3D
892 handle = ds3d_play( snd->sid, snd->hid, gs->id_sig, source_pos, source_vel, min_range, max_range, looping, ds_convert_volume(max_volume*Master_sound_volume), ds_convert_volume(volume), ds_priority(priority));
895 // play sound as a fake 3D sound
896 if ( distance <= 0 ) {
900 pan = vm_vec_dot(&View_matrix.rvec,&vector_to_sound);
903 handle = snd_play_looping( gs, pan, -1, -1, volume/gs->default_volume, priority, force );
905 handle = snd_play( gs, pan, volume/gs->default_volume, priority);
912 // update the given 3d sound with a new position
913 void snd_update_3d_pos(int soundnum, game_snd *gs, vector *new_pos)
917 // get new volume and pan vals
918 snd_get_3d_vol_and_pan(gs, new_pos, &vol, &pan);
921 snd_set_volume(soundnum, vol);
924 snd_set_pan(soundnum, pan);
927 // ---------------------------------------------------------------------------------------
928 // snd_get_3d_vol_and_pan()
930 // Based on the 3D position the player and the object, calculate
931 // the correct volume and pan.
933 // parameters: gs => pointer to sound description
934 // pos => 3D position used to calc volume and pan
935 // vol => output parameter for the volume
936 // pan => output parameter for the pan
937 // radius => optional parameter (default value 0) which indicates sound attenuation
938 // should occur from this radius
940 // returns: -1 => could not determine vol or pan
943 // NOTE: the volume is not scaled by the Master_sound_volume, since this always occurs
944 // when snd_play() or snd_play_looping() is called
946 int snd_get_3d_vol_and_pan(game_snd *gs, vector *pos, float* vol, float *pan, float radius)
948 vector vector_to_sound;
949 float distance, max_volume;
960 if ( gs->id == -1 ) {
961 gs->id = snd_load(gs);
964 snd = &Sounds[gs->id];
965 if ( !(snd->flags & SND_F_USED) )
968 distance = vm_vec_normalized_dir_quick( &vector_to_sound, pos, &View_position );
971 max_volume = gs->default_volume;
972 if ( distance <= gs->min ) {
976 *vol = max_volume - (distance - gs->min) * max_volume / (gs->max - gs->min);
982 if ( *vol > MIN_SOUND_VOLUME ) {
986 *pan = vm_vec_dot(&View_matrix.rvec,&vector_to_sound);
992 // ---------------------------------------------------------------------------------------
993 // volume 0 to 1.0. Returns the handle of the sound. -1 if failed.
994 // If startloop or stoploop are not -1, then then are used.
996 // NOTE: vol_scale parameter is the multiplicative scaling applied to the default volume
997 // (vol_scale is a default parameter with a default value of 1.0f)
999 // input: gs => game-level sound description
1000 // source_pos => global pos of where the sound is
1001 // listen_pos => global pos of where listener is
1002 // source_vel => velocity of the source playing the sound (used for DirectSound3D only)
1003 // looping => flag to indicate the sound should loop (default value 0)
1004 // vol_scale => factor to scale the static volume by (applied before attenuation)
1005 // priority => SND_PRIORITY_MUST_PLAY (default value)
1006 // SND_PRIORITY_SINGLE_INSTANCE
1007 // SND_PRIORITY_DOUBLE_INSTANCE
1008 // SND_PRIORITY_TRIPLE_INSTANCE
1010 // returns: -1 => sound could not be played
1011 // n => handle for instance of sound
1013 int snd_play_looping( game_snd *gs, float pan, int start_loop, int stop_loop, float vol_scale, int priority, int force )
1022 Assert( gs != NULL );
1024 if (!ds_initialized)
1027 if ( gs->id == -1 ) {
1028 gs->id = snd_load(gs);
1030 else if ( gs->id_sig != Sounds[gs->id].sig ) {
1031 gs->id = snd_load(gs);
1037 snd = &Sounds[gs->id];
1039 if ( !(snd->flags & SND_F_USED) )
1042 volume = gs->default_volume * vol_scale;
1043 volume *= Master_sound_volume;
1044 if ( volume > 1.0f )
1047 if ( (volume > MIN_SOUND_VOLUME) || force) {
1048 handle = ds_play( snd->sid, snd->hid, gs->id_sig, ds_priority(priority), ds_convert_volume(volume), fl2i(pan*MAX_PAN), 1);
1054 // ---------------------------------------------------------------------------------------
1057 // Stop a sound from playing.
1059 // parameters: sig => handle to sound, what is returned from snd_play()
1061 void snd_stop( int sig )
1065 if (!ds_initialized) return;
1066 if ( sig < 0 ) return;
1068 channel = ds_get_channel(sig);
1069 if ( channel == -1 )
1072 ds_stop_channel(channel);
1075 // ---------------------------------------------------------------------------------------
1078 // Set the volume of a currently playing sound
1080 // parameters: sig => handle to sound, what is returned from snd_play()
1081 // volume => volume of sound (range: 0.0 -> 1.0)
1083 void snd_set_volume( int sig, float volume )
1088 if (!ds_initialized)
1094 channel = ds_get_channel(sig);
1095 if ( channel == -1 ) {
1096 nprintf(( "Sound", "WARNING: Trying to set volume for a non-playing sound.\n" ));
1100 new_volume = volume * Master_sound_volume;
1101 ds_set_volume( channel, ds_convert_volume(new_volume) );
1104 // ---------------------------------------------------------------------------------------
1107 // Set the pan of a currently playing sound
1109 // parameters: sig => handle to sound, what is returned from snd_play()
1110 // pan => pan of sound (range: -1.0 -> 1.0)
1112 void snd_set_pan( int sig, float pan )
1116 if (!ds_initialized)
1122 channel = ds_get_channel(sig);
1123 if ( channel == -1 ) {
1124 nprintf(( "Sound", "WARNING: Trying to set pan for a non-playing sound.\n" ));
1128 ds_set_pan( channel, fl2i(pan*MAX_PAN) );
1131 // ---------------------------------------------------------------------------------------
1134 // Return the pitch of a currently playing sound
1136 // returns: pitch of sound ( range: 100 to 100000)
1138 // parameters: sig => handle to sound, what is returned from snd_play()
1140 int snd_get_pitch(int sig)
1142 int channel, pitch=10000;
1144 if (!ds_initialized)
1150 channel = ds_get_channel(sig);
1151 if ( channel == -1 ) {
1152 nprintf(( "Sound", "WARNING: Trying to get pitch for a non-playing sound.\n" ));
1156 pitch = ds_get_pitch(channel);
1161 // ---------------------------------------------------------------------------------------
1164 // Set the pitch of a currently playing sound
1166 // parameters: sig => handle to sound, what is returned from snd_play()
1167 // pan => pitch of sound (range: 100 to 100000)
1169 void snd_set_pitch( int sig, int pitch )
1173 if (!ds_initialized) return;
1174 if ( sig < 0 ) return;
1176 channel = ds_get_channel(sig);
1177 if ( channel == -1 ) {
1178 nprintf(( "Sound", "WARNING: Trying to set pitch for a non-playing sound.\n" ));
1182 ds_set_pitch(channel, pitch);
1185 // ---------------------------------------------------------------------------------------
1188 // Determine if a sound is playing
1190 // returns: 1 => sound is currently playing
1191 // 0 => sound is not playing
1193 // parameters: sig => signature of sound, what is returned from snd_play()
1195 int snd_is_playing( int sig )
1197 int channel, is_playing;
1199 if (!ds_initialized)
1205 channel = ds_get_channel(sig);
1206 if ( channel == -1 )
1209 is_playing = ds_is_channel_playing(channel);
1210 if ( is_playing == TRUE ) {
1218 // ---------------------------------------------------------------------------------------
1219 // snd_chg_loop_status()
1221 // Change whether a currently playing song is looping or not
1223 // parameters: sig => handle to sound, what is returned from snd_play()
1224 // loop => whether to start (1) or stop (0) looping
1226 void snd_chg_loop_status(int sig, int loop)
1230 if (!ds_initialized)
1236 channel = ds_get_channel(sig);
1237 if ( channel == -1 ) {
1238 nprintf(( "Sound", "WARNING: Trying to change loop status of a non-playing sound!\n" ));
1242 ds_chg_loop_status(channel, loop);
1245 // ---------------------------------------------------------------------------------------
1248 // Stop all playing sound channels (including looping sounds)
1250 // NOTE: This stops all sounds that are playing from Channels[] sound buffers. It doesn't
1251 // stop every secondary sound buffer in existance
1255 if (!ds_initialized)
1258 ds_stop_channel_all();
1261 // ---------------------------------------------------------------------------------------
1264 // Return the pointer to the DirectSound interface
1269 return (uint)pDirectSound;
1272 // ---------------------------------------------------------------------------------------
1278 if ( !ds_initialized )
1284 // return the time in ms for the duration of the sound
1285 int snd_get_duration(int snd_id)
1290 return Sounds[snd_id].duration;
1294 MONITOR( SoundChannels );
1296 // update the position of the listener for the specific 3D sound API we're
1298 void snd_update_listener(vector *pos, vector *vel, matrix *orient)
1300 MONITOR_INC( SoundChannels, ds_get_number_channels() );
1301 ds3d_update_listener(pos, vel, orient);
1304 // this could probably be optimized a bit
1305 void snd_rewind(int snd_handle, game_snd *gs, float seconds)
1307 float current_time,desired_time;
1309 DWORD current_offset,desired_offset;
1312 if(!snd_is_playing(snd_handle))
1315 snd = &Sounds[gs->id].info;
1317 current_offset = ds_get_play_position(ds_get_channel(snd_handle)); // current offset into the sound
1318 bps = (float)snd->sample_rate * (float)snd->bits; // data rate
1319 current_time = (float)current_offset/bps; // how many seconds we're into the sound
1321 // don't rewind if it'll put us before the beginning of the sound
1322 if(current_time - seconds < 0.0f)
1325 desired_time = current_time - seconds; // where we want to be
1326 desired_offset = (DWORD)(desired_time * bps); // the target
1328 ds_set_position(ds_get_channel(snd_handle),desired_offset);
1331 // this could probably be optimized a bit
1332 void snd_ffwd(int snd_handle, game_snd *gs, float seconds)
1334 if(!snd_is_playing(snd_handle))
1337 float current_time,desired_time;
1339 DWORD current_offset,desired_offset;
1342 if(!snd_is_playing(snd_handle))
1345 snd = &Sounds[gs->id].info;
1347 current_offset = ds_get_play_position(ds_get_channel(snd_handle)); // current offset into the sound
1348 bps = (float)snd->sample_rate * (float)snd->bits; // data rate
1349 current_time = (float)current_offset/bps; // how many seconds we're into the sound
1351 // don't rewind if it'll put us past the end of the sound
1352 if(current_time + seconds > (float)snd->duration)
1355 desired_time = current_time + seconds; // where we want to be
1356 desired_offset = (DWORD)(desired_time * bps); // the target
1358 ds_set_position(ds_get_channel(snd_handle),desired_offset);
1361 // this could probably be optimized a bit
1362 void snd_set_pos(int snd_handle, game_snd *gs, float val,int as_pct)
1364 if(!snd_is_playing(snd_handle))
1369 snd = &Sounds[gs->id].info;
1370 // set position as an absolute from 0 to 1
1372 Assert((val >= 0.0) && (val <= 1.0));
1373 ds_set_position(ds_get_channel(snd_handle),(DWORD)((float)snd->size * val));
1375 // set the position as an absolute # of seconds from the beginning of the sound
1378 Assert(val <= (float)snd->duration/1000.0f);
1379 bps = (float)snd->sample_rate * (float)snd->bits; // data rate
1380 ds_set_position(ds_get_channel(snd_handle),(DWORD)(bps * val));
1384 // Return the number of sounds currently playing
1385 int snd_num_playing()
1387 return ds_get_number_channels();
1390 // Stop the first channel found that is playing a sound
1391 void snd_stop_any_sound()
1395 for ( i = 0; i < 16; i++ ) {
1396 if ( ds_is_channel_playing(i) ) {
1403 // Return the raw sound data for a loaded sound
1405 // input: handle => index into Sounds[] array
1406 // data => allocated mem to hold sound
1408 // exit: 0 => success
1410 int snd_get_data(int handle, char *data)
1412 Assert(handle >= 0 && handle < MAX_SOUNDS);
1413 if ( ds_get_data(Sounds[handle].sid, data) ) {
1420 // return the size of the sound data associated with the sound handle
1421 int snd_size(int handle, int *size)
1423 Assert(handle >= 0 && handle < MAX_SOUNDS);
1424 if ( ds_get_size(Sounds[handle].sid, size) ) {
1431 // retrieve the bits per sample and frequency for a given sound
1432 void snd_get_format(int handle, int *bits_per_sample, int *frequency)
1434 Assert(handle >= 0 && handle < MAX_SOUNDS);
1435 *bits_per_sample = Sounds[handle].info.bits;
1436 *frequency = Sounds[handle].info.sample_rate;
1439 // return the time for the sound to play in milliseconds
1440 int snd_time_remaining(int handle, int bits_per_sample, int frequency)
1442 int channel, is_playing, time_remaining = 0;
1444 if (!ds_initialized)
1450 channel = ds_get_channel(handle);
1451 if ( channel == -1 )
1454 is_playing = ds_is_channel_playing(channel);
1455 if ( !is_playing ) {
1459 int current_offset, max_offset;
1461 current_offset = ds_get_play_position(channel);
1462 max_offset = ds_get_channel_size(channel);
1464 if ( current_offset < max_offset ) {
1465 int bytes_remaining = max_offset - current_offset;
1466 int samples_remaining = bytes_remaining / fl2i(bits_per_sample/8.0f);
1467 time_remaining = fl2i(1000 * samples_remaining/frequency + 0.5f);
1470 // mprintf(("time_remaining: %d\n", time_remaining));
1471 return time_remaining;
1475 // snd_env_ interface
1477 static unsigned long Sound_env_id;
1478 static float Sound_env_volume;
1479 static float Sound_env_damping;
1480 static float Sound_env_decay;
1482 // Set the sound environment
1484 int sound_env_set(sound_env *se)
1486 if (ds_eax_set_all(se->id, se->volume, se->damping, se->decay) == 0) {
1487 Sound_env_id = se->id;
1488 Sound_env_volume = se->volume;
1489 Sound_env_damping = se->damping;
1490 Sound_env_decay = se->decay;
1497 // Get the sound environment
1499 int sound_env_get(sound_env *se)
1501 EAX_REVERBPROPERTIES er;
1503 if (ds_eax_get_all(&er) == 0) {
1504 se->id = er.environment;
1505 se->volume = er.fVolume;
1506 se->decay = er.fDecayTime_sec;
1507 se->damping = er.fDamping;
1514 // Turn off the sound environment
1516 int sound_env_disable()
1519 se.id = SND_ENV_GENERIC;
1527 // Return 1 if EAX can used to set the sound environment, otherwise return 0
1529 int sound_env_supported()
1531 return ds_eax_is_inited();
1534 // Called once per game frame