snd_decoder.cpp 14 KB

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