Team Fortress 2 Source Code as on 22/4/2020
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

469 lines
13 KiB

  1. //========= Copyright Valve Corporation, All rights reserved. ============//
  2. //
  3. // Purpose:
  4. //
  5. //=====================================================================================//
  6. #include "audio_pch.h"
  7. // memdbgon must be the last include file in a .cpp file!!!
  8. #include "tier0/memdbgon.h"
  9. // max size of ADPCM block in bytes
  10. #define MAX_BLOCK_SIZE 4096
  11. //-----------------------------------------------------------------------------
  12. // Purpose: Mixer for ADPCM encoded audio
  13. //-----------------------------------------------------------------------------
  14. class CAudioMixerWaveADPCM : public CAudioMixerWave
  15. {
  16. public:
  17. CAudioMixerWaveADPCM( IWaveData *data );
  18. ~CAudioMixerWaveADPCM( void );
  19. virtual void Mix( IAudioDevice *pDevice, channel_t *pChannel, void *pData, int outputOffset, int inputOffset, fixedint fracRate, int outCount, int timecompress );
  20. virtual int GetOutputData( void **pData, int sampleCount, char copyBuf[AUDIOSOURCE_COPYBUF_SIZE] );
  21. // need to override this to fixup blocks
  22. void SetSampleStart( int newPosition );
  23. virtual int GetMixSampleSize() { return CalcSampleSize( 16, NumChannels() ); }
  24. private:
  25. bool DecodeBlock( void );
  26. int NumChannels( void );
  27. void DecompressBlockMono( short *pOut, const char *pIn, int count );
  28. void DecompressBlockStereo( short *pOut, const char *pIn, int count );
  29. const ADPCMWAVEFORMAT *m_pFormat;
  30. const ADPCMCOEFSET *m_pCoefficients;
  31. short *m_pSamples;
  32. int m_sampleCount;
  33. int m_samplePosition;
  34. int m_blockSize;
  35. int m_offset;
  36. int m_totalBytes;
  37. };
  38. CAudioMixerWaveADPCM::CAudioMixerWaveADPCM( IWaveData *data ) : CAudioMixerWave( data )
  39. {
  40. m_pSamples = NULL;
  41. m_sampleCount = 0;
  42. m_samplePosition = 0;
  43. m_offset = 0;
  44. CAudioSourceWave &source = reinterpret_cast<CAudioSourceWave &>(m_pData->Source());
  45. #ifdef _DEBUG
  46. CAudioSource *pSource = NULL;
  47. pSource = &m_pData->Source();
  48. Assert( dynamic_cast<CAudioSourceWave *>(pSource) != NULL );
  49. #endif
  50. m_pFormat = (const ADPCMWAVEFORMAT *)source.GetHeader();
  51. if ( m_pFormat )
  52. {
  53. m_pCoefficients = (ADPCMCOEFSET *)((char *)m_pFormat + sizeof(WAVEFORMATEX) + 4);
  54. // create the decode buffer
  55. m_pSamples = new short[m_pFormat->wSamplesPerBlock * m_pFormat->wfx.nChannels];
  56. // number of bytes for samples
  57. m_blockSize = ((m_pFormat->wSamplesPerBlock - 2) * m_pFormat->wfx.nChannels ) / 2;
  58. // size of channel header
  59. m_blockSize += 7 * m_pFormat->wfx.nChannels;
  60. Assert( m_blockSize < MAX_BLOCK_SIZE );
  61. m_totalBytes = source.DataSize();
  62. }
  63. }
  64. CAudioMixerWaveADPCM::~CAudioMixerWaveADPCM( void )
  65. {
  66. delete[] m_pSamples;
  67. }
  68. int CAudioMixerWaveADPCM::NumChannels( void )
  69. {
  70. if ( m_pFormat )
  71. {
  72. return m_pFormat->wfx.nChannels;
  73. }
  74. return 0;
  75. }
  76. void CAudioMixerWaveADPCM::Mix( IAudioDevice *pDevice, channel_t *pChannel, void *pData, int outputOffset, int inputOffset, fixedint fracRate, int outCount, int timecompress )
  77. {
  78. if ( NumChannels() == 1 )
  79. pDevice->Mix16Mono( pChannel, (short *)pData, outputOffset, inputOffset, fracRate, outCount, timecompress );
  80. else
  81. pDevice->Mix16Stereo( pChannel, (short *)pData, outputOffset, inputOffset, fracRate, outCount, timecompress );
  82. }
  83. static int error_sign_lut[] = { 0, 1, 2, 3, 4, 5, 6, 7, -8, -7, -6, -5, -4, -3, -2, -1 };
  84. static int error_coefficients_lut[] = { 230, 230, 230, 230, 307, 409, 512, 614,
  85. 768, 614, 512, 409, 307, 230, 230, 230 };
  86. //-----------------------------------------------------------------------------
  87. // Purpose: ADPCM decompress a single block of 1-channel audio
  88. // Input : *pOut - output buffer 16-bit
  89. // *pIn - input block
  90. // count - number of samples to decode (to support partial blocks)
  91. //-----------------------------------------------------------------------------
  92. void CAudioMixerWaveADPCM::DecompressBlockMono( short *pOut, const char *pIn, int count )
  93. {
  94. int pred = *pIn++;
  95. int co1 = m_pCoefficients[pred].iCoef1;
  96. int co2 = m_pCoefficients[pred].iCoef2;
  97. // read initial delta
  98. int delta = *((short *)pIn);
  99. pIn += 2;
  100. // read initial samples for prediction
  101. int samp1 = *((short *)pIn);
  102. pIn += 2;
  103. int samp2 = *((short *)pIn);
  104. pIn += 2;
  105. // write out the initial samples (stored in reverse order)
  106. *pOut++ = (short)samp2;
  107. *pOut++ = (short)samp1;
  108. // subtract the 2 samples in the header
  109. count -= 2;
  110. // this is a toggle to read nibbles, first nibble is high
  111. int high = 1;
  112. int error, sample=0;
  113. // now process the block
  114. while ( count )
  115. {
  116. // read the error nibble from the input stream
  117. if ( high )
  118. {
  119. sample = (unsigned char) (*pIn++);
  120. // high nibble
  121. error = sample >> 4;
  122. // cache low nibble for next read
  123. sample = sample & 0xf;
  124. // Next read is from cache, not stream
  125. high = 0;
  126. }
  127. else
  128. {
  129. // stored in previous read (low nibble)
  130. error = sample;
  131. // next read is from stream
  132. high = 1;
  133. }
  134. // convert to signed with LUT
  135. int errorSign = error_sign_lut[error];
  136. // interpolate the new sample
  137. int predSample = (samp1 * co1) + (samp2 * co2);
  138. // coefficients are fixed point 8-bit, so shift back to 16-bit integer
  139. predSample >>= 8;
  140. // Add in current error estimate
  141. predSample += (errorSign * delta);
  142. // Correct error estimate
  143. delta = (delta * error_coefficients_lut[error]) >> 8;
  144. // Clamp error estimate
  145. if ( delta < 16 )
  146. delta = 16;
  147. // clamp
  148. if ( predSample > 32767L )
  149. predSample = 32767L;
  150. else if ( predSample < -32768L )
  151. predSample = -32768L;
  152. // output
  153. *pOut++ = (short)predSample;
  154. // move samples over
  155. samp2 = samp1;
  156. samp1 = predSample;
  157. count--;
  158. }
  159. }
  160. //-----------------------------------------------------------------------------
  161. // Purpose: Decode a single block of stereo ADPCM audio
  162. // Input : *pOut - 16-bit output buffer
  163. // *pIn - ADPCM encoded block data
  164. // count - number of sample pairs to decode
  165. //-----------------------------------------------------------------------------
  166. void CAudioMixerWaveADPCM::DecompressBlockStereo( short *pOut, const char *pIn, int count )
  167. {
  168. int pred[2], co1[2], co2[2];
  169. int i;
  170. for ( i = 0; i < 2; i++ )
  171. {
  172. pred[i] = *pIn++;
  173. co1[i] = m_pCoefficients[pred[i]].iCoef1;
  174. co2[i] = m_pCoefficients[pred[i]].iCoef2;
  175. }
  176. int delta[2], samp1[2], samp2[2];
  177. for ( i = 0; i < 2; i++, pIn += 2 )
  178. {
  179. // read initial delta
  180. delta[i] = *((short *)pIn);
  181. }
  182. // read initial samples for prediction
  183. for ( i = 0; i < 2; i++, pIn += 2 )
  184. {
  185. samp1[i] = *((short *)pIn);
  186. }
  187. for ( i = 0; i < 2; i++, pIn += 2 )
  188. {
  189. samp2[i] = *((short *)pIn);
  190. }
  191. // write out the initial samples (stored in reverse order)
  192. *pOut++ = (short)samp2[0]; // left
  193. *pOut++ = (short)samp2[1]; // right
  194. *pOut++ = (short)samp1[0]; // left
  195. *pOut++ = (short)samp1[1]; // right
  196. // subtract the 2 samples in the header
  197. count -= 2;
  198. // this is a toggle to read nibbles, first nibble is high
  199. int high = 1;
  200. int error, sample=0;
  201. // now process the block
  202. while ( count )
  203. {
  204. for ( i = 0; i < 2; i++ )
  205. {
  206. // read the error nibble from the input stream
  207. if ( high )
  208. {
  209. sample = (unsigned char) (*pIn++);
  210. // high nibble
  211. error = sample >> 4;
  212. // cache low nibble for next read
  213. sample = sample & 0xf;
  214. // Next read is from cache, not stream
  215. high = 0;
  216. }
  217. else
  218. {
  219. // stored in previous read (low nibble)
  220. error = sample;
  221. // next read is from stream
  222. high = 1;
  223. }
  224. // convert to signed with LUT
  225. int errorSign = error_sign_lut[error];
  226. // interpolate the new sample
  227. int predSample = (samp1[i] * co1[i]) + (samp2[i] * co2[i]);
  228. // coefficients are fixed point 8-bit, so shift back to 16-bit integer
  229. predSample >>= 8;
  230. // Add in current error estimate
  231. predSample += (errorSign * delta[i]);
  232. // Correct error estimate
  233. delta[i] = (delta[i] * error_coefficients_lut[error]) >> 8;
  234. // Clamp error estimate
  235. if ( delta[i] < 16 )
  236. delta[i] = 16;
  237. // clamp
  238. if ( predSample > 32767L )
  239. predSample = 32767L;
  240. else if ( predSample < -32768L )
  241. predSample = -32768L;
  242. // output
  243. *pOut++ = (short)predSample;
  244. // move samples over
  245. samp2[i] = samp1[i];
  246. samp1[i] = predSample;
  247. }
  248. count--;
  249. }
  250. }
  251. //-----------------------------------------------------------------------------
  252. // Purpose: Read data from the source and pass it to the appropriate decompress
  253. // routine.
  254. // Output : Returns true if data was decoded, false if none.
  255. //-----------------------------------------------------------------------------
  256. bool CAudioMixerWaveADPCM::DecodeBlock( void )
  257. {
  258. char tmpBlock[MAX_BLOCK_SIZE];
  259. char *pData;
  260. int blockSize;
  261. int firstSample;
  262. // fixup position with possible loop
  263. CAudioSourceWave &source = reinterpret_cast<CAudioSourceWave &>(m_pData->Source());
  264. m_offset = source.ConvertLoopedPosition( m_offset );
  265. if ( m_offset >= m_totalBytes )
  266. {
  267. // no more data
  268. return false;
  269. }
  270. // can only decode in block sized chunks
  271. firstSample = m_offset % m_blockSize;
  272. m_offset = m_offset - firstSample;
  273. // adpcm must calculate and request correct block size for proper decoding
  274. // last block size may be truncated
  275. blockSize = m_totalBytes - m_offset;
  276. if ( blockSize > m_blockSize )
  277. {
  278. blockSize = m_blockSize;
  279. }
  280. // get requested data
  281. int available = m_pData->ReadSourceData( (void **)(&pData), m_offset, blockSize, NULL );
  282. if ( available < blockSize )
  283. {
  284. // pump to get all of requested data
  285. int total = 0;
  286. while ( available && total < blockSize )
  287. {
  288. memcpy( tmpBlock + total, pData, available );
  289. total += available;
  290. available = m_pData->ReadSourceData( (void **)(&pData), m_offset + total, blockSize - total, NULL );
  291. }
  292. pData = tmpBlock;
  293. available = total;
  294. }
  295. if ( !available )
  296. {
  297. // no more data
  298. return false;
  299. }
  300. // advance the file pointer
  301. m_offset += available;
  302. int channelCount = NumChannels();
  303. // this is sample pairs for stereo, samples for mono
  304. m_sampleCount = m_pFormat->wSamplesPerBlock;
  305. // short block?, fixup sample count (2 samples per byte, divided by number of channels per sample set)
  306. m_sampleCount -= ((m_blockSize - available) * 2) / channelCount;
  307. // new block, start at the first sample
  308. m_samplePosition = firstSample;
  309. // no need to subclass for different channel counts...
  310. if ( channelCount == 1 )
  311. {
  312. DecompressBlockMono( m_pSamples, pData, m_sampleCount );
  313. }
  314. else
  315. {
  316. DecompressBlockStereo( m_pSamples, pData, m_sampleCount );
  317. }
  318. return true;
  319. }
  320. //-----------------------------------------------------------------------------
  321. // Purpose: Read existing buffer or decompress a new block when necessary
  322. // Input : **pData - output data pointer
  323. // sampleCount - number of samples (or pairs)
  324. // Output : int - available samples (zero to stop decoding)
  325. //-----------------------------------------------------------------------------
  326. int CAudioMixerWaveADPCM::GetOutputData( void **pData, int sampleCount, char copyBuf[AUDIOSOURCE_COPYBUF_SIZE] )
  327. {
  328. if ( m_samplePosition >= m_sampleCount )
  329. {
  330. if ( !DecodeBlock() )
  331. return 0;
  332. }
  333. if ( m_pSamples && m_samplePosition < m_sampleCount )
  334. {
  335. *pData = (void *)(m_pSamples + m_samplePosition * NumChannels());
  336. int available = m_sampleCount - m_samplePosition;
  337. if ( available > sampleCount )
  338. available = sampleCount;
  339. m_samplePosition += available;
  340. // update count of max samples loaded in CAudioMixerWave
  341. CAudioMixerWave::m_sample_max_loaded += available;
  342. // update index of last sample loaded
  343. CAudioMixerWave::m_sample_loaded_index += available;
  344. return available;
  345. }
  346. return 0;
  347. }
  348. //-----------------------------------------------------------------------------
  349. // Purpose: Seek to a new position in the file
  350. // NOTE: In most cases, only call this once, and call it before playing
  351. // any data.
  352. // Input : newPosition - new position in the sample clocks of this sample
  353. //-----------------------------------------------------------------------------
  354. void CAudioMixerWaveADPCM::SetSampleStart( int newPosition )
  355. {
  356. // cascade to base wave to update sample counter
  357. CAudioMixerWave::SetSampleStart( newPosition );
  358. // which block is the desired starting sample in?
  359. int blockStart = newPosition / m_pFormat->wSamplesPerBlock;
  360. // how far into the block is the sample
  361. int blockOffset = newPosition % m_pFormat->wSamplesPerBlock;
  362. // set the file position
  363. m_offset = blockStart * m_blockSize;
  364. // NOTE: Must decode a block here to properly position the sample Index
  365. // THIS MEANS YOU DON'T WANT TO CALL THIS ROUTINE OFTEN FOR ADPCM SOUNDS
  366. DecodeBlock();
  367. // limit to the samples decoded
  368. if ( blockOffset < m_sampleCount )
  369. blockOffset = m_sampleCount;
  370. // set the new current position
  371. m_samplePosition = blockOffset;
  372. }
  373. //-----------------------------------------------------------------------------
  374. // Purpose: Abstract factory function for ADPCM mixers
  375. // Input : *data - wave data access object
  376. // channels -
  377. // Output : CAudioMixer
  378. //-----------------------------------------------------------------------------
  379. CAudioMixer *CreateADPCMMixer( IWaveData *data )
  380. {
  381. return new CAudioMixerWaveADPCM( data );
  382. }