mp3dec.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407
  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> /* for memmove, memcpy (can replace with different implementations if desired) */
  43. #include <contrib/hxmp3/mp3common.h> /* includes mp3dec.h (public API) and internal, platform-independent API */
  44. /**************************************************************************************
  45. * Function: MP3InitDecoder
  46. *
  47. * Description: allocate memory for platform-specific data
  48. * clear all the user-accessible fields
  49. *
  50. * Inputs: none
  51. *
  52. * Outputs: none
  53. *
  54. * Return: handle to mp3 decoder instance, 0 if malloc fails
  55. **************************************************************************************/
  56. HMP3Decoder MP3InitDecoder(void)
  57. {
  58. MP3DecInfo *mp3DecInfo;
  59. mp3DecInfo = AllocateBuffers();
  60. return (HMP3Decoder)mp3DecInfo;
  61. }
  62. /**************************************************************************************
  63. * Function: MP3FreeDecoder
  64. *
  65. * Description: free platform-specific data allocated by InitMP3Decoder
  66. * zero out the contents of MP3DecInfo struct
  67. *
  68. * Inputs: valid MP3 decoder instance pointer (HMP3Decoder)
  69. *
  70. * Outputs: none
  71. *
  72. * Return: none
  73. **************************************************************************************/
  74. void MP3FreeDecoder(HMP3Decoder hMP3Decoder)
  75. {
  76. MP3DecInfo *mp3DecInfo = (MP3DecInfo *)hMP3Decoder;
  77. if (!mp3DecInfo)
  78. return;
  79. FreeBuffers(mp3DecInfo);
  80. }
  81. /**************************************************************************************
  82. * Function: MP3FindSyncWord
  83. *
  84. * Description: locate the next byte-alinged sync word in the raw mp3 stream
  85. *
  86. * Inputs: buffer to search for sync word
  87. * max number of bytes to search in buffer
  88. *
  89. * Outputs: none
  90. *
  91. * Return: offset to first sync word (bytes from start of buf)
  92. * -1 if sync not found after searching nBytes
  93. **************************************************************************************/
  94. int MP3FindSyncWord(unsigned char *buf, int nBytes)
  95. {
  96. int i;
  97. /* find byte-aligned syncword - need 12 (MPEG 1,2) or 11 (MPEG 2.5) matching bits */
  98. for (i = 0; i < nBytes - 1; i++) {
  99. if ( (buf[i+0] & SYNCWORDH) == SYNCWORDH && (buf[i+1] & SYNCWORDL) == SYNCWORDL )
  100. return i;
  101. }
  102. return -1;
  103. }
  104. /**************************************************************************************
  105. * Function: MP3FindFreeSync
  106. *
  107. * Description: figure out number of bytes between adjacent sync words in "free" mode
  108. *
  109. * Inputs: buffer to search for next sync word
  110. * the 4-byte frame header starting at the current sync word
  111. * max number of bytes to search in buffer
  112. *
  113. * Outputs: none
  114. *
  115. * Return: offset to next sync word, minus any pad byte (i.e. nSlots)
  116. * -1 if sync not found after searching nBytes
  117. *
  118. * Notes: this checks that the first 22 bits of the next frame header are the
  119. * same as the current frame header, but it's still not foolproof
  120. * (could accidentally find a sequence in the bitstream which
  121. * appears to match but is not actually the next frame header)
  122. * this could be made more error-resilient by checking several frames
  123. * in a row and verifying that nSlots is the same in each case
  124. * since free mode requires CBR (see spec) we generally only call
  125. * this function once (first frame) then store the result (nSlots)
  126. * and just use it from then on
  127. **************************************************************************************/
  128. static int MP3FindFreeSync(unsigned char *buf, unsigned char firstFH[4], int nBytes)
  129. {
  130. int offset = 0;
  131. unsigned char *bufPtr = buf;
  132. /* loop until we either:
  133. * - run out of nBytes (FindMP3SyncWord() returns -1)
  134. * - find the next valid frame header (sync word, version, layer, CRC flag, bitrate, and sample rate
  135. * in next header must match current header)
  136. */
  137. while (1) {
  138. offset = MP3FindSyncWord(bufPtr, nBytes);
  139. bufPtr += offset;
  140. if (offset < 0) {
  141. return -1;
  142. } else if ( (bufPtr[0] == firstFH[0]) && (bufPtr[1] == firstFH[1]) && ((bufPtr[2] & 0xfc) == (firstFH[2] & 0xfc)) ) {
  143. /* want to return number of bytes per frame, NOT counting the padding byte, so subtract one if padFlag == 1 */
  144. if ((firstFH[2] >> 1) & 0x01)
  145. bufPtr--;
  146. return bufPtr - buf;
  147. }
  148. bufPtr += 3;
  149. nBytes -= (offset + 3);
  150. };
  151. return -1;
  152. }
  153. /**************************************************************************************
  154. * Function: MP3GetLastFrameInfo
  155. *
  156. * Description: get info about last MP3 frame decoded (number of sampled decoded,
  157. * sample rate, bitrate, etc.)
  158. *
  159. * Inputs: valid MP3 decoder instance pointer (HMP3Decoder)
  160. * pointer to MP3FrameInfo struct
  161. *
  162. * Outputs: filled-in MP3FrameInfo struct
  163. *
  164. * Return: none
  165. *
  166. * Notes: call this right after calling MP3Decode
  167. **************************************************************************************/
  168. void MP3GetLastFrameInfo(HMP3Decoder hMP3Decoder, MP3FrameInfo *mp3FrameInfo)
  169. {
  170. MP3DecInfo *mp3DecInfo = (MP3DecInfo *)hMP3Decoder;
  171. if (!mp3DecInfo || mp3DecInfo->layer != 3) {
  172. mp3FrameInfo->bitrate = 0;
  173. mp3FrameInfo->nChans = 0;
  174. mp3FrameInfo->samprate = 0;
  175. mp3FrameInfo->bitsPerSample = 0;
  176. mp3FrameInfo->outputSamps = 0;
  177. mp3FrameInfo->layer = 0;
  178. mp3FrameInfo->version = 0;
  179. } else {
  180. mp3FrameInfo->bitrate = mp3DecInfo->bitrate;
  181. mp3FrameInfo->nChans = mp3DecInfo->nChans;
  182. mp3FrameInfo->samprate = mp3DecInfo->samprate;
  183. mp3FrameInfo->bitsPerSample = 16;
  184. mp3FrameInfo->outputSamps = mp3DecInfo->nChans * (int)samplesPerFrameTab[mp3DecInfo->version][mp3DecInfo->layer - 1];
  185. mp3FrameInfo->layer = mp3DecInfo->layer;
  186. mp3FrameInfo->version = mp3DecInfo->version;
  187. }
  188. }
  189. /**************************************************************************************
  190. * Function: MP3GetNextFrameInfo
  191. *
  192. * Description: parse MP3 frame header
  193. *
  194. * Inputs: valid MP3 decoder instance pointer (HMP3Decoder)
  195. * pointer to MP3FrameInfo struct
  196. * pointer to buffer containing valid MP3 frame header (located using
  197. * MP3FindSyncWord(), above)
  198. *
  199. * Outputs: filled-in MP3FrameInfo struct
  200. *
  201. * Return: error code, defined in mp3dec.h (0 means no error, < 0 means error)
  202. **************************************************************************************/
  203. int MP3GetNextFrameInfo(HMP3Decoder hMP3Decoder, MP3FrameInfo *mp3FrameInfo, unsigned char *buf)
  204. {
  205. MP3DecInfo *mp3DecInfo = (MP3DecInfo *)hMP3Decoder;
  206. if (!mp3DecInfo)
  207. return ERR_MP3_NULL_POINTER;
  208. if (UnpackFrameHeader(mp3DecInfo, buf) == -1 || mp3DecInfo->layer != 3)
  209. return ERR_MP3_INVALID_FRAMEHEADER;
  210. MP3GetLastFrameInfo(mp3DecInfo, mp3FrameInfo);
  211. return ERR_MP3_NONE;
  212. }
  213. /**************************************************************************************
  214. * Function: MP3ClearBadFrame
  215. *
  216. * Description: zero out pcm buffer if error decoding MP3 frame
  217. *
  218. * Inputs: mp3DecInfo struct with correct frame size parameters filled in
  219. * pointer pcm output buffer
  220. *
  221. * Outputs: zeroed out pcm buffer
  222. *
  223. * Return: none
  224. **************************************************************************************/
  225. static void MP3ClearBadFrame(MP3DecInfo *mp3DecInfo, short *outbuf)
  226. {
  227. int i;
  228. if (!mp3DecInfo)
  229. return;
  230. for (i = 0; i < mp3DecInfo->nGrans * mp3DecInfo->nGranSamps * mp3DecInfo->nChans; i++)
  231. outbuf[i] = 0;
  232. }
  233. /**************************************************************************************
  234. * Function: MP3Decode
  235. *
  236. * Description: decode one frame of MP3 data
  237. *
  238. * Inputs: valid MP3 decoder instance pointer (HMP3Decoder)
  239. * double pointer to buffer of MP3 data (containing headers + mainData)
  240. * number of valid bytes remaining in inbuf
  241. * pointer to outbuf, big enough to hold one frame of decoded PCM samples
  242. * flag indicating whether MP3 data is normal MPEG format (useSize = 0)
  243. * or reformatted as "self-contained" frames (useSize = 1)
  244. *
  245. * Outputs: PCM data in outbuf, interleaved LRLRLR... if stereo
  246. * number of output samples = nGrans * nGranSamps * nChans
  247. * updated inbuf pointer, updated bytesLeft
  248. *
  249. * Return: error code, defined in mp3dec.h (0 means no error, < 0 means error)
  250. *
  251. * Notes: switching useSize on and off between frames in the same stream
  252. * is not supported (bit reservoir is not maintained if useSize on)
  253. **************************************************************************************/
  254. int MP3Decode(HMP3Decoder hMP3Decoder, unsigned char **inbuf, int *bytesLeft, short *outbuf, int useSize)
  255. {
  256. int offset, bitOffset, mainBits, gr, ch, fhBytes, siBytes, freeFrameBytes;
  257. int prevBitOffset, sfBlockBits, huffBlockBits;
  258. unsigned char *mainPtr;
  259. MP3DecInfo *mp3DecInfo = (MP3DecInfo *)hMP3Decoder;
  260. if (!mp3DecInfo)
  261. return ERR_MP3_NULL_POINTER;
  262. /* unpack frame header */
  263. fhBytes = UnpackFrameHeader(mp3DecInfo, *inbuf);
  264. if (fhBytes < 0)
  265. return ERR_MP3_INVALID_FRAMEHEADER; /* don't clear outbuf since we don't know size (failed to parse header) */
  266. *inbuf += fhBytes;
  267. /* unpack side info */
  268. siBytes = UnpackSideInfo(mp3DecInfo, *inbuf);
  269. if (siBytes < 0) {
  270. MP3ClearBadFrame(mp3DecInfo, outbuf);
  271. return ERR_MP3_INVALID_SIDEINFO;
  272. }
  273. *inbuf += siBytes;
  274. *bytesLeft -= (fhBytes + siBytes);
  275. /* if free mode, need to calculate bitrate and nSlots manually, based on frame size */
  276. if (mp3DecInfo->bitrate == 0 || mp3DecInfo->freeBitrateFlag) {
  277. if (!mp3DecInfo->freeBitrateFlag) {
  278. /* first time through, need to scan for next sync word and figure out frame size */
  279. mp3DecInfo->freeBitrateFlag = 1;
  280. mp3DecInfo->freeBitrateSlots = MP3FindFreeSync(*inbuf, *inbuf - fhBytes - siBytes, *bytesLeft);
  281. if (mp3DecInfo->freeBitrateSlots < 0) {
  282. MP3ClearBadFrame(mp3DecInfo, outbuf);
  283. return ERR_MP3_FREE_BITRATE_SYNC;
  284. }
  285. freeFrameBytes = mp3DecInfo->freeBitrateSlots + fhBytes + siBytes;
  286. mp3DecInfo->bitrate = (freeFrameBytes * mp3DecInfo->samprate * 8) / (mp3DecInfo->nGrans * mp3DecInfo->nGranSamps);
  287. }
  288. mp3DecInfo->nSlots = mp3DecInfo->freeBitrateSlots + CheckPadBit(mp3DecInfo); /* add pad byte, if required */
  289. }
  290. /* useSize != 0 means we're getting reformatted (RTP) packets (see RFC 3119)
  291. * - calling function assembles "self-contained" MP3 frames by shifting any main_data
  292. * from the bit reservoir (in previous frames) to AFTER the sync word and side info
  293. * - calling function should set mainDataBegin to 0, and tell us exactly how large this
  294. * frame is (in bytesLeft)
  295. */
  296. if (useSize) {
  297. mp3DecInfo->nSlots = *bytesLeft;
  298. if (mp3DecInfo->mainDataBegin != 0 || mp3DecInfo->nSlots <= 0) {
  299. /* error - non self-contained frame, or missing frame (size <= 0), could do loss concealment here */
  300. MP3ClearBadFrame(mp3DecInfo, outbuf);
  301. return ERR_MP3_INVALID_FRAMEHEADER;
  302. }
  303. /* can operate in-place on reformatted frames */
  304. mp3DecInfo->mainDataBytes = mp3DecInfo->nSlots;
  305. mainPtr = *inbuf;
  306. *inbuf += mp3DecInfo->nSlots;
  307. *bytesLeft -= (mp3DecInfo->nSlots);
  308. } else {
  309. /* out of data - assume last or truncated frame */
  310. if (mp3DecInfo->nSlots > *bytesLeft)
  311. return ERR_MP3_INDATA_UNDERFLOW;
  312. /* fill main data buffer with enough new data for this frame */
  313. if (mp3DecInfo->mainDataBytes >= mp3DecInfo->mainDataBegin) {
  314. /* adequate "old" main data available (i.e. bit reservoir) */
  315. memmove(mp3DecInfo->mainBuf, mp3DecInfo->mainBuf + mp3DecInfo->mainDataBytes - mp3DecInfo->mainDataBegin, mp3DecInfo->mainDataBegin);
  316. memcpy(mp3DecInfo->mainBuf + mp3DecInfo->mainDataBegin, *inbuf, mp3DecInfo->nSlots);
  317. mp3DecInfo->mainDataBytes = mp3DecInfo->mainDataBegin + mp3DecInfo->nSlots;
  318. *inbuf += mp3DecInfo->nSlots;
  319. *bytesLeft -= (mp3DecInfo->nSlots);
  320. mainPtr = mp3DecInfo->mainBuf;
  321. } else {
  322. /* not enough data in bit reservoir from previous frames (perhaps starting in middle of file) */
  323. memcpy(mp3DecInfo->mainBuf + mp3DecInfo->mainDataBytes, *inbuf, mp3DecInfo->nSlots);
  324. mp3DecInfo->mainDataBytes += mp3DecInfo->nSlots;
  325. *inbuf += mp3DecInfo->nSlots;
  326. *bytesLeft -= (mp3DecInfo->nSlots);
  327. return ERR_MP3_MAINDATA_UNDERFLOW;
  328. }
  329. }
  330. bitOffset = 0;
  331. mainBits = mp3DecInfo->mainDataBytes * 8;
  332. /* decode one complete frame */
  333. for (gr = 0; gr < mp3DecInfo->nGrans; gr++) {
  334. for (ch = 0; ch < mp3DecInfo->nChans; ch++) {
  335. /* unpack scale factors and compute size of scale factor block */
  336. prevBitOffset = bitOffset;
  337. offset = UnpackScaleFactors(mp3DecInfo, mainPtr, &bitOffset, mainBits, gr, ch);
  338. sfBlockBits = 8*offset - prevBitOffset + bitOffset;
  339. huffBlockBits = mp3DecInfo->part23Length[gr][ch] - sfBlockBits;
  340. mainPtr += offset;
  341. mainBits -= sfBlockBits;
  342. if (offset < 0 || mainBits < huffBlockBits) {
  343. MP3ClearBadFrame(mp3DecInfo, outbuf);
  344. return ERR_MP3_INVALID_SCALEFACT;
  345. }
  346. /* decode Huffman code words */
  347. prevBitOffset = bitOffset;
  348. offset = DecodeHuffman(mp3DecInfo, mainPtr, &bitOffset, huffBlockBits, gr, ch);
  349. if (offset < 0) {
  350. MP3ClearBadFrame(mp3DecInfo, outbuf);
  351. return ERR_MP3_INVALID_HUFFCODES;
  352. }
  353. mainPtr += offset;
  354. mainBits -= (8*offset - prevBitOffset + bitOffset);
  355. }
  356. /* dequantize coefficients, decode stereo, reorder short blocks */
  357. Dequantize(mp3DecInfo, gr);
  358. /* alias reduction, inverse MDCT, overlap-add, frequency inversion */
  359. for (ch = 0; ch < mp3DecInfo->nChans; ch++)
  360. IMDCT(mp3DecInfo, gr, ch);
  361. /* subband transform - if stereo, interleaves pcm LRLRLR */
  362. Subband(mp3DecInfo, outbuf + gr*mp3DecInfo->nGranSamps*mp3DecInfo->nChans);
  363. }
  364. return ERR_MP3_NONE;
  365. }