mp3dec.c 16 KB

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