bitstream.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389
  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. * bitstream.c - bitstream unpacking, frame header parsing, side info parsing
  41. **************************************************************************************/
  42. #include "coder.h"
  43. #include "assembly.h"
  44. /**************************************************************************************
  45. * Function: SetBitstreamPointer
  46. *
  47. * Description: initialize bitstream reader
  48. *
  49. * Inputs: pointer to BitStreamInfo struct
  50. * number of bytes in bitstream
  51. * pointer to byte-aligned buffer of data to read from
  52. *
  53. * Outputs: filled bitstream info struct
  54. *
  55. * Return: none
  56. **************************************************************************************/
  57. void SetBitstreamPointer(BitStreamInfo *bsi, int nBytes, unsigned char *buf)
  58. {
  59. /* init bitstream */
  60. bsi->bytePtr = buf;
  61. bsi->iCache = 0; /* 4-byte unsigned int */
  62. bsi->cachedBits = 0; /* i.e. zero bits in cache */
  63. bsi->nBytes = nBytes;
  64. }
  65. /**************************************************************************************
  66. * Function: RefillBitstreamCache
  67. *
  68. * Description: read new data from bitstream buffer into bsi cache
  69. *
  70. * Inputs: pointer to initialized BitStreamInfo struct
  71. *
  72. * Outputs: updated bitstream info struct
  73. *
  74. * Return: none
  75. *
  76. * Notes: only call when iCache is completely drained (resets bitOffset to 0)
  77. * always loads 4 new bytes except when bsi->nBytes < 4 (end of buffer)
  78. * stores data as big-endian in cache, regardless of machine endian-ness
  79. *
  80. * TODO: optimize for ARM
  81. * possibly add little/big-endian modes for doing 32-bit loads
  82. **************************************************************************************/
  83. static __inline void RefillBitstreamCache(BitStreamInfo *bsi)
  84. {
  85. int nBytes = bsi->nBytes;
  86. /* optimize for common case, independent of machine endian-ness */
  87. if (nBytes >= 4) {
  88. bsi->iCache = (*bsi->bytePtr++) << 24;
  89. bsi->iCache |= (*bsi->bytePtr++) << 16;
  90. bsi->iCache |= (*bsi->bytePtr++) << 8;
  91. bsi->iCache |= (*bsi->bytePtr++);
  92. bsi->cachedBits = 32;
  93. bsi->nBytes -= 4;
  94. } else {
  95. bsi->iCache = 0;
  96. while (nBytes--) {
  97. bsi->iCache |= (*bsi->bytePtr++);
  98. bsi->iCache <<= 8;
  99. }
  100. bsi->iCache <<= ((3 - bsi->nBytes)*8);
  101. bsi->cachedBits = 8*bsi->nBytes;
  102. bsi->nBytes = 0;
  103. }
  104. }
  105. /**************************************************************************************
  106. * Function: GetBits
  107. *
  108. * Description: get bits from bitstream, advance bitstream pointer
  109. *
  110. * Inputs: pointer to initialized BitStreamInfo struct
  111. * number of bits to get from bitstream
  112. *
  113. * Outputs: updated bitstream info struct
  114. *
  115. * Return: the next nBits bits of data from bitstream buffer
  116. *
  117. * Notes: nBits must be in range [0, 31], nBits outside this range masked by 0x1f
  118. * for speed, does not indicate error if you overrun bit buffer
  119. * if nBits = 0, returns 0 (useful for scalefactor unpacking)
  120. *
  121. * TODO: optimize for ARM
  122. **************************************************************************************/
  123. unsigned int GetBits(BitStreamInfo *bsi, int nBits)
  124. {
  125. unsigned int data, lowBits;
  126. nBits &= 0x1f; /* nBits mod 32 to avoid unpredictable results like >> by negative amount */
  127. data = bsi->iCache >> (31 - nBits); /* unsigned >> so zero-extend */
  128. data >>= 1; /* do as >> 31, >> 1 so that nBits = 0 works okay (returns 0) */
  129. bsi->iCache <<= nBits; /* left-justify cache */
  130. bsi->cachedBits -= nBits; /* how many bits have we drawn from the cache so far */
  131. /* if we cross an int boundary, refill the cache */
  132. if (bsi->cachedBits < 0) {
  133. lowBits = -bsi->cachedBits;
  134. RefillBitstreamCache(bsi);
  135. data |= bsi->iCache >> (32 - lowBits); /* get the low-order bits */
  136. bsi->cachedBits -= lowBits; /* how many bits have we drawn from the cache so far */
  137. bsi->iCache <<= lowBits; /* left-justify cache */
  138. }
  139. return data;
  140. }
  141. /**************************************************************************************
  142. * Function: CalcBitsUsed
  143. *
  144. * Description: calculate how many bits have been read from bitstream
  145. *
  146. * Inputs: pointer to initialized BitStreamInfo struct
  147. * pointer to start of bitstream buffer
  148. * bit offset into first byte of startBuf (0-7)
  149. *
  150. * Outputs: none
  151. *
  152. * Return: number of bits read from bitstream, as offset from startBuf:startOffset
  153. **************************************************************************************/
  154. int CalcBitsUsed(BitStreamInfo *bsi, unsigned char *startBuf, int startOffset)
  155. {
  156. int bitsUsed;
  157. bitsUsed = (bsi->bytePtr - startBuf) * 8;
  158. bitsUsed -= bsi->cachedBits;
  159. bitsUsed -= startOffset;
  160. return bitsUsed;
  161. }
  162. /**************************************************************************************
  163. * Function: CheckPadBit
  164. *
  165. * Description: check whether padding byte is present in an MP3 frame
  166. *
  167. * Inputs: MP3DecInfo struct with valid FrameHeader struct
  168. * (filled by UnpackFrameHeader())
  169. *
  170. * Outputs: none
  171. *
  172. * Return: 1 if pad bit is set, 0 if not, -1 if null input pointer
  173. **************************************************************************************/
  174. int CheckPadBit(MP3DecInfo *mp3DecInfo)
  175. {
  176. FrameHeader *fh;
  177. /* validate pointers */
  178. if (!mp3DecInfo || !mp3DecInfo->FrameHeaderPS)
  179. return -1;
  180. fh = ((FrameHeader *)(mp3DecInfo->FrameHeaderPS));
  181. return (fh->paddingBit ? 1 : 0);
  182. }
  183. /**************************************************************************************
  184. * Function: UnpackFrameHeader
  185. *
  186. * Description: parse the fields of the MP3 frame header
  187. *
  188. * Inputs: buffer pointing to a complete MP3 frame header (4 bytes, plus 2 if CRC)
  189. *
  190. * Outputs: filled frame header info in the MP3DecInfo structure
  191. * updated platform-specific FrameHeader struct
  192. *
  193. * Return: length (in bytes) of frame header (for caller to calculate offset to
  194. * first byte following frame header)
  195. * -1 if null frameHeader or invalid header
  196. *
  197. * TODO: check for valid modes, depending on capabilities of decoder
  198. * test CRC on actual stream (verify no endian problems)
  199. **************************************************************************************/
  200. int UnpackFrameHeader(MP3DecInfo *mp3DecInfo, unsigned char *buf)
  201. {
  202. int verIdx;
  203. FrameHeader *fh;
  204. /* validate pointers and sync word */
  205. if (!mp3DecInfo || !mp3DecInfo->FrameHeaderPS || (buf[0] & SYNCWORDH) != SYNCWORDH || (buf[1] & SYNCWORDL) != SYNCWORDL)
  206. return -1;
  207. fh = ((FrameHeader *)(mp3DecInfo->FrameHeaderPS));
  208. /* read header fields - use bitmasks instead of GetBits() for speed, since format never varies */
  209. verIdx = (buf[1] >> 3) & 0x03;
  210. fh->ver = (MPEGVersion)( verIdx == 0 ? MPEG25 : ((verIdx & 0x01) ? MPEG1 : MPEG2) );
  211. fh->layer = 4 - ((buf[1] >> 1) & 0x03); /* easy mapping of index to layer number, 4 = error */
  212. fh->crc = 1 - ((buf[1] >> 0) & 0x01);
  213. fh->brIdx = (buf[2] >> 4) & 0x0f;
  214. fh->srIdx = (buf[2] >> 2) & 0x03;
  215. fh->paddingBit = (buf[2] >> 1) & 0x01;
  216. fh->privateBit = (buf[2] >> 0) & 0x01;
  217. fh->sMode = (StereoMode)((buf[3] >> 6) & 0x03); /* maps to correct enum (see definition) */
  218. fh->modeExt = (buf[3] >> 4) & 0x03;
  219. fh->copyFlag = (buf[3] >> 3) & 0x01;
  220. fh->origFlag = (buf[3] >> 2) & 0x01;
  221. fh->emphasis = (buf[3] >> 0) & 0x03;
  222. /* check parameters to avoid indexing tables with bad values */
  223. if (fh->srIdx == 3 || fh->layer == 4 || fh->brIdx == 15)
  224. return -1;
  225. fh->sfBand = &sfBandTable[fh->ver][fh->srIdx]; /* for readability (we reference sfBandTable many times in decoder) */
  226. if (fh->sMode != Joint) /* just to be safe (dequant, stproc check fh->modeExt) */
  227. fh->modeExt = 0;
  228. /* init user-accessible data */
  229. mp3DecInfo->nChans = (fh->sMode == Mono ? 1 : 2);
  230. mp3DecInfo->samprate = samplerateTab[fh->ver][fh->srIdx];
  231. mp3DecInfo->nGrans = (fh->ver == MPEG1 ? NGRANS_MPEG1 : NGRANS_MPEG2);
  232. mp3DecInfo->nGranSamps = ((int)samplesPerFrameTab[fh->ver][fh->layer - 1]) / mp3DecInfo->nGrans;
  233. mp3DecInfo->layer = fh->layer;
  234. mp3DecInfo->version = fh->ver;
  235. /* get bitrate and nSlots from table, unless brIdx == 0 (free mode) in which case caller must figure it out himself
  236. * question - do we want to overwrite mp3DecInfo->bitrate with 0 each time if it's free mode, and
  237. * copy the pre-calculated actual free bitrate into it in mp3dec.c (according to the spec,
  238. * this shouldn't be necessary, since it should be either all frames free or none free)
  239. */
  240. if (fh->brIdx) {
  241. mp3DecInfo->bitrate = ((int)bitrateTab[fh->ver][fh->layer - 1][fh->brIdx]) * 1000;
  242. /* nSlots = total frame bytes (from table) - sideInfo bytes - header - CRC (if present) + pad (if present) */
  243. mp3DecInfo->nSlots = (int)slotTab[fh->ver][fh->srIdx][fh->brIdx] -
  244. (int)sideBytesTab[fh->ver][(fh->sMode == Mono ? 0 : 1)] -
  245. 4 - (fh->crc ? 2 : 0) + (fh->paddingBit ? 1 : 0);
  246. }
  247. /* load crc word, if enabled, and return length of frame header (in bytes) */
  248. if (fh->crc) {
  249. fh->CRCWord = ((int)buf[4] << 8 | (int)buf[5] << 0);
  250. return 6;
  251. } else {
  252. fh->CRCWord = 0;
  253. return 4;
  254. }
  255. }
  256. /**************************************************************************************
  257. * Function: UnpackSideInfo
  258. *
  259. * Description: parse the fields of the MP3 side info header
  260. *
  261. * Inputs: MP3DecInfo structure filled by UnpackFrameHeader()
  262. * buffer pointing to the MP3 side info data
  263. *
  264. * Outputs: updated mainDataBegin in MP3DecInfo struct
  265. * updated private (platform-specific) SideInfo struct
  266. *
  267. * Return: length (in bytes) of side info data
  268. * -1 if null input pointers
  269. **************************************************************************************/
  270. int UnpackSideInfo(MP3DecInfo *mp3DecInfo, unsigned char *buf)
  271. {
  272. int gr, ch, bd, nBytes;
  273. BitStreamInfo bitStreamInfo, *bsi;
  274. FrameHeader *fh;
  275. SideInfo *si;
  276. SideInfoSub *sis;
  277. /* validate pointers and sync word */
  278. if (!mp3DecInfo || !mp3DecInfo->FrameHeaderPS || !mp3DecInfo->SideInfoPS)
  279. return -1;
  280. fh = ((FrameHeader *)(mp3DecInfo->FrameHeaderPS));
  281. si = ((SideInfo *)(mp3DecInfo->SideInfoPS));
  282. bsi = &bitStreamInfo;
  283. if (fh->ver == MPEG1) {
  284. /* MPEG 1 */
  285. nBytes = (fh->sMode == Mono ? SIBYTES_MPEG1_MONO : SIBYTES_MPEG1_STEREO);
  286. SetBitstreamPointer(bsi, nBytes, buf);
  287. si->mainDataBegin = GetBits(bsi, 9);
  288. si->privateBits = GetBits(bsi, (fh->sMode == Mono ? 5 : 3));
  289. for (ch = 0; ch < mp3DecInfo->nChans; ch++)
  290. for (bd = 0; bd < MAX_SCFBD; bd++)
  291. si->scfsi[ch][bd] = GetBits(bsi, 1);
  292. } else {
  293. /* MPEG 2, MPEG 2.5 */
  294. nBytes = (fh->sMode == Mono ? SIBYTES_MPEG2_MONO : SIBYTES_MPEG2_STEREO);
  295. SetBitstreamPointer(bsi, nBytes, buf);
  296. si->mainDataBegin = GetBits(bsi, 8);
  297. si->privateBits = GetBits(bsi, (fh->sMode == Mono ? 1 : 2));
  298. }
  299. for(gr =0; gr < mp3DecInfo->nGrans; gr++) {
  300. for (ch = 0; ch < mp3DecInfo->nChans; ch++) {
  301. sis = &si->sis[gr][ch]; /* side info subblock for this granule, channel */
  302. sis->part23Length = GetBits(bsi, 12);
  303. sis->nBigvals = GetBits(bsi, 9);
  304. sis->globalGain = GetBits(bsi, 8);
  305. sis->sfCompress = GetBits(bsi, (fh->ver == MPEG1 ? 4 : 9));
  306. sis->winSwitchFlag = GetBits(bsi, 1);
  307. if(sis->winSwitchFlag) {
  308. /* this is a start, stop, short, or mixed block */
  309. sis->blockType = GetBits(bsi, 2); /* 0 = normal, 1 = start, 2 = short, 3 = stop */
  310. sis->mixedBlock = GetBits(bsi, 1); /* 0 = not mixed, 1 = mixed */
  311. sis->tableSelect[0] = GetBits(bsi, 5);
  312. sis->tableSelect[1] = GetBits(bsi, 5);
  313. sis->tableSelect[2] = 0; /* unused */
  314. sis->subBlockGain[0] = GetBits(bsi, 3);
  315. sis->subBlockGain[1] = GetBits(bsi, 3);
  316. sis->subBlockGain[2] = GetBits(bsi, 3);
  317. /* TODO - check logic */
  318. if (sis->blockType == 0) {
  319. /* this should not be allowed, according to spec */
  320. sis->nBigvals = 0;
  321. sis->part23Length = 0;
  322. sis->sfCompress = 0;
  323. } else if (sis->blockType == 2 && sis->mixedBlock == 0) {
  324. /* short block, not mixed */
  325. sis->region0Count = 8;
  326. } else {
  327. /* start, stop, or short-mixed */
  328. sis->region0Count = 7;
  329. }
  330. sis->region1Count = 20 - sis->region0Count;
  331. } else {
  332. /* this is a normal block */
  333. sis->blockType = 0;
  334. sis->mixedBlock = 0;
  335. sis->tableSelect[0] = GetBits(bsi, 5);
  336. sis->tableSelect[1] = GetBits(bsi, 5);
  337. sis->tableSelect[2] = GetBits(bsi, 5);
  338. sis->region0Count = GetBits(bsi, 4);
  339. sis->region1Count = GetBits(bsi, 3);
  340. }
  341. sis->preFlag = (fh->ver == MPEG1 ? GetBits(bsi, 1) : 0);
  342. sis->sfactScale = GetBits(bsi, 1);
  343. sis->count1TableSelect = GetBits(bsi, 1);
  344. }
  345. }
  346. mp3DecInfo->mainDataBegin = si->mainDataBegin; /* needed by main decode loop */
  347. ASSERT(nBytes == CalcBitsUsed(bsi, buf, 0) >> 3);
  348. return nBytes;
  349. }