2 * 11/19/04 1.0 moved to LGPL.
4 * 11/17/04 Uncomplete frames discarded. E.B, javalayer@javazoom.net
6 * 12/05/03 ID3v2 tag returned. E.B, javalayer@javazoom.net
8 * 12/12/99 Based on Ibitstream. Exceptions thrown on errors,
9 * Temporary removed seek functionality. mdm@techie.com
11 * 02/12/99 : Java Conversion by E.B , javalayer@javazoom.net
13 * 04/14/97 : Added function prototypes for new syncing and seeking
14 * mechanisms. Also made this file portable. Changes made by Jeff Tsay
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.
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.
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 *----------------------------------------------------------------------
37 * The <code>Bistream</code> class is responsible for parsing an MPEG audio
40 * <b>REVIEW:</b> much of the parsing currently occurs in the various decoders.
41 * This should be moved into this class and associated inner classes.
43 public final class Bitstream implements BitstreamErrors {
45 * Synchronization control constant for the initial synchronization to the
49 static byte INITIAL_SYNC = 0;
52 * Synchronization control constant for non-initial frame synchronizations.
56 static byte STRICT_SYNC = 1;
58 // max. 1730 bytes per frame: 144 * 384kbit/s / 32000 Hz + 2 Bytes CRC
60 * Maximum size of the frame buffer.
63 private static final int BUFFER_INT_SIZE = 433;
66 * The frame buffer that holds the data for the current frame.
69 private final int[] framebuffer = new int[BUFFER_INT_SIZE];
72 * Number of valid bytes in the frame buffer.
75 private int framesize;
78 * The bytes read from the stream.
81 private byte[] frame_bytes = new byte[BUFFER_INT_SIZE * 4];
84 * Index into <code>framebuffer</code> where the next bits are retrieved.
87 private int wordpointer;
90 * Number (0-31, from MSB to LSB) of next bit for get_bits()
96 * The current specified syncword
102 * Audio header position in stream.
105 private int header_pos = 0;
111 private boolean single_ch_mode;
112 // private int current_frame_number;
113 // private int last_frame_number;
116 private final int bitmask[] = {
118 0x00000001, 0x00000003, 0x00000007, 0x0000000F, 0x0000001F, 0x0000003F, 0x0000007F,
119 0x000000FF, 0x000001FF, 0x000003FF, 0x000007FF, 0x00000FFF, 0x00001FFF, 0x00003FFF,
120 0x00007FFF, 0x0000FFFF, 0x0001FFFF };
123 private final PushbackInputStream source;
126 private final Header header = new Header();
129 private final byte syncbuf[] = new byte[4];
132 private Crc16[] crc = new Crc16[1];
135 private byte[] rawid3v2 = null;
138 private boolean firstframe = true;
140 private BitReserve br;
141 private int main_data_begin;
142 private int frame_start;
145 * Construct a IBitstream that reads data from a given InputStream.
148 * The InputStream to read from.
150 public Bitstream(InputStream in) {
152 throw new NullPointerException("in");
153 in = new BufferedInputStream(in);
156 // source = new PushbackInputStream(in, 1024);
157 source = new PushbackInputStream(in, BUFFER_INT_SIZE * 4);
160 // current_frame_number = -1;
161 // last_frame_number = -1;
163 br = new BitReserve();
168 * Return position of the first audio header.
170 * @return size of ID3v2 tag frames.
172 public int header_pos() {
183 private void loadID3v2(InputStream in) {
186 // Read ID3v2 header (10 bytes).
188 size = readID3v2Header(in);
190 } catch (IOException e) {
193 // Unread ID3v2 header (10 bytes).
195 } catch (IOException e) {
201 rawid3v2 = new byte[size];
202 in.read(rawid3v2, 0, rawid3v2.length);
204 } catch (IOException e) {
209 * Parse ID3v2 tag header to find out size of ID3v2 frames.
213 * @return size of ID3v2 frames + header
214 * @throws IOException
217 private int readID3v2Header(InputStream in) throws IOException {
218 byte[] id3header = new byte[4];
220 in.read(id3header, 0, 3);
222 if ((id3header[0] == 'I') && (id3header[1] == 'D') && (id3header[2] == '3')) {
223 in.read(id3header, 0, 3);
224 int majorVersion = id3header[0];
225 int revision = id3header[1];
226 in.read(id3header, 0, 4);
228 (int) (id3header[0] << 21) + (id3header[1] << 14) + (id3header[2] << 7) + (id3header[3]);
234 * Return raw ID3v2 frames + header.
236 * @return ID3v2 InputStream or null if ID3v2 frames are not available.
238 public InputStream getRawID3v2() {
239 if (rawid3v2 == null)
242 ByteArrayInputStream bain = new ByteArrayInputStream(rawid3v2);
248 * Close the Bitstream.
250 * @throws BitstreamException
252 public void close() throws BitstreamException {
255 } catch (IOException ex) {
256 throw newBitstreamException(STREAM_ERROR, ex);
261 * Reads and parses the next frame from the input source.
263 * @return the Header describing details of the frame read, or null if the end
264 * of the stream has been reached.
266 public Header readFrame() throws BitstreamException {
268 Header result = null;
270 result = readNextFrame();
271 if (result == null) {
274 // E.B, Parse VBR (if any) first frame.
275 if (firstframe == true) {
276 result.parseVBR(frame_bytes);
280 int channels = (header.mode() == Header.SINGLE_CHANNEL) ? 1 : 2;
282 result.setSideInfoBuf(getSideInfoBuffer(channels));
283 result.setBitReserve(getBitReserve(result.slots()));
287 } catch (BitstreamException ex) {
288 if ((ex.getErrorCode() == INVALIDFRAME)) {
289 // Try to skip this frame.
290 // System.out.println("INVALIDFRAME");
293 result = readNextFrame();
294 } catch (BitstreamException e) {
295 if ((e.getErrorCode() != STREAM_EOF)) {
296 // wrap original exception so stack trace is maintained.
297 throw newBitstreamException(e.getErrorCode(), e);
300 } else if ((ex.getErrorCode() != STREAM_EOF)) {
301 // wrap original exception so stack trace is maintained.
302 throw newBitstreamException(ex.getErrorCode(), ex);
310 * Read next MP3 frame.
312 * @return MP3 frame header.
313 * @throws BitstreamException
315 private Header readNextFrame() throws BitstreamException {
316 if (framesize == -1) {
317 if (nextFrame() == -1) {
325 * Read next MP3 frame.
327 * @throws BitstreamException
329 private int nextFrame() throws BitstreamException {
330 // entire frame is read by the header class.
331 // header.read_header(this, crc);
332 return header.read_header(this, crc);
336 * Unreads the bytes read from the frame.
338 * @throws BitstreamException
340 // REVIEW: add new error codes for this.
341 public void unreadFrame() throws BitstreamException {
342 if (wordpointer == -1 && bitindex == -1 && (framesize > 0)) {
344 source.unread(frame_bytes, 0, framesize);
345 } catch (IOException ex) {
346 throw newBitstreamException(STREAM_ERROR);
354 public void closeFrame() {
361 * Determines if the next 4 bytes of the stream represent a frame header.
363 public boolean isSyncCurrentPosition(int syncmode) throws BitstreamException {
364 int read = readBytes(syncbuf, 0, 4);
366 ((syncbuf[0] << 24) & 0xFF000000) | ((syncbuf[1] << 16) & 0x00FF0000)
367 | ((syncbuf[2] << 8) & 0x0000FF00) | ((syncbuf[3] << 0) & 0x000000FF);
370 source.unread(syncbuf, 0, read);
371 } catch (IOException ex) {
374 boolean sync = false;
380 sync = isSyncMark(headerstring, syncmode, syncword);
387 // REVIEW: this class should provide inner classes to
388 // parse the frame contents. Eventually, readBits will
390 public int readBits(int n) {
394 public int peek_bits(int number_of_bits) {
396 int peekbitindex = bitindex;
397 int peekPointer = wordpointer;
400 int sum = peekbitindex + number_of_bits;
402 if (peekPointer < 0) {
407 // all bits contained in *wordpointer
408 returnvalue = (framebuffer[peekPointer] >>> (32 - sum)) & bitmask[number_of_bits];
409 // returnvalue = (wordpointer[0] >> (32 - sum)) &
410 // bitmask[number_of_bits];
411 if ((peekbitindex += number_of_bits) == 32) {
413 peekPointer++; // added by me!
418 // E.B : Check that ?
419 // ((short[])&returnvalue)[0] = ((short[])wordpointer + 1)[0];
420 // wordpointer++; // Added by me!
421 // ((short[])&returnvalue + 1)[0] = ((short[])wordpointer)[0];
422 int Right = (framebuffer[peekPointer] & 0x0000FFFF);
424 int Left = (framebuffer[peekPointer] & 0xFFFF0000);
425 returnvalue = ((Right << 16) & 0xFFFF0000) | ((Left >>> 16) & 0x0000FFFF);
427 returnvalue >>>= 48 - sum; // returnvalue >>= 16 - (number_of_bits - (32
429 returnvalue &= bitmask[number_of_bits];
430 peekbitindex = sum - 32;
435 public int readCheckedBits(int n) {
436 // REVIEW: implement CRC check.
440 protected BitstreamException newBitstreamException(int errorcode) {
441 return new BitstreamException(errorcode, null);
444 protected BitstreamException newBitstreamException(int errorcode, Throwable throwable) {
445 return new BitstreamException(errorcode, throwable);
449 * Get next 32 bits from bitstream. They are stored in the headerstring.
450 * syncmod allows Synchro flag ID The returned value is False at the end of
454 int syncHeader(byte syncmode) throws BitstreamException {
457 // read additional 2 bytes
458 int bytesRead = readBytes(syncbuf, 0, 3);
461 throw newBitstreamException(STREAM_EOF, null);
464 ((syncbuf[0] << 16) & 0x00FF0000) | ((syncbuf[1] << 8) & 0x0000FF00)
465 | ((syncbuf[2] << 0) & 0x000000FF);
470 if (readBytes(syncbuf, 3, 1) != 1) {
471 // System.out.println("THROW NEW BITSTREAM EXCEPTION");
473 throw newBitstreamException(STREAM_EOF, null);
476 headerstring |= (syncbuf[3] & 0x000000FF);
478 sync = isSyncMark(headerstring, syncmode, syncword);
481 // current_frame_number++;
482 // if (last_frame_number < current_frame_number) last_frame_number =
483 // current_frame_number;
488 public boolean isSyncMark(int headerstring, int syncmode, int word) {
489 boolean sync = false;
491 if (syncmode == INITIAL_SYNC) {
492 // sync = ((headerstring & 0xFFF00000) == 0xFFF00000);
493 sync = ((headerstring & 0xFFE00000) == 0xFFE00000); // SZD: MPEG 2.5
496 ((headerstring & 0xFFF80C00) == word)
497 && (((headerstring & 0x000000C0) == 0x000000C0) == single_ch_mode);
500 // filter out invalid sample rate
502 sync = (((headerstring >>> 10) & 3) != 3);
503 // filter out invalid layer
505 sync = (((headerstring >>> 17) & 3) != 0);
506 // filter out invalid version
508 sync = (((headerstring >>> 19) & 3) != 1);
514 * Reads the data for the next frame. The frame is not parsed until parse
517 int read_frame_data(int bytesize) throws BitstreamException {
519 numread = readFully(frame_bytes, 0, bytesize);
520 framesize = bytesize;
527 * Parses the data previously read with read_frame_data().
530 void parse_frame() throws BitstreamException {
531 // Convert Bytes read to int
533 byte[] byteread = frame_bytes;
534 int bytesize = framesize;
536 // Check ID3v1 TAG (True only if last frame).
537 // for (int t=0;t<(byteread.length)-2;t++)
539 // if ((byteread[t]=='T') && (byteread[t+1]=='A') && (byteread[t+2]=='G'))
541 // System.out.println("ID3v1 detected at offset "+t);
542 // throw newBitstreamException(INVALIDFRAME, null);
546 for ( int k = 0; k < bytesize; k = k + 4) {
553 if (k + 1 < bytesize)
554 b1 = byteread[k + 1];
555 if (k + 2 < bytesize)
556 b2 = byteread[k + 2];
557 if (k + 3 < bytesize)
558 b3 = byteread[k + 3];
560 ((b0 << 24) & 0xFF000000) | ((b1 << 16) & 0x00FF0000) | ((b2 << 8) & 0x0000FF00)
568 * Read bits from buffer into the lower bits of an unsigned int. The LSB
569 * contains the latest read bit of the stream. (1 <= number_of_bits <= 16)
572 public int get_bits( int number_of_bits) {
575 int sum = bitindex + number_of_bits;
578 // There is a problem here, wordpointer could be -1 ?!
584 // all bits contained in *wordpointer
585 returnvalue = (framebuffer[wordpointer] >>> (32 - sum)) & bitmask[number_of_bits];
586 // returnvalue = (wordpointer[0] >> (32 - sum)) & bitmask[number_of_bits];
587 if ((bitindex += number_of_bits) == 32) {
589 wordpointer++; // added by me!
594 // E.B : Check that ?
595 // ((short[])&returnvalue)[0] = ((short[])wordpointer + 1)[0];
596 // wordpointer++; // Added by me!
597 // ((short[])&returnvalue + 1)[0] = ((short[])wordpointer)[0];
598 int Right = (framebuffer[wordpointer] & 0x0000FFFF);
600 int Left = (framebuffer[wordpointer] & 0xFFFF0000);
601 returnvalue = ((Right << 16) & 0xFFFF0000) | ((Left >>> 16) & 0x0000FFFF);
603 returnvalue >>>= 48 - sum; // returnvalue >>= 16 - (number_of_bits - (32 -
605 returnvalue &= bitmask[number_of_bits];
611 * Set the word we want to sync the header to. In Big-Endian byte order
613 void set_syncword( int syncword0) {
614 syncword = syncword0 & 0xFFFFFF3F;
615 single_ch_mode = ((syncword0 & 0x000000C0) == 0x000000C0);
619 * Reads the exact number of bytes from the source input stream into a byte
623 * The byte array to read the specified number of bytes into.
625 * The index in the array where the first byte read should be stored.
627 * the number of bytes to read.
629 * @exception BitstreamException
630 * is thrown if the specified number of bytes could not be read
635 private int readFully( byte[] b, int offs, int len)
636 throws BitstreamException {
640 int bytesread = source.read(b, offs, len);
641 if (bytesread == -1) {
646 // throw newBitstreamException(UNEXPECTED_EOF, new EOFException());
648 nRead = nRead + bytesread;
652 } catch (IOException ex) {
653 throw newBitstreamException(STREAM_ERROR, ex);
659 * Simlar to readFully, but doesn't throw exception when EOF is reached.
663 private int readBytes( byte[] b, int offs, int len)
664 throws BitstreamException {
665 int totalBytesRead = 0;
668 int bytesread = source.read(b, offs, len);
669 if (bytesread == -1) {
672 totalBytesRead += bytesread;
676 } catch (IOException ex) {
677 throw newBitstreamException(STREAM_ERROR, ex);
679 return totalBytesRead;
682 public SideInfoBuffer getSideInfoBuffer(int channelType) {
687 SideInfoBuffer sib = new SideInfoBuffer();
689 // first, store main_data_begin from the side inforamtion
690 main_data_begin = peek_bits(9);
693 if (channelType == 1) { // mono
694 max = wordpointer + 4;
696 max = wordpointer + 8;
700 for (; wordpointer < max; wordpointer++) {
701 sib.setBuffer(wordpointer, framebuffer[wordpointer]);
703 } catch (ArrayIndexOutOfBoundsException e) {
704 System.out.print("wordpointer=" + wordpointer);
705 System.out.println("framebuffer length=" + framebuffer.length);
711 public BitReserve getBitReserve(int nSlots) {
714 int bytes_to_discard;
717 for (i = 0; i < nSlots; i++)
718 br.hputbuf(get_bits(8));
720 int main_data_end = br.hsstell() >>> 3; // of previous frame
722 if ((flush_main = (br.hsstell() & 7)) != 0) {
723 br.hgetbits(8 - flush_main);
727 bytes_to_discard = frame_start - main_data_end - main_data_begin;
729 frame_start += nSlots;
731 if (bytes_to_discard < 0) {
735 if (main_data_end > 4096) {
737 br.rewindNbytes(4096);
740 for (; bytes_to_discard > 0; bytes_to_discard--)
743 // resynch index by trusted code
744 br.buf_byte_idx = br.totbit % br.BUFSIZE;