snd_decoder.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576
  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. #include "../idlib/precompiled.h"
  21. #pragma hdrstop
  22. #include "snd_local.h"
  23. #include "OggVorbis/vorbis/codec.h"
  24. #include "OggVorbis/vorbis/vorbisfile.h"
  25. /*
  26. ===================================================================================
  27. Thread safe decoder memory allocator.
  28. Each OggVorbis decoder consumes about 150kB of memory.
  29. ===================================================================================
  30. */
  31. idDynamicBlockAlloc<byte, 1<<20, 128> decoderMemoryAllocator;
  32. const int MIN_OGGVORBIS_MEMORY = 768 * 1024;
  33. extern "C" {
  34. void *_decoder_malloc( size_t size );
  35. void *_decoder_calloc( size_t num, size_t size );
  36. void *_decoder_realloc( void *memblock, size_t size );
  37. void _decoder_free( void *memblock );
  38. }
  39. void *_decoder_malloc( size_t size ) {
  40. void *ptr = decoderMemoryAllocator.Alloc( size );
  41. assert( size == 0 || ptr != NULL );
  42. return ptr;
  43. }
  44. void *_decoder_calloc( size_t num, size_t size ) {
  45. void *ptr = decoderMemoryAllocator.Alloc( num * size );
  46. assert( ( num * size ) == 0 || ptr != NULL );
  47. memset( ptr, 0, num * size );
  48. return ptr;
  49. }
  50. void *_decoder_realloc( void *memblock, size_t size ) {
  51. void *ptr = decoderMemoryAllocator.Resize( (byte *)memblock, size );
  52. assert( size == 0 || ptr != NULL );
  53. return ptr;
  54. }
  55. void _decoder_free( void *memblock ) {
  56. decoderMemoryAllocator.Free( (byte *)memblock );
  57. }
  58. /*
  59. ===================================================================================
  60. OggVorbis file loading/decoding.
  61. ===================================================================================
  62. */
  63. /*
  64. ====================
  65. FS_ReadOGG
  66. ====================
  67. */
  68. size_t FS_ReadOGG( void *dest, size_t size1, size_t size2, void *fh ) {
  69. idFile *f = reinterpret_cast<idFile *>(fh);
  70. return f->Read( dest, size1 * size2 );
  71. }
  72. /*
  73. ====================
  74. FS_SeekOGG
  75. ====================
  76. */
  77. int FS_SeekOGG( void *fh, ogg_int64_t to, int type ) {
  78. fsOrigin_t retype = FS_SEEK_SET;
  79. if ( type == SEEK_CUR ) {
  80. retype = FS_SEEK_CUR;
  81. } else if ( type == SEEK_END ) {
  82. retype = FS_SEEK_END;
  83. } else if ( type == SEEK_SET ) {
  84. retype = FS_SEEK_SET;
  85. } else {
  86. common->FatalError( "fs_seekOGG: seek without type\n" );
  87. }
  88. idFile *f = reinterpret_cast<idFile *>(fh);
  89. return f->Seek( to, retype );
  90. }
  91. /*
  92. ====================
  93. FS_CloseOGG
  94. ====================
  95. */
  96. int FS_CloseOGG( void *fh ) {
  97. return 0;
  98. }
  99. /*
  100. ====================
  101. FS_TellOGG
  102. ====================
  103. */
  104. long FS_TellOGG( void *fh ) {
  105. idFile *f = reinterpret_cast<idFile *>(fh);
  106. return f->Tell();
  107. }
  108. /*
  109. ====================
  110. ov_openFile
  111. ====================
  112. */
  113. int ov_openFile( idFile *f, OggVorbis_File *vf ) {
  114. ov_callbacks callbacks;
  115. memset( vf, 0, sizeof( OggVorbis_File ) );
  116. callbacks.read_func = FS_ReadOGG;
  117. callbacks.seek_func = FS_SeekOGG;
  118. callbacks.close_func = FS_CloseOGG;
  119. callbacks.tell_func = FS_TellOGG;
  120. return ov_open_callbacks((void *)f, vf, NULL, -1, callbacks);
  121. }
  122. /*
  123. ====================
  124. idWaveFile::OpenOGG
  125. ====================
  126. */
  127. int idWaveFile::OpenOGG( const char* strFileName, waveformatex_t *pwfx ) {
  128. OggVorbis_File *ov;
  129. memset( pwfx, 0, sizeof( waveformatex_t ) );
  130. mhmmio = fileSystem->OpenFileRead( strFileName );
  131. if ( !mhmmio ) {
  132. return -1;
  133. }
  134. Sys_EnterCriticalSection( CRITICAL_SECTION_ONE );
  135. ov = new OggVorbis_File;
  136. if( ov_openFile( mhmmio, ov ) < 0 ) {
  137. delete ov;
  138. Sys_LeaveCriticalSection( CRITICAL_SECTION_ONE );
  139. fileSystem->CloseFile( mhmmio );
  140. mhmmio = NULL;
  141. return -1;
  142. }
  143. mfileTime = mhmmio->Timestamp();
  144. vorbis_info *vi = ov_info( ov, -1 );
  145. mpwfx.Format.nSamplesPerSec = vi->rate;
  146. mpwfx.Format.nChannels = vi->channels;
  147. mpwfx.Format.wBitsPerSample = sizeof(short) * 8;
  148. mdwSize = ov_pcm_total( ov, -1 ) * vi->channels; // pcm samples * num channels
  149. mbIsReadingFromMemory = false;
  150. if ( idSoundSystemLocal::s_realTimeDecoding.GetBool() ) {
  151. ov_clear( ov );
  152. fileSystem->CloseFile( mhmmio );
  153. mhmmio = NULL;
  154. delete ov;
  155. mpwfx.Format.wFormatTag = WAVE_FORMAT_TAG_OGG;
  156. mhmmio = fileSystem->OpenFileRead( strFileName );
  157. mMemSize = mhmmio->Length();
  158. } else {
  159. ogg = ov;
  160. mpwfx.Format.wFormatTag = WAVE_FORMAT_TAG_PCM;
  161. mMemSize = mdwSize * sizeof( short );
  162. }
  163. memcpy( pwfx, &mpwfx, sizeof( waveformatex_t ) );
  164. Sys_LeaveCriticalSection( CRITICAL_SECTION_ONE );
  165. isOgg = true;
  166. return 0;
  167. }
  168. /*
  169. ====================
  170. idWaveFile::ReadOGG
  171. ====================
  172. */
  173. int idWaveFile::ReadOGG( byte* pBuffer, int dwSizeToRead, int *pdwSizeRead ) {
  174. int total = dwSizeToRead;
  175. char *bufferPtr = (char *)pBuffer;
  176. OggVorbis_File *ov = (OggVorbis_File *) ogg;
  177. do {
  178. int ret = ov_read( ov, bufferPtr, total >= 4096 ? 4096 : total, Swap_IsBigEndian(), 2, 1, &ov->stream );
  179. if ( ret == 0 ) {
  180. break;
  181. }
  182. if ( ret < 0 ) {
  183. return -1;
  184. }
  185. bufferPtr += ret;
  186. total -= ret;
  187. } while( total > 0 );
  188. dwSizeToRead = (byte *)bufferPtr - pBuffer;
  189. if ( pdwSizeRead != NULL ) {
  190. *pdwSizeRead = dwSizeToRead;
  191. }
  192. return dwSizeToRead;
  193. }
  194. /*
  195. ====================
  196. idWaveFile::CloseOGG
  197. ====================
  198. */
  199. int idWaveFile::CloseOGG( void ) {
  200. OggVorbis_File *ov = (OggVorbis_File *) ogg;
  201. if ( ov != NULL ) {
  202. Sys_EnterCriticalSection( CRITICAL_SECTION_ONE );
  203. ov_clear( ov );
  204. delete ov;
  205. Sys_LeaveCriticalSection( CRITICAL_SECTION_ONE );
  206. fileSystem->CloseFile( mhmmio );
  207. mhmmio = NULL;
  208. ogg = NULL;
  209. return 0;
  210. }
  211. return -1;
  212. }
  213. /*
  214. ===================================================================================
  215. idSampleDecoderLocal
  216. ===================================================================================
  217. */
  218. class idSampleDecoderLocal : public idSampleDecoder {
  219. public:
  220. virtual void Decode( idSoundSample *sample, int sampleOffset44k, int sampleCount44k, float *dest );
  221. virtual void ClearDecoder( void );
  222. virtual idSoundSample * GetSample( void ) const;
  223. virtual int GetLastDecodeTime( void ) const;
  224. void Clear( void );
  225. int DecodePCM( idSoundSample *sample, int sampleOffset44k, int sampleCount44k, float *dest );
  226. int DecodeOGG( idSoundSample *sample, int sampleOffset44k, int sampleCount44k, float *dest );
  227. private:
  228. bool failed; // set if decoding failed
  229. int lastFormat; // last format being decoded
  230. idSoundSample * lastSample; // last sample being decoded
  231. int lastSampleOffset; // last offset into the decoded sample
  232. int lastDecodeTime; // last time decoding sound
  233. idFile_Memory file; // encoded file in memory
  234. OggVorbis_File ogg; // OggVorbis file
  235. };
  236. idBlockAlloc<idSampleDecoderLocal, 64> sampleDecoderAllocator;
  237. /*
  238. ====================
  239. idSampleDecoder::Init
  240. ====================
  241. */
  242. void idSampleDecoder::Init( void ) {
  243. decoderMemoryAllocator.Init();
  244. decoderMemoryAllocator.SetLockMemory( true );
  245. decoderMemoryAllocator.SetFixedBlocks( idSoundSystemLocal::s_realTimeDecoding.GetBool() ? 10 : 1 );
  246. }
  247. /*
  248. ====================
  249. idSampleDecoder::Shutdown
  250. ====================
  251. */
  252. void idSampleDecoder::Shutdown( void ) {
  253. decoderMemoryAllocator.Shutdown();
  254. sampleDecoderAllocator.Shutdown();
  255. }
  256. /*
  257. ====================
  258. idSampleDecoder::Alloc
  259. ====================
  260. */
  261. idSampleDecoder *idSampleDecoder::Alloc( void ) {
  262. idSampleDecoderLocal *decoder = sampleDecoderAllocator.Alloc();
  263. decoder->Clear();
  264. return decoder;
  265. }
  266. /*
  267. ====================
  268. idSampleDecoder::Free
  269. ====================
  270. */
  271. void idSampleDecoder::Free( idSampleDecoder *decoder ) {
  272. idSampleDecoderLocal *localDecoder = static_cast<idSampleDecoderLocal *>( decoder );
  273. localDecoder->ClearDecoder();
  274. sampleDecoderAllocator.Free( localDecoder );
  275. }
  276. /*
  277. ====================
  278. idSampleDecoder::GetNumUsedBlocks
  279. ====================
  280. */
  281. int idSampleDecoder::GetNumUsedBlocks( void ) {
  282. return decoderMemoryAllocator.GetNumUsedBlocks();
  283. }
  284. /*
  285. ====================
  286. idSampleDecoder::GetUsedBlockMemory
  287. ====================
  288. */
  289. int idSampleDecoder::GetUsedBlockMemory( void ) {
  290. return decoderMemoryAllocator.GetUsedBlockMemory();
  291. }
  292. /*
  293. ====================
  294. idSampleDecoderLocal::Clear
  295. ====================
  296. */
  297. void idSampleDecoderLocal::Clear( void ) {
  298. failed = false;
  299. lastFormat = WAVE_FORMAT_TAG_PCM;
  300. lastSample = NULL;
  301. lastSampleOffset = 0;
  302. lastDecodeTime = 0;
  303. }
  304. /*
  305. ====================
  306. idSampleDecoderLocal::ClearDecoder
  307. ====================
  308. */
  309. void idSampleDecoderLocal::ClearDecoder( void ) {
  310. Sys_EnterCriticalSection( CRITICAL_SECTION_ONE );
  311. switch( lastFormat ) {
  312. case WAVE_FORMAT_TAG_PCM: {
  313. break;
  314. }
  315. case WAVE_FORMAT_TAG_OGG: {
  316. ov_clear( &ogg );
  317. memset( &ogg, 0, sizeof( ogg ) );
  318. break;
  319. }
  320. }
  321. Clear();
  322. Sys_LeaveCriticalSection( CRITICAL_SECTION_ONE );
  323. }
  324. /*
  325. ====================
  326. idSampleDecoderLocal::GetSample
  327. ====================
  328. */
  329. idSoundSample *idSampleDecoderLocal::GetSample( void ) const {
  330. return lastSample;
  331. }
  332. /*
  333. ====================
  334. idSampleDecoderLocal::GetLastDecodeTime
  335. ====================
  336. */
  337. int idSampleDecoderLocal::GetLastDecodeTime( void ) const {
  338. return lastDecodeTime;
  339. }
  340. /*
  341. ====================
  342. idSampleDecoderLocal::Decode
  343. ====================
  344. */
  345. void idSampleDecoderLocal::Decode( idSoundSample *sample, int sampleOffset44k, int sampleCount44k, float *dest ) {
  346. int readSamples44k;
  347. if ( sample->objectInfo.wFormatTag != lastFormat || sample != lastSample ) {
  348. ClearDecoder();
  349. }
  350. lastDecodeTime = soundSystemLocal.CurrentSoundTime;
  351. if ( failed ) {
  352. memset( dest, 0, sampleCount44k * sizeof( dest[0] ) );
  353. return;
  354. }
  355. // samples can be decoded both from the sound thread and the main thread for shakes
  356. Sys_EnterCriticalSection( CRITICAL_SECTION_ONE );
  357. switch( sample->objectInfo.wFormatTag ) {
  358. case WAVE_FORMAT_TAG_PCM: {
  359. readSamples44k = DecodePCM( sample, sampleOffset44k, sampleCount44k, dest );
  360. break;
  361. }
  362. case WAVE_FORMAT_TAG_OGG: {
  363. readSamples44k = DecodeOGG( sample, sampleOffset44k, sampleCount44k, dest );
  364. break;
  365. }
  366. default: {
  367. readSamples44k = 0;
  368. break;
  369. }
  370. }
  371. Sys_LeaveCriticalSection( CRITICAL_SECTION_ONE );
  372. if ( readSamples44k < sampleCount44k ) {
  373. memset( dest + readSamples44k, 0, ( sampleCount44k - readSamples44k ) * sizeof( dest[0] ) );
  374. }
  375. }
  376. /*
  377. ====================
  378. idSampleDecoderLocal::DecodePCM
  379. ====================
  380. */
  381. int idSampleDecoderLocal::DecodePCM( idSoundSample *sample, int sampleOffset44k, int sampleCount44k, float *dest ) {
  382. const byte *first;
  383. int pos, size, readSamples;
  384. lastFormat = WAVE_FORMAT_TAG_PCM;
  385. lastSample = sample;
  386. int shift = 22050 / sample->objectInfo.nSamplesPerSec;
  387. int sampleOffset = sampleOffset44k >> shift;
  388. int sampleCount = sampleCount44k >> shift;
  389. if ( sample->nonCacheData == NULL ) {
  390. //BC uh should I not ignore this? keeps crashing after exiting out of satsuma level.
  391. //assert( false ); // this should never happen ( note: I've seen that happen with the main thread down in idGameLocal::MapClear clearing entities - TTimo )
  392. failed = true;
  393. return 0;
  394. }
  395. if ( !sample->FetchFromCache( sampleOffset * sizeof( short ), &first, &pos, &size, false ) ) {
  396. failed = true;
  397. return 0;
  398. }
  399. if ( size - pos < sampleCount * sizeof( short ) ) {
  400. readSamples = ( size - pos ) / sizeof( short );
  401. } else {
  402. readSamples = sampleCount;
  403. }
  404. // duplicate samples for 44kHz output
  405. SIMDProcessor->UpSamplePCMTo44kHz( dest, (const short *)(first+pos), readSamples, sample->objectInfo.nSamplesPerSec, sample->objectInfo.nChannels );
  406. return ( readSamples << shift );
  407. }
  408. /*
  409. ====================
  410. idSampleDecoderLocal::DecodeOGG
  411. ====================
  412. */
  413. int idSampleDecoderLocal::DecodeOGG( idSoundSample *sample, int sampleOffset44k, int sampleCount44k, float *dest ) {
  414. int readSamples, totalSamples;
  415. int shift = 22050 / sample->objectInfo.nSamplesPerSec;
  416. int sampleOffset = sampleOffset44k >> shift;
  417. int sampleCount = sampleCount44k >> shift;
  418. // open OGG file if not yet opened
  419. if ( lastSample == NULL ) {
  420. // make sure there is enough space for another decoder
  421. if ( decoderMemoryAllocator.GetFreeBlockMemory() < MIN_OGGVORBIS_MEMORY ) {
  422. return 0;
  423. }
  424. if ( sample->nonCacheData == NULL ) {
  425. assert( false ); // this should never happen
  426. failed = true;
  427. return 0;
  428. }
  429. file.SetData( (const char *)sample->nonCacheData, sample->objectMemSize );
  430. if ( ov_openFile( &file, &ogg ) < 0 ) {
  431. failed = true;
  432. return 0;
  433. }
  434. lastFormat = WAVE_FORMAT_TAG_OGG;
  435. lastSample = sample;
  436. }
  437. // seek to the right offset if necessary
  438. if ( sampleOffset != lastSampleOffset ) {
  439. if ( ov_pcm_seek( &ogg, sampleOffset / sample->objectInfo.nChannels ) != 0 ) {
  440. failed = true;
  441. return 0;
  442. }
  443. }
  444. lastSampleOffset = sampleOffset;
  445. // decode OGG samples
  446. totalSamples = sampleCount;
  447. readSamples = 0;
  448. do {
  449. float **samples;
  450. int ret = ov_read_float( &ogg, &samples, totalSamples / sample->objectInfo.nChannels, &ogg.stream );
  451. if ( ret == 0 ) {
  452. failed = true;
  453. break;
  454. }
  455. if ( ret < 0 ) {
  456. failed = true;
  457. return 0;
  458. }
  459. ret *= sample->objectInfo.nChannels;
  460. SIMDProcessor->UpSampleOGGTo44kHz( dest + ( readSamples << shift ), samples, ret, sample->objectInfo.nSamplesPerSec, sample->objectInfo.nChannels );
  461. readSamples += ret;
  462. totalSamples -= ret;
  463. } while( totalSamples > 0 );
  464. lastSampleOffset += readSamples;
  465. return ( readSamples << shift );
  466. }