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 @LATTICE("FB<F,FF<F,WP<BI,FF*,WP*,BI*")
44 @METHODDEFAULT("OUT<THIS,THIS<VAR,VAR<IN,VAR*,THISLOC=THIS,GLOBALLOC=IN")
45 public final class Bitstream implements BitstreamErrors {
47 * Synchronization control constant for the initial synchronization to the
51 static byte INITIAL_SYNC = 0;
54 * Synchronization control constant for non-initial frame synchronizations.
58 static byte STRICT_SYNC = 1;
60 // max. 1730 bytes per frame: 144 * 384kbit/s / 32000 Hz + 2 Bytes CRC
62 * Maximum size of the frame buffer.
65 private static final int BUFFER_INT_SIZE = 433;
68 * The frame buffer that holds the data for the current frame.
71 private final int[] framebuffer = new int[BUFFER_INT_SIZE];
74 * Number of valid bytes in the frame buffer.
77 private int framesize;
80 * The bytes read from the stream.
83 private byte[] frame_bytes = new byte[BUFFER_INT_SIZE * 4];
86 * Index into <code>framebuffer</code> where the next bits are retrieved.
89 private int wordpointer;
92 * Number (0-31, from MSB to LSB) of next bit for get_bits()
98 * The current specified syncword
101 private int syncword;
104 * Audio header position in stream.
107 private int header_pos = 0;
113 private boolean single_ch_mode;
114 // private int current_frame_number;
115 // private int last_frame_number;
118 private final int bitmask[] = {
120 0x00000001, 0x00000003, 0x00000007, 0x0000000F, 0x0000001F, 0x0000003F, 0x0000007F,
121 0x000000FF, 0x000001FF, 0x000003FF, 0x000007FF, 0x00000FFF, 0x00001FFF, 0x00003FFF,
122 0x00007FFF, 0x0000FFFF, 0x0001FFFF };
125 private final PushbackInputStream source;
128 private final Header header = new Header();
131 private final byte syncbuf[] = new byte[4];
134 private Crc16[] crc = new Crc16[1];
137 private byte[] rawid3v2 = null;
140 private boolean firstframe = true;
142 private BitReserve br;
143 private int main_data_begin;
144 private int frame_start;
147 * Construct a IBitstream that reads data from a given InputStream.
150 * The InputStream to read from.
152 public Bitstream(InputStream in) {
154 throw new NullPointerException("in");
155 in = new BufferedInputStream(in);
158 // source = new PushbackInputStream(in, 1024);
159 source = new PushbackInputStream(in, BUFFER_INT_SIZE * 4);
162 // current_frame_number = -1;
163 // last_frame_number = -1;
165 br = new BitReserve();
170 * Return position of the first audio header.
172 * @return size of ID3v2 tag frames.
174 public int header_pos() {
185 private void loadID3v2(InputStream in) {
188 // Read ID3v2 header (10 bytes).
190 size = readID3v2Header(in);
192 } catch (IOException e) {
195 // Unread ID3v2 header (10 bytes).
197 } catch (IOException e) {
203 rawid3v2 = new byte[size];
204 in.read(rawid3v2, 0, rawid3v2.length);
206 } catch (IOException e) {
211 * Parse ID3v2 tag header to find out size of ID3v2 frames.
215 * @return size of ID3v2 frames + header
216 * @throws IOException
219 private int readID3v2Header(InputStream in) throws IOException {
220 byte[] id3header = new byte[4];
222 in.read(id3header, 0, 3);
224 if ((id3header[0] == 'I') && (id3header[1] == 'D') && (id3header[2] == '3')) {
225 in.read(id3header, 0, 3);
226 int majorVersion = id3header[0];
227 int revision = id3header[1];
228 in.read(id3header, 0, 4);
230 (int) (id3header[0] << 21) + (id3header[1] << 14) + (id3header[2] << 7) + (id3header[3]);
236 * Return raw ID3v2 frames + header.
238 * @return ID3v2 InputStream or null if ID3v2 frames are not available.
240 public InputStream getRawID3v2() {
241 if (rawid3v2 == null)
244 ByteArrayInputStream bain = new ByteArrayInputStream(rawid3v2);
250 * Close the Bitstream.
252 * @throws BitstreamException
254 public void close() throws BitstreamException {
257 } catch (IOException ex) {
258 throw newBitstreamException(STREAM_ERROR, ex);
263 * Reads and parses the next frame from the input source.
265 * @return the Header describing details of the frame read, or null if the end
266 * of the stream has been reached.
268 public Header readFrame() throws BitstreamException {
269 Header result = null;
271 result = readNextFrame();
272 // E.B, Parse VBR (if any) first frame.
273 if (firstframe == true) {
274 result.parseVBR(frame_bytes);
277 } catch (BitstreamException ex) {
278 if ((ex.getErrorCode() == INVALIDFRAME)) {
279 // Try to skip this frame.
280 // System.out.println("INVALIDFRAME");
283 result = readNextFrame();
284 } catch (BitstreamException e) {
285 if ((e.getErrorCode() != STREAM_EOF)) {
286 // wrap original exception so stack trace is maintained.
287 throw newBitstreamException(e.getErrorCode(), e);
290 } else if ((ex.getErrorCode() != STREAM_EOF)) {
291 // wrap original exception so stack trace is maintained.
292 throw newBitstreamException(ex.getErrorCode(), ex);
299 * Read next MP3 frame.
301 * @return MP3 frame header.
302 * @throws BitstreamException
304 private Header readNextFrame() throws BitstreamException {
305 if (framesize == -1) {
312 * Read next MP3 frame.
314 * @throws BitstreamException
316 private void nextFrame() throws BitstreamException {
317 // entire frame is read by the header class.
318 header.read_header(this, crc);
322 * Unreads the bytes read from the frame.
324 * @throws BitstreamException
326 // REVIEW: add new error codes for this.
327 public void unreadFrame() throws BitstreamException {
328 if (wordpointer == -1 && bitindex == -1 && (framesize > 0)) {
330 source.unread(frame_bytes, 0, framesize);
331 } catch (IOException ex) {
332 throw newBitstreamException(STREAM_ERROR);
340 public void closeFrame() {
347 * Determines if the next 4 bytes of the stream represent a frame header.
349 public boolean isSyncCurrentPosition(int syncmode) throws BitstreamException {
350 int read = readBytes(syncbuf, 0, 4);
352 ((syncbuf[0] << 24) & 0xFF000000) | ((syncbuf[1] << 16) & 0x00FF0000)
353 | ((syncbuf[2] << 8) & 0x0000FF00) | ((syncbuf[3] << 0) & 0x000000FF);
356 source.unread(syncbuf, 0, read);
357 } catch (IOException ex) {
360 boolean sync = false;
366 sync = isSyncMark(headerstring, syncmode, syncword);
373 // REVIEW: this class should provide inner classes to
374 // parse the frame contents. Eventually, readBits will
376 public int readBits(int n) {
380 public int peek_bits(int number_of_bits) {
382 int peekbitindex = bitindex;
383 int peekPointer = wordpointer;
386 int sum = peekbitindex + number_of_bits;
388 if (peekPointer < 0) {
393 // all bits contained in *wordpointer
394 returnvalue = (framebuffer[peekPointer] >>> (32 - sum)) & bitmask[number_of_bits];
395 // returnvalue = (wordpointer[0] >> (32 - sum)) &
396 // bitmask[number_of_bits];
397 if ((peekbitindex += number_of_bits) == 32) {
399 peekPointer++; // added by me!
404 // E.B : Check that ?
405 // ((short[])&returnvalue)[0] = ((short[])wordpointer + 1)[0];
406 // wordpointer++; // Added by me!
407 // ((short[])&returnvalue + 1)[0] = ((short[])wordpointer)[0];
408 int Right = (framebuffer[peekPointer] & 0x0000FFFF);
410 int Left = (framebuffer[peekPointer] & 0xFFFF0000);
411 returnvalue = ((Right << 16) & 0xFFFF0000) | ((Left >>> 16) & 0x0000FFFF);
413 returnvalue >>>= 48 - sum; // returnvalue >>= 16 - (number_of_bits - (32
415 returnvalue &= bitmask[number_of_bits];
416 peekbitindex = sum - 32;
421 public int readCheckedBits(int n) {
422 // REVIEW: implement CRC check.
426 protected BitstreamException newBitstreamException(int errorcode) {
427 return new BitstreamException(errorcode, null);
430 protected BitstreamException newBitstreamException(int errorcode, Throwable throwable) {
431 return new BitstreamException(errorcode, throwable);
435 * Get next 32 bits from bitstream. They are stored in the headerstring.
436 * syncmod allows Synchro flag ID The returned value is False at the end of
440 int syncHeader(byte syncmode) throws BitstreamException {
443 // read additional 2 bytes
444 int bytesRead = readBytes(syncbuf, 0, 3);
447 throw newBitstreamException(STREAM_EOF, null);
450 ((syncbuf[0] << 16) & 0x00FF0000) | ((syncbuf[1] << 8) & 0x0000FF00)
451 | ((syncbuf[2] << 0) & 0x000000FF);
456 if (readBytes(syncbuf, 3, 1) != 1)
457 throw newBitstreamException(STREAM_EOF, null);
459 headerstring |= (syncbuf[3] & 0x000000FF);
461 sync = isSyncMark(headerstring, syncmode, syncword);
464 // current_frame_number++;
465 // if (last_frame_number < current_frame_number) last_frame_number =
466 // current_frame_number;
471 public boolean isSyncMark(int headerstring, int syncmode, int word) {
472 boolean sync = false;
474 if (syncmode == INITIAL_SYNC) {
475 // sync = ((headerstring & 0xFFF00000) == 0xFFF00000);
476 sync = ((headerstring & 0xFFE00000) == 0xFFE00000); // SZD: MPEG 2.5
479 ((headerstring & 0xFFF80C00) == word)
480 && (((headerstring & 0x000000C0) == 0x000000C0) == single_ch_mode);
483 // filter out invalid sample rate
485 sync = (((headerstring >>> 10) & 3) != 3);
486 // filter out invalid layer
488 sync = (((headerstring >>> 17) & 3) != 0);
489 // filter out invalid version
491 sync = (((headerstring >>> 19) & 3) != 1);
497 * Reads the data for the next frame. The frame is not parsed until parse
500 int read_frame_data(int bytesize) throws BitstreamException {
502 numread = readFully(frame_bytes, 0, bytesize);
503 framesize = bytesize;
510 * Parses the data previously read with read_frame_data().
512 @LATTICE("GLOBAL<B,B<BNUM,BNUM<K,K<BYTE,BYTE<THIS,B*,K*,THISLOC=THIS,GLOBALLOC=GLOBAL")
513 void parse_frame() throws BitstreamException {
514 // Convert Bytes read to int
516 @LOC("BYTE") byte[] byteread = frame_bytes;
517 @LOC("BYTE") int bytesize = framesize;
519 // Check ID3v1 TAG (True only if last frame).
520 // for (int t=0;t<(byteread.length)-2;t++)
522 // if ((byteread[t]=='T') && (byteread[t+1]=='A') && (byteread[t+2]=='G'))
524 // System.out.println("ID3v1 detected at offset "+t);
525 // throw newBitstreamException(INVALIDFRAME, null);
529 for (@LOC("K") int k = 0; k < bytesize; k = k + 4) {
530 @LOC("BYTE") int convert = 0;
531 @LOC("BNUM") byte b0 = 0;
532 @LOC("BNUM") byte b1 = 0;
533 @LOC("BNUM") byte b2 = 0;
534 @LOC("BNUM") byte b3 = 0;
536 if (k + 1 < bytesize)
537 b1 = byteread[k + 1];
538 if (k + 2 < bytesize)
539 b2 = byteread[k + 2];
540 if (k + 3 < bytesize)
541 b3 = byteread[k + 3];
543 ((b0 << 24) & 0xFF000000) | ((b1 << 16) & 0x00FF0000) | ((b2 << 8) & 0x0000FF00)
551 * Read bits from buffer into the lower bits of an unsigned int. The LSB
552 * contains the latest read bit of the stream. (1 <= number_of_bits <= 16)
554 @LATTICE("OUT<RL,RL<THIS,THIS<IN,OUT*,THISLOC=THIS,RETURNLOC=OUT")
555 public int get_bits(@LOC("IN") int number_of_bits) {
557 @LOC("OUT") int returnvalue = 0;
558 @LOC("THIS,Bitstream.BI") int sum = bitindex + number_of_bits;
561 // There is a problem here, wordpointer could be -1 ?!
567 // all bits contained in *wordpointer
568 returnvalue = (framebuffer[wordpointer] >>> (32 - sum)) & bitmask[number_of_bits];
569 // returnvalue = (wordpointer[0] >> (32 - sum)) & bitmask[number_of_bits];
570 if ((bitindex += number_of_bits) == 32) {
572 wordpointer++; // added by me!
577 // E.B : Check that ?
578 // ((short[])&returnvalue)[0] = ((short[])wordpointer + 1)[0];
579 // wordpointer++; // Added by me!
580 // ((short[])&returnvalue + 1)[0] = ((short[])wordpointer)[0];
581 @LOC("RL") int Right = (framebuffer[wordpointer] & 0x0000FFFF);
583 @LOC("RL") int Left = (framebuffer[wordpointer] & 0xFFFF0000);
584 returnvalue = ((Right << 16) & 0xFFFF0000) | ((Left >>> 16) & 0x0000FFFF);
586 returnvalue >>>= 48 - sum; // returnvalue >>= 16 - (number_of_bits - (32 -
588 returnvalue &= bitmask[number_of_bits];
594 * Set the word we want to sync the header to. In Big-Endian byte order
596 void set_syncword(@LOC("IN") int syncword0) {
597 syncword = syncword0 & 0xFFFFFF3F;
598 single_ch_mode = ((syncword0 & 0x000000C0) == 0x000000C0);
602 * Reads the exact number of bytes from the source input stream into a byte
606 * The byte array to read the specified number of bytes into.
608 * The index in the array where the first byte read should be stored.
610 * the number of bytes to read.
612 * @exception BitstreamException
613 * is thrown if the specified number of bytes could not be read
616 @LATTICE("OUT<VAR,VAR<THIS,THIS<IN,IN*,VAR*,THISLOC=THIS")
618 private int readFully(@LOC("OUT") byte[] b, @LOC("IN") int offs, @LOC("IN") int len)
619 throws BitstreamException {
620 @LOC("VAR") int nRead = 0;
623 @LOC("IN") int bytesread = source.read(b, offs, len);
624 if (bytesread == -1) {
629 // throw newBitstreamException(UNEXPECTED_EOF, new EOFException());
631 nRead = nRead + bytesread;
635 } catch (IOException ex) {
636 throw newBitstreamException(STREAM_ERROR, ex);
642 * Simlar to readFully, but doesn't throw exception when EOF is reached.
644 @LATTICE("OUT<VAR,VAR<THIS,THIS<IN,IN*,VAR*,THISLOC=THIS")
646 private int readBytes(@LOC("OUT") byte[] b, @LOC("IN") int offs, @LOC("IN") int len)
647 throws BitstreamException {
648 @LOC("VAR") int totalBytesRead = 0;
651 @LOC("IN") int bytesread = source.read(b, offs, len);
652 if (bytesread == -1) {
655 totalBytesRead += bytesread;
659 } catch (IOException ex) {
660 throw newBitstreamException(STREAM_ERROR, ex);
662 return totalBytesRead;
665 public SideInfoBuffer getSideInfoBuffer(int channelType) {
670 SideInfoBuffer sib = new SideInfoBuffer();
672 // first, store main_data_begin from the side inforamtion
673 main_data_begin = peek_bits(9);
674 System.out.println("main_data_begin=" + main_data_begin);
677 if (channelType == 1) { // mono
678 max = wordpointer + 4;
680 max = wordpointer + 8;
684 for (; wordpointer < max; wordpointer++) {
685 sib.setBuffer(wordpointer, framebuffer[wordpointer]);
687 } catch (ArrayIndexOutOfBoundsException e) {
688 System.out.print("wordpointer=" + wordpointer);
689 System.out.println("framebuffer length=" + framebuffer.length);
695 public BitReserve getBitReserve(int nSlots) {
698 int bytes_to_discard;
701 for (i = 0; i < nSlots; i++)
702 br.hputbuf(get_bits(8));
704 int main_data_end = br.hsstell() >>> 3; // of previous frame
706 if ((flush_main = (br.hsstell() & 7)) != 0) {
707 br.hgetbits(8 - flush_main);
711 bytes_to_discard = frame_start - main_data_end - main_data_begin;
713 frame_start += nSlots;
715 if (bytes_to_discard < 0) {
716 System.out.println("HERE?");
720 if (main_data_end > 4096) {
722 br.rewindNbytes(4096);
725 for (; bytes_to_discard > 0; bytes_to_discard--)