2
0

mp3dec.c 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484
  1. /* ***** BEGIN LICENSE BLOCK *****
  2. * Version: RCSL 1.0/RPSL 1.0
  3. *
  4. * Portions Copyright (c) 1995-2002 RealNetworks, Inc. All Rights Reserved.
  5. *
  6. * The contents of this file, and the files included with this file, are
  7. * subject to the current version of the RealNetworks Public Source License
  8. * Version 1.0 (the "RPSL") available at
  9. * http://www.helixcommunity.org/content/rpsl unless you have licensed
  10. * the file under the RealNetworks Community Source License Version 1.0
  11. * (the "RCSL") available at http://www.helixcommunity.org/content/rcsl,
  12. * in which case the RCSL will apply. You may also obtain the license terms
  13. * directly from RealNetworks. You may not use this file except in
  14. * compliance with the RPSL or, if you have a valid RCSL with RealNetworks
  15. * applicable to this file, the RCSL. Please see the applicable RPSL or
  16. * RCSL for the rights, obligations and limitations governing use of the
  17. * contents of the file.
  18. *
  19. * This file is part of the Helix DNA Technology. RealNetworks is the
  20. * developer of the Original Code and owns the copyrights in the portions
  21. * it created.
  22. *
  23. * This file, and the files included with this file, is distributed and made
  24. * available on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
  25. * EXPRESS OR IMPLIED, AND REALNETWORKS HEREBY DISCLAIMS ALL SUCH WARRANTIES,
  26. * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, FITNESS
  27. * FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
  28. *
  29. * Technology Compatibility Kit Test Suite(s) Location:
  30. * http://www.helixcommunity.org/content/tck
  31. *
  32. * Contributor(s):
  33. *
  34. * ***** END LICENSE BLOCK ***** */
  35. /**************************************************************************************
  36. * Fixed-point MP3 decoder
  37. * Jon Recker (jrecker@real.com), Ken Cooke (kenc@real.com)
  38. * June 2003
  39. *
  40. * mp3dec.c - platform-independent top level MP3 decoder API
  41. **************************************************************************************/
  42. #include "string.h"
  43. //#include "hlxclib/string.h" /* for memmove, memcpy (can replace with different implementations if desired) */
  44. #include "mp3common.h" /* includes mp3dec.h (public API) and internal, platform-independent API */
  45. //#define PROFILE
  46. #ifdef PROFILE
  47. #include "systime.h"
  48. #endif
  49. /**************************************************************************************
  50. * Function: MP3InitDecoder
  51. *
  52. * Description: allocate memory for platform-specific data
  53. * clear all the user-accessible fields
  54. *
  55. * Inputs: none
  56. *
  57. * Outputs: none
  58. *
  59. * Return: handle to mp3 decoder instance, 0 if malloc fails
  60. **************************************************************************************/
  61. HMP3Decoder MP3InitDecoder(void)
  62. {
  63. MP3DecInfo *mp3DecInfo;
  64. mp3DecInfo = AllocateBuffers();
  65. return (HMP3Decoder)mp3DecInfo;
  66. }
  67. /**************************************************************************************
  68. * Function: MP3FreeDecoder
  69. *
  70. * Description: free platform-specific data allocated by InitMP3Decoder
  71. * zero out the contents of MP3DecInfo struct
  72. *
  73. * Inputs: valid MP3 decoder instance pointer (HMP3Decoder)
  74. *
  75. * Outputs: none
  76. *
  77. * Return: none
  78. **************************************************************************************/
  79. void MP3FreeDecoder(HMP3Decoder hMP3Decoder)
  80. {
  81. MP3DecInfo *mp3DecInfo = (MP3DecInfo *)hMP3Decoder;
  82. if (!mp3DecInfo)
  83. return;
  84. FreeBuffers(mp3DecInfo);
  85. }
  86. /**************************************************************************************
  87. * Function: MP3FindSyncWord
  88. *
  89. * Description: locate the next byte-alinged sync word in the raw mp3 stream
  90. *
  91. * Inputs: buffer to search for sync word
  92. * max number of bytes to search in buffer
  93. *
  94. * Outputs: none
  95. *
  96. * Return: offset to first sync word (bytes from start of buf)
  97. * -1 if sync not found after searching nBytes
  98. **************************************************************************************/
  99. int MP3FindSyncWord(unsigned char *buf, int nBytes)
  100. {
  101. int i;
  102. /* find byte-aligned syncword - need 12 (MPEG 1,2) or 11 (MPEG 2.5) matching bits */
  103. for (i = 0; i < nBytes - 1; i++) {
  104. if ( (buf[i+0] & SYNCWORDH) == SYNCWORDH && (buf[i+1] & SYNCWORDL) == SYNCWORDL )
  105. return i;
  106. }
  107. return -1;
  108. }
  109. /**************************************************************************************
  110. * Function: MP3FindFreeSync
  111. *
  112. * Description: figure out number of bytes between adjacent sync words in "free" mode
  113. *
  114. * Inputs: buffer to search for next sync word
  115. * the 4-byte frame header starting at the current sync word
  116. * max number of bytes to search in buffer
  117. *
  118. * Outputs: none
  119. *
  120. * Return: offset to next sync word, minus any pad byte (i.e. nSlots)
  121. * -1 if sync not found after searching nBytes
  122. *
  123. * Notes: this checks that the first 22 bits of the next frame header are the
  124. * same as the current frame header, but it's still not foolproof
  125. * (could accidentally find a sequence in the bitstream which
  126. * appears to match but is not actually the next frame header)
  127. * this could be made more error-resilient by checking several frames
  128. * in a row and verifying that nSlots is the same in each case
  129. * since free mode requires CBR (see spec) we generally only call
  130. * this function once (first frame) then store the result (nSlots)
  131. * and just use it from then on
  132. **************************************************************************************/
  133. static int MP3FindFreeSync(unsigned char *buf, unsigned char firstFH[4], int nBytes)
  134. {
  135. int offset = 0;
  136. unsigned char *bufPtr = buf;
  137. /* loop until we either:
  138. * - run out of nBytes (FindMP3SyncWord() returns -1)
  139. * - find the next valid frame header (sync word, version, layer, CRC flag, bitrate, and sample rate
  140. * in next header must match current header)
  141. */
  142. while (1) {
  143. offset = MP3FindSyncWord(bufPtr, nBytes);
  144. bufPtr += offset;
  145. if (offset < 0) {
  146. return -1;
  147. } else if ( (bufPtr[0] == firstFH[0]) && (bufPtr[1] == firstFH[1]) && ((bufPtr[2] & 0xfc) == (firstFH[2] & 0xfc)) ) {
  148. /* want to return number of bytes per frame, NOT counting the padding byte, so subtract one if padFlag == 1 */
  149. if ((firstFH[2] >> 1) & 0x01)
  150. bufPtr--;
  151. return bufPtr - buf;
  152. }
  153. bufPtr += 3;
  154. nBytes -= (offset + 3);
  155. };
  156. return -1;
  157. }
  158. /**************************************************************************************
  159. * Function: MP3GetLastFrameInfo
  160. *
  161. * Description: get info about last MP3 frame decoded (number of sampled decoded,
  162. * sample rate, bitrate, etc.)
  163. *
  164. * Inputs: valid MP3 decoder instance pointer (HMP3Decoder)
  165. * pointer to MP3FrameInfo struct
  166. *
  167. * Outputs: filled-in MP3FrameInfo struct
  168. *
  169. * Return: none
  170. *
  171. * Notes: call this right after calling MP3Decode
  172. **************************************************************************************/
  173. void MP3GetLastFrameInfo(HMP3Decoder hMP3Decoder, MP3FrameInfo *mp3FrameInfo)
  174. {
  175. MP3DecInfo *mp3DecInfo = (MP3DecInfo *)hMP3Decoder;
  176. if (!mp3DecInfo || mp3DecInfo->layer != 3) {
  177. mp3FrameInfo->bitrate = 0;
  178. mp3FrameInfo->nChans = 0;
  179. mp3FrameInfo->samprate = 0;
  180. mp3FrameInfo->bitsPerSample = 0;
  181. mp3FrameInfo->outputSamps = 0;
  182. mp3FrameInfo->layer = 0;
  183. mp3FrameInfo->version = 0;
  184. } else {
  185. mp3FrameInfo->bitrate = mp3DecInfo->bitrate;
  186. mp3FrameInfo->nChans = mp3DecInfo->nChans;
  187. mp3FrameInfo->samprate = mp3DecInfo->samprate;
  188. mp3FrameInfo->bitsPerSample = 16;
  189. mp3FrameInfo->outputSamps = mp3DecInfo->nChans * (int)samplesPerFrameTab[mp3DecInfo->version][mp3DecInfo->layer - 1];
  190. mp3FrameInfo->layer = mp3DecInfo->layer;
  191. mp3FrameInfo->version = mp3DecInfo->version;
  192. }
  193. }
  194. /**************************************************************************************
  195. * Function: MP3GetNextFrameInfo
  196. *
  197. * Description: parse MP3 frame header
  198. *
  199. * Inputs: valid MP3 decoder instance pointer (HMP3Decoder)
  200. * pointer to MP3FrameInfo struct
  201. * pointer to buffer containing valid MP3 frame header (located using
  202. * MP3FindSyncWord(), above)
  203. *
  204. * Outputs: filled-in MP3FrameInfo struct
  205. *
  206. * Return: error code, defined in mp3dec.h (0 means no error, < 0 means error)
  207. **************************************************************************************/
  208. int MP3GetNextFrameInfo(HMP3Decoder hMP3Decoder, MP3FrameInfo *mp3FrameInfo, unsigned char *buf)
  209. {
  210. MP3DecInfo *mp3DecInfo = (MP3DecInfo *)hMP3Decoder;
  211. if (!mp3DecInfo)
  212. return ERR_MP3_NULL_POINTER;
  213. if (UnpackFrameHeader(mp3DecInfo, buf) == -1 || mp3DecInfo->layer != 3)
  214. return ERR_MP3_INVALID_FRAMEHEADER;
  215. MP3GetLastFrameInfo(mp3DecInfo, mp3FrameInfo);
  216. return ERR_MP3_NONE;
  217. }
  218. /**************************************************************************************
  219. * Function: MP3ClearBadFrame
  220. *
  221. * Description: zero out pcm buffer if error decoding MP3 frame
  222. *
  223. * Inputs: mp3DecInfo struct with correct frame size parameters filled in
  224. * pointer pcm output buffer
  225. *
  226. * Outputs: zeroed out pcm buffer
  227. *
  228. * Return: none
  229. **************************************************************************************/
  230. static void MP3ClearBadFrame(MP3DecInfo *mp3DecInfo, short *outbuf)
  231. {
  232. int i;
  233. if (!mp3DecInfo)
  234. return;
  235. for (i = 0; i < mp3DecInfo->nGrans * mp3DecInfo->nGranSamps * mp3DecInfo->nChans; i++)
  236. outbuf[i] = 0;
  237. }
  238. /**************************************************************************************
  239. * Function: MP3Decode
  240. *
  241. * Description: decode one frame of MP3 data
  242. *
  243. * Inputs: valid MP3 decoder instance pointer (HMP3Decoder)
  244. * double pointer to buffer of MP3 data (containing headers + mainData)
  245. * number of valid bytes remaining in inbuf
  246. * pointer to outbuf, big enough to hold one frame of decoded PCM samples
  247. * flag indicating whether MP3 data is normal MPEG format (useSize = 0)
  248. * or reformatted as "self-contained" frames (useSize = 1)
  249. *
  250. * Outputs: PCM data in outbuf, interleaved LRLRLR... if stereo
  251. * number of output samples = nGrans * nGranSamps * nChans
  252. * updated inbuf pointer, updated bytesLeft
  253. *
  254. * Return: error code, defined in mp3dec.h (0 means no error, < 0 means error)
  255. *
  256. * Notes: switching useSize on and off between frames in the same stream
  257. * is not supported (bit reservoir is not maintained if useSize on)
  258. **************************************************************************************/
  259. int MP3Decode(HMP3Decoder hMP3Decoder, unsigned char **inbuf, int *bytesLeft, short *outbuf, int useSize)
  260. {
  261. int offset, bitOffset, mainBits, gr, ch, fhBytes, siBytes, freeFrameBytes;
  262. int prevBitOffset, sfBlockBits, huffBlockBits;
  263. unsigned char *mainPtr;
  264. MP3DecInfo *mp3DecInfo = (MP3DecInfo *)hMP3Decoder;
  265. #ifdef PROFILE
  266. long time;
  267. #endif
  268. if (!mp3DecInfo)
  269. return ERR_MP3_NULL_POINTER;
  270. /* unpack frame header */
  271. fhBytes = UnpackFrameHeader(mp3DecInfo, *inbuf);
  272. if (fhBytes < 0)
  273. return ERR_MP3_INVALID_FRAMEHEADER; /* don't clear outbuf since we don't know size (failed to parse header) */
  274. *inbuf += fhBytes;
  275. #ifdef PROFILE
  276. time = systime_get();
  277. #endif
  278. /* unpack side info */
  279. siBytes = UnpackSideInfo(mp3DecInfo, *inbuf);
  280. if (siBytes < 0) {
  281. MP3ClearBadFrame(mp3DecInfo, outbuf);
  282. return ERR_MP3_INVALID_SIDEINFO;
  283. }
  284. *inbuf += siBytes;
  285. *bytesLeft -= (fhBytes + siBytes);
  286. #ifdef PROFILE
  287. time = systime_get() - time;
  288. printf("UnpackSideInfo: %i ms\n", time);
  289. #endif
  290. /* if free mode, need to calculate bitrate and nSlots manually, based on frame size */
  291. if (mp3DecInfo->bitrate == 0 || mp3DecInfo->freeBitrateFlag) {
  292. if (!mp3DecInfo->freeBitrateFlag) {
  293. /* first time through, need to scan for next sync word and figure out frame size */
  294. mp3DecInfo->freeBitrateFlag = 1;
  295. mp3DecInfo->freeBitrateSlots = MP3FindFreeSync(*inbuf, *inbuf - fhBytes - siBytes, *bytesLeft);
  296. if (mp3DecInfo->freeBitrateSlots < 0) {
  297. MP3ClearBadFrame(mp3DecInfo, outbuf);
  298. return ERR_MP3_FREE_BITRATE_SYNC;
  299. }
  300. freeFrameBytes = mp3DecInfo->freeBitrateSlots + fhBytes + siBytes;
  301. mp3DecInfo->bitrate = (freeFrameBytes * mp3DecInfo->samprate * 8) / (mp3DecInfo->nGrans * mp3DecInfo->nGranSamps);
  302. }
  303. mp3DecInfo->nSlots = mp3DecInfo->freeBitrateSlots + CheckPadBit(mp3DecInfo); /* add pad byte, if required */
  304. }
  305. /* useSize != 0 means we're getting reformatted (RTP) packets (see RFC 3119)
  306. * - calling function assembles "self-contained" MP3 frames by shifting any main_data
  307. * from the bit reservoir (in previous frames) to AFTER the sync word and side info
  308. * - calling function should set mainDataBegin to 0, and tell us exactly how large this
  309. * frame is (in bytesLeft)
  310. */
  311. if (useSize) {
  312. mp3DecInfo->nSlots = *bytesLeft;
  313. if (mp3DecInfo->mainDataBegin != 0 || mp3DecInfo->nSlots <= 0) {
  314. /* error - non self-contained frame, or missing frame (size <= 0), could do loss concealment here */
  315. MP3ClearBadFrame(mp3DecInfo, outbuf);
  316. return ERR_MP3_INVALID_FRAMEHEADER;
  317. }
  318. /* can operate in-place on reformatted frames */
  319. mp3DecInfo->mainDataBytes = mp3DecInfo->nSlots;
  320. mainPtr = *inbuf;
  321. *inbuf += mp3DecInfo->nSlots;
  322. *bytesLeft -= (mp3DecInfo->nSlots);
  323. } else {
  324. /* out of data - assume last or truncated frame */
  325. if (mp3DecInfo->nSlots > *bytesLeft) {
  326. MP3ClearBadFrame(mp3DecInfo, outbuf);
  327. return ERR_MP3_INDATA_UNDERFLOW;
  328. }
  329. #ifdef PROFILE
  330. time = systime_get();
  331. #endif
  332. /* fill main data buffer with enough new data for this frame */
  333. if (mp3DecInfo->mainDataBytes >= mp3DecInfo->mainDataBegin) {
  334. /* adequate "old" main data available (i.e. bit reservoir) */
  335. memmove(mp3DecInfo->mainBuf, mp3DecInfo->mainBuf + mp3DecInfo->mainDataBytes - mp3DecInfo->mainDataBegin, mp3DecInfo->mainDataBegin);
  336. memcpy(mp3DecInfo->mainBuf + mp3DecInfo->mainDataBegin, *inbuf, mp3DecInfo->nSlots);
  337. mp3DecInfo->mainDataBytes = mp3DecInfo->mainDataBegin + mp3DecInfo->nSlots;
  338. *inbuf += mp3DecInfo->nSlots;
  339. *bytesLeft -= (mp3DecInfo->nSlots);
  340. mainPtr = mp3DecInfo->mainBuf;
  341. } else {
  342. /* not enough data in bit reservoir from previous frames (perhaps starting in middle of file) */
  343. memcpy(mp3DecInfo->mainBuf + mp3DecInfo->mainDataBytes, *inbuf, mp3DecInfo->nSlots);
  344. mp3DecInfo->mainDataBytes += mp3DecInfo->nSlots;
  345. *inbuf += mp3DecInfo->nSlots;
  346. *bytesLeft -= (mp3DecInfo->nSlots);
  347. MP3ClearBadFrame(mp3DecInfo, outbuf);
  348. return ERR_MP3_MAINDATA_UNDERFLOW;
  349. }
  350. #ifdef PROFILE
  351. time = systime_get() - time;
  352. printf("data buffer filling: %i ms\n", time);
  353. #endif
  354. }
  355. bitOffset = 0;
  356. mainBits = mp3DecInfo->mainDataBytes * 8;
  357. /* decode one complete frame */
  358. for (gr = 0; gr < mp3DecInfo->nGrans; gr++) {
  359. for (ch = 0; ch < mp3DecInfo->nChans; ch++) {
  360. #ifdef PROFILE
  361. time = systime_get();
  362. #endif
  363. /* unpack scale factors and compute size of scale factor block */
  364. prevBitOffset = bitOffset;
  365. offset = UnpackScaleFactors(mp3DecInfo, mainPtr, &bitOffset, mainBits, gr, ch);
  366. #ifdef PROFILE
  367. time = systime_get() - time;
  368. printf("UnpackScaleFactors: %i ms\n", time);
  369. #endif
  370. sfBlockBits = 8*offset - prevBitOffset + bitOffset;
  371. huffBlockBits = mp3DecInfo->part23Length[gr][ch] - sfBlockBits;
  372. mainPtr += offset;
  373. mainBits -= sfBlockBits;
  374. if (offset < 0 || mainBits < huffBlockBits) {
  375. MP3ClearBadFrame(mp3DecInfo, outbuf);
  376. return ERR_MP3_INVALID_SCALEFACT;
  377. }
  378. #ifdef PROFILE
  379. time = systime_get();
  380. #endif
  381. /* decode Huffman code words */
  382. prevBitOffset = bitOffset;
  383. offset = DecodeHuffman(mp3DecInfo, mainPtr, &bitOffset, huffBlockBits, gr, ch);
  384. if (offset < 0) {
  385. MP3ClearBadFrame(mp3DecInfo, outbuf);
  386. return ERR_MP3_INVALID_HUFFCODES;
  387. }
  388. #ifdef PROFILE
  389. time = systime_get() - time;
  390. printf("Huffman: %i ms\n", time);
  391. #endif
  392. mainPtr += offset;
  393. mainBits -= (8*offset - prevBitOffset + bitOffset);
  394. }
  395. #ifdef PROFILE
  396. time = systime_get();
  397. #endif
  398. /* dequantize coefficients, decode stereo, reorder short blocks */
  399. if (Dequantize(mp3DecInfo, gr) < 0) {
  400. MP3ClearBadFrame(mp3DecInfo, outbuf);
  401. return ERR_MP3_INVALID_DEQUANTIZE;
  402. }
  403. #ifdef PROFILE
  404. time = systime_get() - time;
  405. printf("Dequantize: %i ms\n", time);
  406. #endif
  407. /* alias reduction, inverse MDCT, overlap-add, frequency inversion */
  408. for (ch = 0; ch < mp3DecInfo->nChans; ch++)
  409. {
  410. #ifdef PROFILE
  411. time = systime_get();
  412. #endif
  413. if (IMDCT(mp3DecInfo, gr, ch) < 0) {
  414. MP3ClearBadFrame(mp3DecInfo, outbuf);
  415. return ERR_MP3_INVALID_IMDCT;
  416. }
  417. #ifdef PROFILE
  418. time = systime_get() - time;
  419. printf("IMDCT: %i ms\n", time);
  420. #endif
  421. }
  422. #ifdef PROFILE
  423. time = systime_get();
  424. #endif
  425. /* subband transform - if stereo, interleaves pcm LRLRLR */
  426. if (Subband(mp3DecInfo, outbuf + gr*mp3DecInfo->nGranSamps*mp3DecInfo->nChans) < 0) {
  427. MP3ClearBadFrame(mp3DecInfo, outbuf);
  428. return ERR_MP3_INVALID_SUBBAND;
  429. }
  430. #ifdef PROFILE
  431. time = systime_get() - time;
  432. printf("Subband: %i ms\n", time);
  433. #endif
  434. }
  435. return ERR_MP3_NONE;
  436. }