Bitstream.java 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655
  1. /*
  2. * 11/19/04 1.0 moved to LGPL.
  3. *
  4. * 11/17/04 Uncomplete frames discarded. E.B, javalayer@javazoom.net
  5. *
  6. * 12/05/03 ID3v2 tag returned. E.B, javalayer@javazoom.net
  7. *
  8. * 12/12/99 Based on Ibitstream. Exceptions thrown on errors,
  9. * Temporary removed seek functionality. mdm@techie.com
  10. *
  11. * 02/12/99 : Java Conversion by E.B , javalayer@javazoom.net
  12. *
  13. * 04/14/97 : Added function prototypes for new syncing and seeking
  14. * mechanisms. Also made this file portable. Changes made by Jeff Tsay
  15. *
  16. * @(#) ibitstream.h 1.5, last edit: 6/15/94 16:55:34
  17. * @(#) Copyright (C) 1993, 1994 Tobias Bading (bading@cs.tu-berlin.de)
  18. * @(#) Berlin University of Technology
  19. *-----------------------------------------------------------------------
  20. * This program is free software; you can redistribute it and/or modify
  21. * it under the terms of the GNU Library General Public License as published
  22. * by the Free Software Foundation; either version 2 of the License, or
  23. * (at your option) any later version.
  24. *
  25. * This program is distributed in the hope that it will be useful,
  26. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  27. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  28. * GNU Library General Public License for more details.
  29. *
  30. * You should have received a copy of the GNU Library General Public
  31. * License along with this program; if not, write to the Free Software
  32. * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  33. *----------------------------------------------------------------------
  34. */
  35. package javazoom.jl.decoder;
  36. import java.io.BufferedInputStream;
  37. import java.io.ByteArrayInputStream;
  38. import java.io.IOException;
  39. import java.io.InputStream;
  40. import java.io.PushbackInputStream;
  41. /**
  42. * The <code>Bistream</code> class is responsible for parsing
  43. * an MPEG audio bitstream.
  44. *
  45. * <b>REVIEW:</b> much of the parsing currently occurs in the
  46. * various decoders. This should be moved into this class and associated
  47. * inner classes.
  48. */
  49. public final class Bitstream implements BitstreamErrors
  50. {
  51. /**
  52. * Synchronization control constant for the initial
  53. * synchronization to the start of a frame.
  54. */
  55. static byte INITIAL_SYNC = 0;
  56. /**
  57. * Synchronization control constant for non-initial frame
  58. * synchronizations.
  59. */
  60. static byte STRICT_SYNC = 1;
  61. // max. 1730 bytes per frame: 144 * 384kbit/s / 32000 Hz + 2 Bytes CRC
  62. /**
  63. * Maximum size of the frame buffer.
  64. */
  65. private static final int BUFFER_INT_SIZE = 433;
  66. /**
  67. * The frame buffer that holds the data for the current frame.
  68. */
  69. private final int[] framebuffer = new int[BUFFER_INT_SIZE];
  70. /**
  71. * Number of valid bytes in the frame buffer.
  72. */
  73. private int framesize;
  74. /**
  75. * The bytes read from the stream.
  76. */
  77. private byte[] frame_bytes = new byte[BUFFER_INT_SIZE*4];
  78. /**
  79. * Index into <code>framebuffer</code> where the next bits are
  80. * retrieved.
  81. */
  82. private int wordpointer;
  83. /**
  84. * Number (0-31, from MSB to LSB) of next bit for get_bits()
  85. */
  86. private int bitindex;
  87. /**
  88. * The current specified syncword
  89. */
  90. private int syncword;
  91. /**
  92. * Audio header position in stream.
  93. */
  94. private int header_pos = 0;
  95. /**
  96. *
  97. */
  98. private boolean single_ch_mode;
  99. //private int current_frame_number;
  100. //private int last_frame_number;
  101. private final int bitmask[] = {0, // dummy
  102. 0x00000001, 0x00000003, 0x00000007, 0x0000000F,
  103. 0x0000001F, 0x0000003F, 0x0000007F, 0x000000FF,
  104. 0x000001FF, 0x000003FF, 0x000007FF, 0x00000FFF,
  105. 0x00001FFF, 0x00003FFF, 0x00007FFF, 0x0000FFFF,
  106. 0x0001FFFF };
  107. private final PushbackInputStream source;
  108. private final Header header = new Header();
  109. private final byte syncbuf[] = new byte[4];
  110. private Crc16[] crc = new Crc16[1];
  111. private byte[] rawid3v2 = null;
  112. private boolean firstframe = true;
  113. /**
  114. * Construct a IBitstream that reads data from a
  115. * given InputStream.
  116. *
  117. * @param in The InputStream to read from.
  118. */
  119. public Bitstream(InputStream in)
  120. {
  121. if (in==null) throw new NullPointerException("in");
  122. in = new BufferedInputStream(in);
  123. loadID3v2(in);
  124. firstframe = true;
  125. //source = new PushbackInputStream(in, 1024);
  126. source = new PushbackInputStream(in, BUFFER_INT_SIZE*4);
  127. closeFrame();
  128. //current_frame_number = -1;
  129. //last_frame_number = -1;
  130. }
  131. /**
  132. * Return position of the first audio header.
  133. * @return size of ID3v2 tag frames.
  134. */
  135. public int header_pos()
  136. {
  137. return header_pos;
  138. }
  139. /**
  140. * Load ID3v2 frames.
  141. * @param in MP3 InputStream.
  142. * @author JavaZOOM
  143. */
  144. private void loadID3v2(InputStream in)
  145. {
  146. int size = -1;
  147. try
  148. {
  149. // Read ID3v2 header (10 bytes).
  150. in.mark(10);
  151. size = readID3v2Header(in);
  152. header_pos = size;
  153. }
  154. catch (IOException e)
  155. {}
  156. finally
  157. {
  158. try
  159. {
  160. // Unread ID3v2 header (10 bytes).
  161. in.reset();
  162. }
  163. catch (IOException e)
  164. {}
  165. }
  166. // Load ID3v2 tags.
  167. try
  168. {
  169. if (size > 0)
  170. {
  171. rawid3v2 = new byte[size];
  172. in.read(rawid3v2,0,rawid3v2.length);
  173. }
  174. }
  175. catch (IOException e)
  176. {}
  177. }
  178. /**
  179. * Parse ID3v2 tag header to find out size of ID3v2 frames.
  180. * @param in MP3 InputStream
  181. * @return size of ID3v2 frames + header
  182. * @throws IOException
  183. * @author JavaZOOM
  184. */
  185. private int readID3v2Header(InputStream in) throws IOException
  186. {
  187. byte[] id3header = new byte[4];
  188. int size = -10;
  189. in.read(id3header,0,3);
  190. // Look for ID3v2
  191. if ( (id3header[0]=='I') && (id3header[1]=='D') && (id3header[2]=='3'))
  192. {
  193. in.read(id3header,0,3);
  194. int majorVersion = id3header[0];
  195. int revision = id3header[1];
  196. in.read(id3header,0,4);
  197. size = (int) (id3header[0] << 21) + (id3header[1] << 14) + (id3header[2] << 7) + (id3header[3]);
  198. }
  199. return (size+10);
  200. }
  201. /**
  202. * Return raw ID3v2 frames + header.
  203. * @return ID3v2 InputStream or null if ID3v2 frames are not available.
  204. */
  205. public InputStream getRawID3v2()
  206. {
  207. if (rawid3v2 == null) return null;
  208. else
  209. {
  210. ByteArrayInputStream bain = new ByteArrayInputStream(rawid3v2);
  211. return bain;
  212. }
  213. }
  214. /**
  215. * Close the Bitstream.
  216. * @throws BitstreamException
  217. */
  218. public void close() throws BitstreamException
  219. {
  220. try
  221. {
  222. source.close();
  223. }
  224. catch (IOException ex)
  225. {
  226. throw newBitstreamException(STREAM_ERROR, ex);
  227. }
  228. }
  229. /**
  230. * Reads and parses the next frame from the input source.
  231. * @return the Header describing details of the frame read,
  232. * or null if the end of the stream has been reached.
  233. */
  234. public Header readFrame() throws BitstreamException
  235. {
  236. Header result = null;
  237. try
  238. {
  239. result = readNextFrame();
  240. // E.B, Parse VBR (if any) first frame.
  241. if (firstframe == true)
  242. {
  243. result.parseVBR(frame_bytes);
  244. firstframe = false;
  245. }
  246. }
  247. catch (BitstreamException ex)
  248. {
  249. if ((ex.getErrorCode()==INVALIDFRAME))
  250. {
  251. // Try to skip this frame.
  252. //System.out.println("INVALIDFRAME");
  253. try
  254. {
  255. closeFrame();
  256. result = readNextFrame();
  257. }
  258. catch (BitstreamException e)
  259. {
  260. if ((e.getErrorCode()!=STREAM_EOF))
  261. {
  262. // wrap original exception so stack trace is maintained.
  263. throw newBitstreamException(e.getErrorCode(), e);
  264. }
  265. }
  266. }
  267. else if ((ex.getErrorCode()!=STREAM_EOF))
  268. {
  269. // wrap original exception so stack trace is maintained.
  270. throw newBitstreamException(ex.getErrorCode(), ex);
  271. }
  272. }
  273. return result;
  274. }
  275. /**
  276. * Read next MP3 frame.
  277. * @return MP3 frame header.
  278. * @throws BitstreamException
  279. */
  280. private Header readNextFrame() throws BitstreamException
  281. {
  282. if (framesize == -1)
  283. {
  284. nextFrame();
  285. }
  286. return header;
  287. }
  288. /**
  289. * Read next MP3 frame.
  290. * @throws BitstreamException
  291. */
  292. private void nextFrame() throws BitstreamException
  293. {
  294. // entire frame is read by the header class.
  295. header.read_header(this, crc);
  296. }
  297. /**
  298. * Unreads the bytes read from the frame.
  299. * @throws BitstreamException
  300. */
  301. // REVIEW: add new error codes for this.
  302. public void unreadFrame() throws BitstreamException
  303. {
  304. if (wordpointer==-1 && bitindex==-1 && (framesize>0))
  305. {
  306. try
  307. {
  308. source.unread(frame_bytes, 0, framesize);
  309. }
  310. catch (IOException ex)
  311. {
  312. throw newBitstreamException(STREAM_ERROR);
  313. }
  314. }
  315. }
  316. /**
  317. * Close MP3 frame.
  318. */
  319. public void closeFrame()
  320. {
  321. framesize = -1;
  322. wordpointer = -1;
  323. bitindex = -1;
  324. }
  325. /**
  326. * Determines if the next 4 bytes of the stream represent a
  327. * frame header.
  328. */
  329. public boolean isSyncCurrentPosition(int syncmode) throws BitstreamException
  330. {
  331. int read = readBytes(syncbuf, 0, 4);
  332. int headerstring = ((syncbuf[0] << 24) & 0xFF000000) | ((syncbuf[1] << 16) & 0x00FF0000) | ((syncbuf[2] << 8) & 0x0000FF00) | ((syncbuf[3] << 0) & 0x000000FF);
  333. try
  334. {
  335. source.unread(syncbuf, 0, read);
  336. }
  337. catch (IOException ex)
  338. {
  339. }
  340. boolean sync = false;
  341. switch (read)
  342. {
  343. case 0:
  344. sync = true;
  345. break;
  346. case 4:
  347. sync = isSyncMark(headerstring, syncmode, syncword);
  348. break;
  349. }
  350. return sync;
  351. }
  352. // REVIEW: this class should provide inner classes to
  353. // parse the frame contents. Eventually, readBits will
  354. // be removed.
  355. public int readBits(int n)
  356. {
  357. return get_bits(n);
  358. }
  359. public int readCheckedBits(int n)
  360. {
  361. // REVIEW: implement CRC check.
  362. return get_bits(n);
  363. }
  364. protected BitstreamException newBitstreamException(int errorcode)
  365. {
  366. return new BitstreamException(errorcode, null);
  367. }
  368. protected BitstreamException newBitstreamException(int errorcode, Throwable throwable)
  369. {
  370. return new BitstreamException(errorcode, throwable);
  371. }
  372. /**
  373. * Get next 32 bits from bitstream.
  374. * They are stored in the headerstring.
  375. * syncmod allows Synchro flag ID
  376. * The returned value is False at the end of stream.
  377. */
  378. int syncHeader(byte syncmode) throws BitstreamException
  379. {
  380. boolean sync;
  381. int headerstring;
  382. // read additional 2 bytes
  383. int bytesRead = readBytes(syncbuf, 0, 3);
  384. if (bytesRead!=3) throw newBitstreamException(STREAM_EOF, null);
  385. headerstring = ((syncbuf[0] << 16) & 0x00FF0000) | ((syncbuf[1] << 8) & 0x0000FF00) | ((syncbuf[2] << 0) & 0x000000FF);
  386. do
  387. {
  388. headerstring <<= 8;
  389. if (readBytes(syncbuf, 3, 1)!=1)
  390. throw newBitstreamException(STREAM_EOF, null);
  391. headerstring |= (syncbuf[3] & 0x000000FF);
  392. sync = isSyncMark(headerstring, syncmode, syncword);
  393. }
  394. while (!sync);
  395. //current_frame_number++;
  396. //if (last_frame_number < current_frame_number) last_frame_number = current_frame_number;
  397. return headerstring;
  398. }
  399. public boolean isSyncMark(int headerstring, int syncmode, int word)
  400. {
  401. boolean sync = false;
  402. if (syncmode == INITIAL_SYNC)
  403. {
  404. //sync = ((headerstring & 0xFFF00000) == 0xFFF00000);
  405. sync = ((headerstring & 0xFFE00000) == 0xFFE00000); // SZD: MPEG 2.5
  406. }
  407. else
  408. {
  409. sync = ((headerstring & 0xFFF80C00) == word) &&
  410. (((headerstring & 0x000000C0) == 0x000000C0) == single_ch_mode);
  411. }
  412. // filter out invalid sample rate
  413. if (sync)
  414. sync = (((headerstring >>> 10) & 3)!=3);
  415. // filter out invalid layer
  416. if (sync)
  417. sync = (((headerstring >>> 17) & 3)!=0);
  418. // filter out invalid version
  419. if (sync)
  420. sync = (((headerstring >>> 19) & 3)!=1);
  421. return sync;
  422. }
  423. /**
  424. * Reads the data for the next frame. The frame is not parsed
  425. * until parse frame is called.
  426. */
  427. int read_frame_data(int bytesize) throws BitstreamException
  428. {
  429. int numread = 0;
  430. numread = readFully(frame_bytes, 0, bytesize);
  431. framesize = bytesize;
  432. wordpointer = -1;
  433. bitindex = -1;
  434. return numread;
  435. }
  436. /**
  437. * Parses the data previously read with read_frame_data().
  438. */
  439. void parse_frame() throws BitstreamException
  440. {
  441. // Convert Bytes read to int
  442. int b=0;
  443. byte[] byteread = frame_bytes;
  444. int bytesize = framesize;
  445. // Check ID3v1 TAG (True only if last frame).
  446. //for (int t=0;t<(byteread.length)-2;t++)
  447. //{
  448. // if ((byteread[t]=='T') && (byteread[t+1]=='A') && (byteread[t+2]=='G'))
  449. // {
  450. // System.out.println("ID3v1 detected at offset "+t);
  451. // throw newBitstreamException(INVALIDFRAME, null);
  452. // }
  453. //}
  454. for (int k=0;k<bytesize;k=k+4)
  455. {
  456. int convert = 0;
  457. byte b0 = 0;
  458. byte b1 = 0;
  459. byte b2 = 0;
  460. byte b3 = 0;
  461. b0 = byteread[k];
  462. if (k+1<bytesize) b1 = byteread[k+1];
  463. if (k+2<bytesize) b2 = byteread[k+2];
  464. if (k+3<bytesize) b3 = byteread[k+3];
  465. framebuffer[b++] = ((b0 << 24) &0xFF000000) | ((b1 << 16) & 0x00FF0000) | ((b2 << 8) & 0x0000FF00) | (b3 & 0x000000FF);
  466. }
  467. wordpointer = 0;
  468. bitindex = 0;
  469. }
  470. /**
  471. * Read bits from buffer into the lower bits of an unsigned int.
  472. * The LSB contains the latest read bit of the stream.
  473. * (1 <= number_of_bits <= 16)
  474. */
  475. public int get_bits(int number_of_bits)
  476. {
  477. int returnvalue = 0;
  478. int sum = bitindex + number_of_bits;
  479. // E.B
  480. // There is a problem here, wordpointer could be -1 ?!
  481. if (wordpointer < 0) wordpointer = 0;
  482. // E.B : End.
  483. if (sum <= 32)
  484. {
  485. // all bits contained in *wordpointer
  486. returnvalue = (framebuffer[wordpointer] >>> (32 - sum)) & bitmask[number_of_bits];
  487. // returnvalue = (wordpointer[0] >> (32 - sum)) & bitmask[number_of_bits];
  488. if ((bitindex += number_of_bits) == 32)
  489. {
  490. bitindex = 0;
  491. wordpointer++; // added by me!
  492. }
  493. return returnvalue;
  494. }
  495. // E.B : Check that ?
  496. //((short[])&returnvalue)[0] = ((short[])wordpointer + 1)[0];
  497. //wordpointer++; // Added by me!
  498. //((short[])&returnvalue + 1)[0] = ((short[])wordpointer)[0];
  499. int Right = (framebuffer[wordpointer] & 0x0000FFFF);
  500. wordpointer++;
  501. int Left = (framebuffer[wordpointer] & 0xFFFF0000);
  502. returnvalue = ((Right << 16) & 0xFFFF0000) | ((Left >>> 16)& 0x0000FFFF);
  503. returnvalue >>>= 48 - sum; // returnvalue >>= 16 - (number_of_bits - (32 - bitindex))
  504. returnvalue &= bitmask[number_of_bits];
  505. bitindex = sum - 32;
  506. return returnvalue;
  507. }
  508. /**
  509. * Set the word we want to sync the header to.
  510. * In Big-Endian byte order
  511. */
  512. void set_syncword(int syncword0)
  513. {
  514. syncword = syncword0 & 0xFFFFFF3F;
  515. single_ch_mode = ((syncword0 & 0x000000C0) == 0x000000C0);
  516. }
  517. /**
  518. * Reads the exact number of bytes from the source
  519. * input stream into a byte array.
  520. *
  521. * @param b The byte array to read the specified number
  522. * of bytes into.
  523. * @param offs The index in the array where the first byte
  524. * read should be stored.
  525. * @param len the number of bytes to read.
  526. *
  527. * @exception BitstreamException is thrown if the specified
  528. * number of bytes could not be read from the stream.
  529. */
  530. private int readFully(byte[] b, int offs, int len)
  531. throws BitstreamException
  532. {
  533. int nRead = 0;
  534. try
  535. {
  536. while (len > 0)
  537. {
  538. int bytesread = source.read(b, offs, len);
  539. if (bytesread == -1)
  540. {
  541. while (len-->0)
  542. {
  543. b[offs++] = 0;
  544. }
  545. break;
  546. //throw newBitstreamException(UNEXPECTED_EOF, new EOFException());
  547. }
  548. nRead = nRead + bytesread;
  549. offs += bytesread;
  550. len -= bytesread;
  551. }
  552. }
  553. catch (IOException ex)
  554. {
  555. throw newBitstreamException(STREAM_ERROR, ex);
  556. }
  557. return nRead;
  558. }
  559. /**
  560. * Simlar to readFully, but doesn't throw exception when
  561. * EOF is reached.
  562. */
  563. private int readBytes(byte[] b, int offs, int len)
  564. throws BitstreamException
  565. {
  566. int totalBytesRead = 0;
  567. try
  568. {
  569. while (len > 0)
  570. {
  571. int bytesread = source.read(b, offs, len);
  572. if (bytesread == -1)
  573. {
  574. break;
  575. }
  576. totalBytesRead += bytesread;
  577. offs += bytesread;
  578. len -= bytesread;
  579. }
  580. }
  581. catch (IOException ex)
  582. {
  583. throw newBitstreamException(STREAM_ERROR, ex);
  584. }
  585. return totalBytesRead;
  586. }
  587. }