snd_local.h 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939
  1. /*
  2. ===========================================================================
  3. Doom 3 GPL Source Code
  4. Copyright (C) 1999-2011 id Software LLC, a ZeniMax Media company.
  5. This file is part of the Doom 3 GPL Source Code (?Doom 3 Source Code?).
  6. Doom 3 Source Code is free software: you can redistribute it and/or modify
  7. it under the terms of the GNU General Public License as published by
  8. the Free Software Foundation, either version 3 of the License, or
  9. (at your option) any later version.
  10. Doom 3 Source Code is distributed in the hope that it will be useful,
  11. but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. GNU General Public License for more details.
  14. You should have received a copy of the GNU General Public License
  15. along with Doom 3 Source Code. If not, see <http://www.gnu.org/licenses/>.
  16. In addition, the Doom 3 Source Code is also subject to certain additional terms. You should have received a copy of these additional terms immediately following the terms and conditions of the GNU General Public License which accompanied the Doom 3 Source Code. If not, please request a copy in writing from id Software at the address below.
  17. If you have questions concerning this license or the applicable additional terms, you may contact in writing id Software LLC, c/o ZeniMax Media Inc., Suite 120, Rockville, Maryland 20850 USA.
  18. ===========================================================================
  19. */
  20. #ifndef __SND_LOCAL_H__
  21. #define __SND_LOCAL_H__
  22. // you need the OpenAL headers for build, even if AL is not enabled - http://www.openal.org/
  23. #ifdef _WIN32
  24. #include "../openal/include/al.h"
  25. #include "../openal/include/alc.h"
  26. #include "../openal/idal.h"
  27. // broken OpenAL SDK ?
  28. #define ID_ALCHAR (ALubyte *)
  29. #elif defined( MACOS_X )
  30. #include <OpenAL/al.h>
  31. #include <OpenAL/alc.h>
  32. #define ID_ALCHAR
  33. #else
  34. #include <AL/al.h>
  35. #include <AL/alc.h>
  36. #define ID_ALCHAR
  37. #endif
  38. #include "../openal/include/efxlib.h"
  39. /* bc flite
  40. extern "C"
  41. {
  42. #include "flite.h"
  43. };
  44. */
  45. // demo sound commands
  46. typedef enum {
  47. SCMD_STATE, // followed by a load game state
  48. SCMD_PLACE_LISTENER,
  49. SCMD_ALLOC_EMITTER,
  50. SCMD_FREE,
  51. SCMD_UPDATE,
  52. SCMD_START,
  53. SCMD_MODIFY,
  54. SCMD_STOP,
  55. SCMD_FADE
  56. } soundDemoCommand_t;
  57. const int SOUND_MAX_CHANNELS = 8;
  58. const int SOUND_DECODER_FREE_DELAY = 1000 * MIXBUFFER_SAMPLES / USERCMD_MSEC; // four seconds
  59. const int PRIMARYFREQ = 44100; // samples per second
  60. const float SND_EPSILON = 1.0f / 32768.0f; // if volume is below this, it will always multiply to zero
  61. const int ROOM_SLICES_IN_BUFFER = 10;
  62. class idAudioHardware;
  63. class idAudioBuffer;
  64. class idWaveFile;
  65. class idSoundCache;
  66. class idSoundSample;
  67. class idSampleDecoder;
  68. class idSoundWorldLocal;
  69. /*
  70. ===================================================================================
  71. General extended waveform format structure.
  72. Use this for all NON PCM formats.
  73. ===================================================================================
  74. */
  75. #ifdef WIN32
  76. #pragma pack(1)
  77. #endif
  78. #ifdef __MWERKS__
  79. #pragma pack (push, 1)
  80. #endif
  81. struct waveformatex_s {
  82. word wFormatTag; /* format type */
  83. word nChannels; /* number of channels (i.e. mono, stereo...) */
  84. dword nSamplesPerSec; /* sample rate */
  85. dword nAvgBytesPerSec; /* for buffer estimation */
  86. word nBlockAlign; /* block size of data */
  87. word wBitsPerSample; /* Number of bits per sample of mono data */
  88. word cbSize; /* The count in bytes of the size of
  89. extra information (after cbSize) */
  90. } PACKED;
  91. typedef waveformatex_s waveformatex_t;
  92. /* OLD general waveform format structure (information common to all formats) */
  93. struct waveformat_s {
  94. word wFormatTag; /* format type */
  95. word nChannels; /* number of channels (i.e. mono, stereo, etc.) */
  96. dword nSamplesPerSec; /* sample rate */
  97. dword nAvgBytesPerSec; /* for buffer estimation */
  98. word nBlockAlign; /* block size of data */
  99. } PACKED;
  100. typedef waveformat_s waveformat_t;
  101. /* flags for wFormatTag field of WAVEFORMAT */
  102. enum {
  103. WAVE_FORMAT_TAG_PCM = 1,
  104. WAVE_FORMAT_TAG_OGG = 2
  105. };
  106. /* specific waveform format structure for PCM data */
  107. struct pcmwaveformat_s {
  108. waveformat_t wf;
  109. word wBitsPerSample;
  110. } PACKED;
  111. typedef pcmwaveformat_s pcmwaveformat_t;
  112. #ifndef mmioFOURCC
  113. #define mmioFOURCC( ch0, ch1, ch2, ch3 ) \
  114. ( (dword)(byte)(ch0) | ( (dword)(byte)(ch1) << 8 ) | \
  115. ( (dword)(byte)(ch2) << 16 ) | ( (dword)(byte)(ch3) << 24 ) )
  116. #endif
  117. #define fourcc_riff mmioFOURCC('R', 'I', 'F', 'F')
  118. struct waveformatextensible_s {
  119. waveformatex_t Format;
  120. union {
  121. word wValidBitsPerSample; /* bits of precision */
  122. word wSamplesPerBlock; /* valid if wBitsPerSample==0*/
  123. word wReserved; /* If neither applies, set to zero*/
  124. } Samples;
  125. dword dwChannelMask; /* which channels are */
  126. /* present in stream */
  127. int SubFormat;
  128. } PACKED;
  129. typedef waveformatextensible_s waveformatextensible_t;
  130. typedef dword fourcc;
  131. /* RIFF chunk information data structure */
  132. struct mminfo_s {
  133. fourcc ckid; /* chunk ID */
  134. dword cksize; /* chunk size */
  135. fourcc fccType; /* form type or list type */
  136. dword dwDataOffset; /* offset of data portion of chunk */
  137. } PACKED;
  138. typedef mminfo_s mminfo_t;
  139. #ifdef WIN32
  140. #pragma pack()
  141. #endif
  142. #ifdef __MWERKS__
  143. #pragma pack (pop)
  144. #endif
  145. /*
  146. ===================================================================================
  147. idWaveFile
  148. ===================================================================================
  149. */
  150. class idWaveFile {
  151. public:
  152. idWaveFile( void );
  153. ~idWaveFile( void );
  154. int Open( const char* strFileName, waveformatex_t* pwfx = NULL );
  155. int OpenFromMemory( short* pbData, int ulDataSize, waveformatextensible_t* pwfx );
  156. int Read( byte* pBuffer, int dwSizeToRead, int *pdwSizeRead );
  157. int Seek( int offset );
  158. int Close( void );
  159. int ResetFile( void );
  160. int GetOutputSize( void ) { return mdwSize; }
  161. int GetMemorySize( void ) { return mMemSize; }
  162. waveformatextensible_t mpwfx; // Pointer to waveformatex structure
  163. private:
  164. idFile * mhmmio; // I/O handle for the WAVE
  165. mminfo_t mck; // Multimedia RIFF chunk
  166. mminfo_t mckRiff; // used when opening a WAVE file
  167. dword mdwSize; // size in samples
  168. dword mMemSize; // size of the wave data in memory
  169. dword mseekBase;
  170. ID_TIME_T mfileTime;
  171. bool mbIsReadingFromMemory;
  172. short * mpbData;
  173. short * mpbDataCur;
  174. dword mulDataSize;
  175. void * ogg; // only !NULL when !s_realTimeDecoding
  176. bool isOgg;
  177. private:
  178. int ReadMMIO( void );
  179. int OpenOGG( const char* strFileName, waveformatex_t* pwfx = NULL );
  180. int ReadOGG( byte* pBuffer, int dwSizeToRead, int *pdwSizeRead );
  181. int CloseOGG( void );
  182. };
  183. /*
  184. ===================================================================================
  185. idAudioHardware
  186. ===================================================================================
  187. */
  188. class idAudioHardware {
  189. public:
  190. static idAudioHardware *Alloc();
  191. virtual ~idAudioHardware();
  192. virtual bool Initialize( ) = 0;
  193. virtual bool Lock( void **pDSLockedBuffer, ulong *dwDSLockedBufferSize ) = 0;
  194. virtual bool Unlock( void *pDSLockedBuffer, dword dwDSLockedBufferSize ) = 0;
  195. virtual bool GetCurrentPosition( ulong *pdwCurrentWriteCursor ) = 0;
  196. // try to write as many sound samples to the device as possible without blocking and prepare for a possible new mixing call
  197. // returns wether there is *some* space for writing available
  198. virtual bool Flush( void ) = 0;
  199. virtual void Write( bool flushing ) = 0;
  200. virtual int GetNumberOfSpeakers( void )= 0;
  201. virtual int GetMixBufferSize( void ) = 0;
  202. virtual short* GetMixBuffer( void ) = 0;
  203. };
  204. /*
  205. ===================================================================================
  206. Encapsulates functionality of a DirectSound buffer.
  207. ===================================================================================
  208. */
  209. class idAudioBuffer {
  210. public:
  211. virtual int Play( dword dwPriority=0, dword dwFlags=0 ) = 0;
  212. virtual int Stop( void ) = 0;
  213. virtual int Reset( void ) = 0;
  214. virtual bool IsSoundPlaying( void ) = 0;
  215. virtual void SetVolume( float x ) = 0;
  216. };
  217. /*
  218. ===================================================================================
  219. idSoundEmitterLocal
  220. ===================================================================================
  221. */
  222. typedef enum {
  223. REMOVE_STATUS_INVALID = -1,
  224. REMOVE_STATUS_ALIVE = 0,
  225. REMOVE_STATUS_WAITSAMPLEFINISHED = 1,
  226. REMOVE_STATUS_SAMPLEFINISHED = 2
  227. } removeStatus_t;
  228. class idSoundFade {
  229. public:
  230. int fadeStart44kHz;
  231. int fadeEnd44kHz;
  232. float fadeStartVolume; // in dB
  233. float fadeEndVolume; // in dB
  234. void Clear();
  235. float FadeDbAt44kHz( int current44kHz );
  236. };
  237. class SoundFX {
  238. protected:
  239. bool initialized;
  240. int channel;
  241. int maxlen;
  242. float* buffer;
  243. float continuitySamples[4];
  244. float param;
  245. public:
  246. SoundFX() { channel = 0; buffer = NULL; initialized = false; maxlen = 0; memset( continuitySamples, 0, sizeof( float ) * 4 ); };
  247. virtual ~SoundFX() { if ( buffer ) delete buffer; };
  248. virtual void Initialize() { };
  249. virtual void ProcessSample( float* in, float* out ) = 0;
  250. void SetChannel( int chan ) { channel = chan; };
  251. int GetChannel() { return channel; };
  252. void SetContinuitySamples( float in1, float in2, float out1, float out2 ) { continuitySamples[0] = in1; continuitySamples[1] = in2; continuitySamples[2] = out1; continuitySamples[3] = out2; }; // FIXME?
  253. void GetContinuitySamples( float& in1, float& in2, float& out1, float& out2 ) { in1 = continuitySamples[0]; in2 = continuitySamples[1]; out1 = continuitySamples[2]; out2 = continuitySamples[3]; };
  254. void SetParameter( float val ) { param = val; };
  255. };
  256. class SoundFX_Lowpass : public SoundFX {
  257. public:
  258. virtual void ProcessSample( float* in, float* out );
  259. };
  260. class SoundFX_LowpassFast : public SoundFX {
  261. float freq;
  262. float res;
  263. float a1, a2, a3;
  264. float b1, b2;
  265. public:
  266. virtual void ProcessSample( float* in, float* out );
  267. void SetParms( float p1 = 0, float p2 = 0, float p3 = 0 );
  268. };
  269. class SoundFX_Comb : public SoundFX {
  270. int currentTime;
  271. public:
  272. virtual void Initialize();
  273. virtual void ProcessSample( float* in, float* out );
  274. };
  275. class FracTime {
  276. public:
  277. int time;
  278. float frac;
  279. void Set( int val ) { time = val; frac = 0; };
  280. void Increment( float val ) { frac += val; while ( frac >= 1.f ) { time++; frac--; } };
  281. };
  282. enum {
  283. PLAYBACK_RESET,
  284. PLAYBACK_ADVANCING
  285. };
  286. class idSoundChannel;
  287. class idSlowChannel {
  288. bool active;
  289. const idSoundChannel* chan;
  290. int playbackState;
  291. int triggerOffset;
  292. FracTime newPosition;
  293. int newSampleOffset;
  294. FracTime curPosition;
  295. int curSampleOffset;
  296. SoundFX_LowpassFast lowpass;
  297. // functions
  298. void GenerateSlowChannel( FracTime& playPos, int sampleCount44k, float* finalBuffer );
  299. float GetSlowmoSpeed();
  300. public:
  301. void AttachSoundChannel( const idSoundChannel *chan );
  302. void Reset();
  303. void GatherChannelSamples( int sampleOffset44k, int sampleCount44k, float *dest );
  304. bool IsActive() { return active; };
  305. FracTime GetCurrentPosition() { return curPosition; };
  306. };
  307. class idSoundChannel {
  308. public:
  309. idSoundChannel( void );
  310. ~idSoundChannel( void );
  311. void Clear( void );
  312. void Start( void );
  313. void Stop( void );
  314. void GatherChannelSamples( int sampleOffset44k, int sampleCount44k, float *dest ) const;
  315. void ALStop( void ); // free OpenAL resources if any
  316. bool triggerState;
  317. int trigger44kHzTime; // hardware time sample the channel started
  318. int triggerGame44kHzTime; // game time sample time the channel started
  319. soundShaderParms_t parms; // combines the shader parms and the per-channel overrides
  320. idSoundSample * leadinSample; // if not looped, this is the only sample
  321. s_channelType triggerChannel;
  322. const idSoundShader *soundShader;
  323. idSampleDecoder * decoder;
  324. float diversity;
  325. float lastVolume; // last calculated volume based on distance
  326. float lastV[6]; // last calculated volume for each speaker, so we can smoothly fade
  327. idSoundFade channelFade;
  328. bool triggered;
  329. ALuint openalSource;
  330. ALuint openalStreamingOffset;
  331. ALuint openalStreamingBuffer[3];
  332. ALuint lastopenalStreamingBuffer[3];
  333. bool disallowSlow;
  334. };
  335. class idSoundEmitterLocal : public idSoundEmitter {
  336. public:
  337. idSoundEmitterLocal( void );
  338. virtual ~idSoundEmitterLocal( void );
  339. //----------------------------------------------
  340. // the "time" parameters should be game time in msec, which is used to make queries
  341. // return deterministic values regardless of async buffer scheduling
  342. // a non-immediate free will let all currently playing sounds complete
  343. virtual void Free( bool immediate );
  344. // the parms specified will be the default overrides for all sounds started on this emitter.
  345. // NULL is acceptable for parms
  346. virtual void UpdateEmitter( const idVec3 &origin, int listenerId, const soundShaderParms_t *parms );
  347. // returns the length of the started sound in msec
  348. virtual int StartSound( const idSoundShader *shader, const s_channelType channel, float diversity = 0, int shaderFlags = 0, bool allowSlow = true /* D3XP */ );
  349. // can pass SCHANNEL_ANY
  350. virtual void ModifySound( const s_channelType channel, const soundShaderParms_t *parms );
  351. virtual void StopSound( const s_channelType channel );
  352. virtual void FadeSound( const s_channelType channel, float to, float over );
  353. virtual bool CurrentlyPlaying( void ) const;
  354. // can pass SCHANNEL_ANY
  355. virtual float CurrentAmplitude( void );
  356. // used for save games
  357. virtual int Index( void ) const;
  358. //----------------------------------------------
  359. void Clear( void );
  360. void OverrideParms( const soundShaderParms_t *base, const soundShaderParms_t *over, soundShaderParms_t *out );
  361. void CheckForCompletion( int current44kHzTime );
  362. void Spatialize( idVec3 listenerPos, int listenerArea, idRenderWorld *rw );
  363. idSoundWorldLocal * soundWorld; // the world that holds this emitter
  364. int index; // in world emitter list
  365. removeStatus_t removeStatus;
  366. idVec3 origin;
  367. int listenerId;
  368. soundShaderParms_t parms; // default overrides for all channels
  369. // the following are calculated in UpdateEmitter, and don't need to be archived
  370. float maxDistance; // greatest of all playing channel distances
  371. int lastValidPortalArea; // so an emitter that slides out of the world continues playing
  372. bool playing; // if false, no channel is active
  373. bool hasShakes;
  374. idVec3 spatializedOrigin; // the virtual sound origin, either the real sound origin,
  375. // or a point through a portal chain
  376. float realDistance; // in meters
  377. float distance; // in meters, this may be the straight-line distance, or
  378. // it may go through a chain of portals. If there
  379. // is not an open-portal path, distance will be > maxDistance
  380. // a single soundEmitter can have many channels playing from the same point
  381. idSoundChannel channels[SOUND_MAX_CHANNELS];
  382. idSlowChannel slowChannels[SOUND_MAX_CHANNELS];
  383. idSlowChannel GetSlowChannel( const idSoundChannel *chan );
  384. void SetSlowChannel( const idSoundChannel *chan, idSlowChannel slow );
  385. void ResetSlowChannel( const idSoundChannel *chan );
  386. // this is just used for feedback to the game or rendering system:
  387. // flashing lights and screen shakes. Because the material expression
  388. // evaluation doesn't do common subexpression removal, we cache the
  389. // last generated value
  390. int ampTime;
  391. float amplitude;
  392. };
  393. /*
  394. ===================================================================================
  395. idSoundWorldLocal
  396. ===================================================================================
  397. */
  398. class s_stats {
  399. public:
  400. s_stats( void ) {
  401. rinuse = 0;
  402. runs = 1;
  403. timeinprocess = 0;
  404. missedWindow = 0;
  405. missedUpdateWindow = 0;
  406. activeSounds = 0;
  407. }
  408. int rinuse;
  409. int runs;
  410. int timeinprocess;
  411. int missedWindow;
  412. int missedUpdateWindow;
  413. int activeSounds;
  414. };
  415. typedef struct soundPortalTrace_s {
  416. int portalArea;
  417. const struct soundPortalTrace_s *prevStack;
  418. } soundPortalTrace_t;
  419. class idSoundWorldLocal : public idSoundWorld {
  420. public:
  421. virtual ~idSoundWorldLocal( void );
  422. // call at each map start
  423. virtual void ClearAllSoundEmitters( void );
  424. virtual void StopAllSounds( void );
  425. // get a new emitter that can play sounds in this world
  426. virtual idSoundEmitter *AllocSoundEmitter( void );
  427. // for load games
  428. virtual idSoundEmitter *EmitterForIndex( int index );
  429. // query data from all emitters in the world
  430. virtual float CurrentShakeAmplitudeForPosition( const int time, const idVec3 &listererPosition );
  431. // where is the camera/microphone
  432. // listenerId allows listener-private sounds to be added
  433. virtual void PlaceListener( const idVec3 &origin, const idMat3 &axis, const int listenerId, const int gameTime, const idStr& areaName );
  434. // fade all sounds in the world with a given shader soundClass
  435. // to is in Db (sigh), over is in seconds
  436. virtual void FadeSoundClasses( const int soundClass, const float to, const float over );
  437. // dumps the current state and begins archiving commands
  438. virtual void StartWritingDemo( idDemoFile *demo );
  439. virtual void StopWritingDemo( void );
  440. // read a sound command from a demo file
  441. virtual void ProcessDemoCommand( idDemoFile *readDemo );
  442. // background music
  443. virtual void PlayShaderDirectly( const char *name, int channel = -1 );
  444. // pause and unpause the sound world
  445. virtual void Pause( void );
  446. virtual void UnPause( void );
  447. virtual bool IsPaused( void );
  448. // avidump
  449. virtual void AVIOpen( const char *path, const char *name );
  450. virtual void AVIClose( void );
  451. // SaveGame Support
  452. virtual void WriteToSaveGame( idFile *savefile );
  453. virtual void ReadFromSaveGame( idFile *savefile );
  454. virtual void ReadFromSaveGameSoundChannel( idFile *saveGame, idSoundChannel *ch );
  455. virtual void ReadFromSaveGameSoundShaderParams( idFile *saveGame, soundShaderParms_t *params );
  456. virtual void WriteToSaveGameSoundChannel( idFile *saveGame, idSoundChannel *ch );
  457. virtual void WriteToSaveGameSoundShaderParams( idFile *saveGame, soundShaderParms_t *params );
  458. virtual void SetSlowmo( bool active );
  459. virtual void SetSlowmoSpeed( float speed );
  460. virtual void SetEnviroSuit( bool active );
  461. //=======================================
  462. idSoundWorldLocal( void );
  463. void Shutdown( void );
  464. void Init( idRenderWorld *rw );
  465. void ClearBuffer( void );
  466. // update
  467. void ForegroundUpdate( int currentTime );
  468. void OffsetSoundTime( int offset44kHz );
  469. idSoundEmitterLocal * AllocLocalSoundEmitter();
  470. void CalcEars( int numSpeakers, idVec3 realOrigin, idVec3 listenerPos, idMat3 listenerAxis, float ears[6], float spatialize );
  471. void AddChannelContribution( idSoundEmitterLocal *sound, idSoundChannel *chan,
  472. int current44kHz, int numSpeakers, float *finalMixBuffer );
  473. void MixLoop( int current44kHz, int numSpeakers, float *finalMixBuffer );
  474. void AVIUpdate( void );
  475. void ResolveOrigin( const int stackDepth, const soundPortalTrace_t *prevStack, const int soundArea, const float dist, const idVec3& soundOrigin, idSoundEmitterLocal *def );
  476. float FindAmplitude( idSoundEmitterLocal *sound, const int localTime, const idVec3 *listenerPosition, const s_channelType channel, bool shakesOnly );
  477. //============================================
  478. idRenderWorld * rw; // for portals and debug drawing
  479. idDemoFile * writeDemo; // if not NULL, archive commands here
  480. idMat3 listenerAxis;
  481. idVec3 listenerPos; // position in meters
  482. int listenerPrivateId;
  483. idVec3 listenerQU; // position in "quake units"
  484. int listenerArea;
  485. idStr listenerAreaName;
  486. int listenerEnvironmentID;
  487. int gameMsec;
  488. int game44kHz;
  489. int pause44kHz;
  490. int lastAVI44kHz; // determine when we need to mix and write another block
  491. idList<idSoundEmitterLocal *>emitters;
  492. idSoundFade soundClassFade[SOUND_MAX_CLASSES]; // for global sound fading
  493. // avi stuff
  494. idFile * fpa[6];
  495. idStr aviDemoPath;
  496. idStr aviDemoName;
  497. idSoundEmitterLocal * localSound; // just for playShaderDirectly()
  498. bool slowmoActive;
  499. float slowmoSpeed;
  500. bool enviroSuitActive;
  501. };
  502. /*
  503. ===================================================================================
  504. idSoundSystemLocal
  505. ===================================================================================
  506. */
  507. typedef struct {
  508. ALuint handle;
  509. int startTime;
  510. idSoundChannel *chan;
  511. bool inUse;
  512. bool looping;
  513. bool stereo;
  514. } openalSource_t;
  515. class idSoundSystemLocal : public idSoundSystem {
  516. public:
  517. idSoundSystemLocal( ) {
  518. isInitialized = false;
  519. }
  520. // all non-hardware initialization
  521. virtual void Init( void );
  522. // shutdown routine
  523. virtual void Shutdown( void );
  524. virtual void ClearBuffer( void );
  525. // sound is attached to the window, and must be recreated when the window is changed
  526. virtual bool ShutdownHW( void );
  527. virtual bool InitHW( void );
  528. // async loop, called at 60Hz
  529. virtual int AsyncUpdate( int time );
  530. // async loop, when the sound driver uses a write strategy
  531. virtual int AsyncUpdateWrite( int time );
  532. // direct mixing called from the sound driver thread for OSes that support it
  533. virtual int AsyncMix( int soundTime, float *mixBuffer );
  534. virtual void SetMute( bool mute );
  535. virtual cinData_t ImageForTime( const int milliseconds, const bool waveform );
  536. int GetSoundDecoderInfo( int index, soundDecoderInfo_t &decoderInfo );
  537. // if rw == NULL, no portal occlusion or rendered debugging is available
  538. virtual idSoundWorld *AllocSoundWorld( idRenderWorld *rw );
  539. // specifying NULL will cause silence to be played
  540. virtual void SetPlayingSoundWorld( idSoundWorld *soundWorld );
  541. // some tools, like the sound dialog, may be used in both the game and the editor
  542. // This can return NULL, so check!
  543. virtual idSoundWorld *GetPlayingSoundWorld( void );
  544. virtual void BeginLevelLoad( void );
  545. virtual void EndLevelLoad( const char *mapString );
  546. virtual void PrintMemInfo( MemInfo_t *mi );
  547. virtual int IsEAXAvailable( void );
  548. //bc flite
  549. //virtual void SynthesizeSpeech( const char *input );
  550. //-------------------------
  551. int GetCurrent44kHzTime( void ) const;
  552. float dB2Scale( const float val ) const;
  553. int SamplesToMilliseconds( int samples ) const;
  554. int MillisecondsToSamples( int ms ) const;
  555. void DoEnviroSuit( float* samples, int numSamples, int numSpeakers );
  556. ALuint AllocOpenALSource( idSoundChannel *chan, bool looping, bool stereo );
  557. void FreeOpenALSource( ALuint handle );
  558. idAudioHardware * snd_audio_hw;
  559. idSoundCache * soundCache;
  560. idSoundWorldLocal * currentSoundWorld; // the one to mix each async tic
  561. int olddwCurrentWritePos; // statistics
  562. int buffers; // statistics
  563. int CurrentSoundTime; // set by the async thread and only used by the main thread
  564. unsigned int nextWriteBlock;
  565. float realAccum[6*MIXBUFFER_SAMPLES+16];
  566. float * finalMixBuffer; // points inside realAccum at a 16 byte aligned boundary
  567. bool isInitialized;
  568. bool muted;
  569. bool shutdown;
  570. s_stats soundStats; // NOTE: updated throughout the code, not displayed anywhere
  571. int meterTops[256];
  572. int meterTopsTime[256];
  573. dword * graph;
  574. float volumesDB[1200]; // dB to float volume conversion
  575. idList<SoundFX*> fxList;
  576. ALCdevice *openalDevice;
  577. ALCcontext *openalContext;
  578. ALsizei openalSourceCount;
  579. openalSource_t openalSources[256];
  580. EAXSet alEAXSet;
  581. EAXGet alEAXGet;
  582. EAXSetBufferMode alEAXSetBufferMode;
  583. EAXGetBufferMode alEAXGetBufferMode;
  584. idEFXFile EFXDatabase;
  585. bool efxloaded;
  586. // latches
  587. static bool useOpenAL;
  588. static bool useEAXReverb;
  589. // mark available during initialization, or through an explicit test
  590. static int EAXAvailable;
  591. static idCVar s_noSound;
  592. static idCVar s_quadraticFalloff;
  593. static idCVar s_drawSounds;
  594. static idCVar s_minVolume6;
  595. static idCVar s_dotbias6;
  596. static idCVar s_minVolume2;
  597. static idCVar s_dotbias2;
  598. static idCVar s_spatializationDecay;
  599. static idCVar s_showStartSound;
  600. static idCVar s_maxSoundsPerShader;
  601. static idCVar s_reverse;
  602. static idCVar s_showLevelMeter;
  603. static idCVar s_meterTopTime;
  604. static idCVar s_volume;
  605. static idCVar s_constantAmplitude;
  606. static idCVar s_playDefaultSound;
  607. static idCVar s_useOcclusion;
  608. static idCVar s_subFraction;
  609. static idCVar s_globalFraction;
  610. static idCVar s_doorDistanceAdd;
  611. static idCVar s_singleEmitter;
  612. static idCVar s_numberOfSpeakers;
  613. static idCVar s_force22kHz;
  614. static idCVar s_clipVolumes;
  615. static idCVar s_realTimeDecoding;
  616. static idCVar s_libOpenAL;
  617. static idCVar s_useOpenAL;
  618. static idCVar s_useEAXReverb;
  619. static idCVar s_muteEAXReverb;
  620. static idCVar s_decompressionLimit;
  621. static idCVar s_slowAttenuate;
  622. static idCVar s_postprocessing;
  623. static idCVar s_enviroSuitCutoffFreq;
  624. static idCVar s_enviroSuitCutoffQ;
  625. static idCVar s_enviroSuitSkipLowpass;
  626. static idCVar s_enviroSuitSkipReverb;
  627. static idCVar s_reverbTime;
  628. static idCVar s_reverbFeedback;
  629. static idCVar s_enviroSuitVolumeScale;
  630. static idCVar s_skipHelltimeFX;
  631. };
  632. extern idSoundSystemLocal soundSystemLocal;
  633. /*
  634. ===================================================================================
  635. This class holds the actual wavefile bitmap, size, and info.
  636. ===================================================================================
  637. */
  638. const int SCACHE_SIZE = MIXBUFFER_SAMPLES*20; // 1/2 of a second (aroundabout)
  639. class idSoundSample {
  640. public:
  641. idSoundSample();
  642. ~idSoundSample();
  643. idStr name; // name of the sample file
  644. ID_TIME_T timestamp; // the most recent of all images used in creation, for reloadImages command
  645. waveformatex_t objectInfo; // what are we caching
  646. int objectSize; // size of waveform in samples, excludes the header
  647. int objectMemSize; // object size in memory
  648. byte * nonCacheData; // if it's not cached
  649. byte * amplitudeData; // precomputed min,max amplitude pairs
  650. ALuint openalBuffer; // openal buffer
  651. bool hardwareBuffer;
  652. bool defaultSound;
  653. bool onDemand;
  654. bool purged;
  655. bool levelLoadReferenced; // so we can tell which samples aren't needed any more
  656. int LengthIn44kHzSamples() const;
  657. ID_TIME_T GetNewTimeStamp( void ) const;
  658. void MakeDefault(); // turns it into a beep
  659. void Load(); // loads the current sound based on name
  660. void Reload( bool force ); // reloads if timestamp has changed, or always if force
  661. void PurgeSoundSample(); // frees all data
  662. void CheckForDownSample(); // down sample if required
  663. bool FetchFromCache( int offset, const byte **output, int *position, int *size, const bool allowIO );
  664. };
  665. /*
  666. ===================================================================================
  667. Sound sample decoder.
  668. ===================================================================================
  669. */
  670. class idSampleDecoder {
  671. public:
  672. static void Init( void );
  673. static void Shutdown( void );
  674. static idSampleDecoder *Alloc( void );
  675. static void Free( idSampleDecoder *decoder );
  676. static int GetNumUsedBlocks( void );
  677. static int GetUsedBlockMemory( void );
  678. virtual ~idSampleDecoder( void ) {}
  679. virtual void Decode( idSoundSample *sample, int sampleOffset44k, int sampleCount44k, float *dest ) = 0;
  680. virtual void ClearDecoder( void ) = 0;
  681. virtual idSoundSample * GetSample( void ) const = 0;
  682. virtual int GetLastDecodeTime( void ) const = 0;
  683. };
  684. /*
  685. ===================================================================================
  686. The actual sound cache.
  687. ===================================================================================
  688. */
  689. class idSoundCache {
  690. public:
  691. idSoundCache();
  692. ~idSoundCache();
  693. idSoundSample * FindSound( const idStr &fname, bool loadOnDemandOnly );
  694. const int GetNumObjects( void ) { return listCache.Num(); }
  695. const idSoundSample * GetObject( const int index ) const;
  696. void ReloadSounds( bool force );
  697. void BeginLevelLoad();
  698. void EndLevelLoad();
  699. void PrintMemInfo( MemInfo_t *mi );
  700. private:
  701. bool insideLevelLoad;
  702. idList<idSoundSample*> listCache;
  703. };
  704. //for use with Flite streaming. (Brian)
  705. //int example_audio_stream_chunk( const cst_wave *w, int start, int size, int last, void *user );
  706. #endif /* !__SND_LOCAL_H__ */