remove unnecessary annotations to calculate evalution numbers.
[IRC.git] / Robust / src / Benchmarks / SSJava / MP3Decoder / Bitstream.java
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
36 /**
37  * The <code>Bistream</code> class is responsible for parsing an MPEG audio
38  * bitstream.
39  * 
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.
42  */
43 public final class Bitstream implements BitstreamErrors {
44   /**
45    * Synchronization control constant for the initial synchronization to the
46    * start of a frame.
47    */
48   
49   static byte INITIAL_SYNC = 0;
50
51   /**
52    * Synchronization control constant for non-initial frame synchronizations.
53    */
54
55   
56   static byte STRICT_SYNC = 1;
57
58   // max. 1730 bytes per frame: 144 * 384kbit/s / 32000 Hz + 2 Bytes CRC
59   /**
60    * Maximum size of the frame buffer.
61    */
62   
63   private static final int BUFFER_INT_SIZE = 433;
64
65   /**
66    * The frame buffer that holds the data for the current frame.
67    */
68   
69   private final int[] framebuffer = new int[BUFFER_INT_SIZE];
70
71   /**
72    * Number of valid bytes in the frame buffer.
73    */
74   
75   private int framesize;
76
77   /**
78    * The bytes read from the stream.
79    */
80   
81   private byte[] frame_bytes = new byte[BUFFER_INT_SIZE * 4];
82
83   /**
84    * Index into <code>framebuffer</code> where the next bits are retrieved.
85    */
86   
87   private int wordpointer;
88
89   /**
90    * Number (0-31, from MSB to LSB) of next bit for get_bits()
91    */
92   
93   private int bitindex;
94
95   /**
96    * The current specified syncword
97    */
98   
99   private int syncword;
100
101   /**
102    * Audio header position in stream.
103    */
104   
105   private int header_pos = 0;
106
107   /**
108       *
109       */
110   
111   private boolean single_ch_mode;
112   // private int current_frame_number;
113   // private int last_frame_number;
114
115   
116   private final int bitmask[] = {
117       0, // dummy
118       0x00000001, 0x00000003, 0x00000007, 0x0000000F, 0x0000001F, 0x0000003F, 0x0000007F,
119       0x000000FF, 0x000001FF, 0x000003FF, 0x000007FF, 0x00000FFF, 0x00001FFF, 0x00003FFF,
120       0x00007FFF, 0x0000FFFF, 0x0001FFFF };
121
122   
123   private final PushbackInputStream source;
124
125   
126   private final Header header = new Header();
127
128   
129   private final byte syncbuf[] = new byte[4];
130
131   
132   private Crc16[] crc = new Crc16[1];
133
134   
135   private byte[] rawid3v2 = null;
136
137   
138   private boolean firstframe = true;
139
140   private BitReserve br;
141   private int main_data_begin;
142   private int frame_start;
143
144   /**
145    * Construct a IBitstream that reads data from a given InputStream.
146    * 
147    * @param in
148    *          The InputStream to read from.
149    */
150   public Bitstream(InputStream in) {
151     if (in == null)
152       throw new NullPointerException("in");
153     in = new BufferedInputStream(in);
154     loadID3v2(in);
155     firstframe = true;
156     // source = new PushbackInputStream(in, 1024);
157     source = new PushbackInputStream(in, BUFFER_INT_SIZE * 4);
158
159     closeFrame();
160     // current_frame_number = -1;
161     // last_frame_number = -1;
162
163     br = new BitReserve();
164
165   }
166
167   /**
168    * Return position of the first audio header.
169    * 
170    * @return size of ID3v2 tag frames.
171    */
172   public int header_pos() {
173     return header_pos;
174   }
175
176   /**
177    * Load ID3v2 frames.
178    * 
179    * @param in
180    *          MP3 InputStream.
181    * @author JavaZOOM
182    */
183   private void loadID3v2(InputStream in) {
184     int size = -1;
185     try {
186       // Read ID3v2 header (10 bytes).
187       in.mark(10);
188       size = readID3v2Header(in);
189       header_pos = size;
190     } catch (IOException e) {
191     } finally {
192       try {
193         // Unread ID3v2 header (10 bytes).
194         in.reset();
195       } catch (IOException e) {
196       }
197     }
198     // Load ID3v2 tags.
199     try {
200       if (size > 0) {
201         rawid3v2 = new byte[size];
202         in.read(rawid3v2, 0, rawid3v2.length);
203       }
204     } catch (IOException e) {
205     }
206   }
207
208   /**
209    * Parse ID3v2 tag header to find out size of ID3v2 frames.
210    * 
211    * @param in
212    *          MP3 InputStream
213    * @return size of ID3v2 frames + header
214    * @throws IOException
215    * @author JavaZOOM
216    */
217   private int readID3v2Header(InputStream in) throws IOException {
218     byte[] id3header = new byte[4];
219     int size = -10;
220     in.read(id3header, 0, 3);
221     // Look for ID3v2
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);
227       size =
228           (int) (id3header[0] << 21) + (id3header[1] << 14) + (id3header[2] << 7) + (id3header[3]);
229     }
230     return (size + 10);
231   }
232
233   /**
234    * Return raw ID3v2 frames + header.
235    * 
236    * @return ID3v2 InputStream or null if ID3v2 frames are not available.
237    */
238   public InputStream getRawID3v2() {
239     if (rawid3v2 == null)
240       return null;
241     else {
242       ByteArrayInputStream bain = new ByteArrayInputStream(rawid3v2);
243       return bain;
244     }
245   }
246
247   /**
248    * Close the Bitstream.
249    * 
250    * @throws BitstreamException
251    */
252   public void close() throws BitstreamException {
253     try {
254       source.close();
255     } catch (IOException ex) {
256       throw newBitstreamException(STREAM_ERROR, ex);
257     }
258   }
259
260   /**
261    * Reads and parses the next frame from the input source.
262    * 
263    * @return the Header describing details of the frame read, or null if the end
264    *         of the stream has been reached.
265    */
266   public Header readFrame() throws BitstreamException {
267
268     Header result = null;
269     try {
270       result = readNextFrame();
271       if (result == null) {
272         return null;
273       }
274       // E.B, Parse VBR (if any) first frame.
275       if (firstframe == true) {
276         result.parseVBR(frame_bytes);
277         firstframe = false;
278       }
279
280       int channels = (header.mode() == Header.SINGLE_CHANNEL) ? 1 : 2;
281
282       result.setSideInfoBuf(getSideInfoBuffer(channels));
283       result.setBitReserve(getBitReserve(result.slots()));
284
285       closeFrame();
286
287     } catch (BitstreamException ex) {
288       if ((ex.getErrorCode() == INVALIDFRAME)) {
289         // Try to skip this frame.
290         // System.out.println("INVALIDFRAME");
291         try {
292           closeFrame();
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);
298           }
299         }
300       } else if ((ex.getErrorCode() != STREAM_EOF)) {
301         // wrap original exception so stack trace is maintained.
302         throw newBitstreamException(ex.getErrorCode(), ex);
303       }
304     }
305
306     return result;
307   }
308
309   /**
310    * Read next MP3 frame.
311    * 
312    * @return MP3 frame header.
313    * @throws BitstreamException
314    */
315   private Header readNextFrame() throws BitstreamException {
316     if (framesize == -1) {
317       if (nextFrame() == -1) {
318         return null;
319       }
320     }
321     return header;
322   }
323
324   /**
325    * Read next MP3 frame.
326    * 
327    * @throws BitstreamException
328    */
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);
333   }
334
335   /**
336    * Unreads the bytes read from the frame.
337    * 
338    * @throws BitstreamException
339    */
340   // REVIEW: add new error codes for this.
341   public void unreadFrame() throws BitstreamException {
342     if (wordpointer == -1 && bitindex == -1 && (framesize > 0)) {
343       try {
344         source.unread(frame_bytes, 0, framesize);
345       } catch (IOException ex) {
346         throw newBitstreamException(STREAM_ERROR);
347       }
348     }
349   }
350
351   /**
352    * Close MP3 frame.
353    */
354   public void closeFrame() {
355     framesize = -1;
356     wordpointer = -1;
357     bitindex = -1;
358   }
359
360   /**
361    * Determines if the next 4 bytes of the stream represent a frame header.
362    */
363   public boolean isSyncCurrentPosition(int syncmode) throws BitstreamException {
364     int read = readBytes(syncbuf, 0, 4);
365     int headerstring =
366         ((syncbuf[0] << 24) & 0xFF000000) | ((syncbuf[1] << 16) & 0x00FF0000)
367             | ((syncbuf[2] << 8) & 0x0000FF00) | ((syncbuf[3] << 0) & 0x000000FF);
368
369     try {
370       source.unread(syncbuf, 0, read);
371     } catch (IOException ex) {
372     }
373
374     boolean sync = false;
375     switch (read) {
376     case 0:
377       sync = true;
378       break;
379     case 4:
380       sync = isSyncMark(headerstring, syncmode, syncword);
381       break;
382     }
383
384     return sync;
385   }
386
387   // REVIEW: this class should provide inner classes to
388   // parse the frame contents. Eventually, readBits will
389   // be removed.
390   public int readBits(int n) {
391     return get_bits(n);
392   }
393
394   public int peek_bits(int number_of_bits) {
395
396     int peekbitindex = bitindex;
397     int peekPointer = wordpointer;
398
399     int returnvalue = 0;
400     int sum = peekbitindex + number_of_bits;
401
402     if (peekPointer < 0) {
403       peekPointer = 0;
404     }
405
406     if (sum <= 32) {
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) {
412         peekbitindex = 0;
413         peekPointer++; // added by me!
414       }
415       return returnvalue;
416     }
417
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);
423     peekPointer++;
424     int Left = (framebuffer[peekPointer] & 0xFFFF0000);
425     returnvalue = ((Right << 16) & 0xFFFF0000) | ((Left >>> 16) & 0x0000FFFF);
426
427     returnvalue >>>= 48 - sum; // returnvalue >>= 16 - (number_of_bits - (32
428                                // - bitindex))
429     returnvalue &= bitmask[number_of_bits];
430     peekbitindex = sum - 32;
431     return returnvalue;
432
433   }
434
435   public int readCheckedBits(int n) {
436     // REVIEW: implement CRC check.
437     return get_bits(n);
438   }
439
440   protected BitstreamException newBitstreamException(int errorcode) {
441     return new BitstreamException(errorcode, null);
442   }
443
444   protected BitstreamException newBitstreamException(int errorcode, Throwable throwable) {
445     return new BitstreamException(errorcode, throwable);
446   }
447
448   /**
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
451    * stream.
452    */
453
454   int syncHeader(byte syncmode) throws BitstreamException {
455     boolean sync;
456     int headerstring;
457     // read additional 2 bytes
458     int bytesRead = readBytes(syncbuf, 0, 3);
459
460     if (bytesRead != 3)
461       throw newBitstreamException(STREAM_EOF, null);
462
463     headerstring =
464         ((syncbuf[0] << 16) & 0x00FF0000) | ((syncbuf[1] << 8) & 0x0000FF00)
465             | ((syncbuf[2] << 0) & 0x000000FF);
466
467     do {
468       headerstring <<= 8;
469
470       if (readBytes(syncbuf, 3, 1) != 1) {
471         // System.out.println("THROW NEW BITSTREAM EXCEPTION");
472         return -1;
473         throw newBitstreamException(STREAM_EOF, null);
474       }
475
476       headerstring |= (syncbuf[3] & 0x000000FF);
477
478       sync = isSyncMark(headerstring, syncmode, syncword);
479     } while (!sync);
480
481     // current_frame_number++;
482     // if (last_frame_number < current_frame_number) last_frame_number =
483     // current_frame_number;
484
485     return headerstring;
486   }
487
488   public boolean isSyncMark(int headerstring, int syncmode, int word) {
489     boolean sync = false;
490
491     if (syncmode == INITIAL_SYNC) {
492       // sync = ((headerstring & 0xFFF00000) == 0xFFF00000);
493       sync = ((headerstring & 0xFFE00000) == 0xFFE00000); // SZD: MPEG 2.5
494     } else {
495       sync =
496           ((headerstring & 0xFFF80C00) == word)
497               && (((headerstring & 0x000000C0) == 0x000000C0) == single_ch_mode);
498     }
499
500     // filter out invalid sample rate
501     if (sync)
502       sync = (((headerstring >>> 10) & 3) != 3);
503     // filter out invalid layer
504     if (sync)
505       sync = (((headerstring >>> 17) & 3) != 0);
506     // filter out invalid version
507     if (sync)
508       sync = (((headerstring >>> 19) & 3) != 1);
509
510     return sync;
511   }
512
513   /**
514    * Reads the data for the next frame. The frame is not parsed until parse
515    * frame is called.
516    */
517   int read_frame_data(int bytesize) throws BitstreamException {
518     int numread = 0;
519     numread = readFully(frame_bytes, 0, bytesize);
520     framesize = bytesize;
521     wordpointer = -1;
522     bitindex = -1;
523     return numread;
524   }
525
526   /**
527    * Parses the data previously read with read_frame_data().
528    */
529   
530   void parse_frame() throws BitstreamException {
531     // Convert Bytes read to int
532      int b = 0;
533      byte[] byteread = frame_bytes;
534      int bytesize = framesize;
535
536     // Check ID3v1 TAG (True only if last frame).
537     // for (int t=0;t<(byteread.length)-2;t++)
538     // {
539     // if ((byteread[t]=='T') && (byteread[t+1]=='A') && (byteread[t+2]=='G'))
540     // {
541     // System.out.println("ID3v1 detected at offset "+t);
542     // throw newBitstreamException(INVALIDFRAME, null);
543     // }
544     // }
545
546     for ( int k = 0; k < bytesize; k = k + 4) {
547        int convert = 0;
548        byte b0 = 0;
549        byte b1 = 0;
550        byte b2 = 0;
551        byte b3 = 0;
552       b0 = byteread[k];
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];
559       framebuffer[b++] =
560           ((b0 << 24) & 0xFF000000) | ((b1 << 16) & 0x00FF0000) | ((b2 << 8) & 0x0000FF00)
561               | (b3 & 0x000000FF);
562     }
563     wordpointer = 0;
564     bitindex = 0;
565   }
566
567   /**
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)
570    */
571   
572   public int get_bits( int number_of_bits) {
573
574      int returnvalue = 0;
575      int sum = bitindex + number_of_bits;
576
577     // E.B
578     // There is a problem here, wordpointer could be -1 ?!
579     if (wordpointer < 0)
580       wordpointer = 0;
581     // E.B : End.
582
583     if (sum <= 32) {
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) {
588         bitindex = 0;
589         wordpointer++; // added by me!
590       }
591       return returnvalue;
592     }
593
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);
599     wordpointer++;
600      int Left = (framebuffer[wordpointer] & 0xFFFF0000);
601     returnvalue = ((Right << 16) & 0xFFFF0000) | ((Left >>> 16) & 0x0000FFFF);
602
603     returnvalue >>>= 48 - sum; // returnvalue >>= 16 - (number_of_bits - (32 -
604                                // bitindex))
605     returnvalue &= bitmask[number_of_bits];
606     bitindex = sum - 32;
607     return returnvalue;
608   }
609
610   /**
611    * Set the word we want to sync the header to. In Big-Endian byte order
612    */
613   void set_syncword( int syncword0) {
614     syncword = syncword0 & 0xFFFFFF3F;
615     single_ch_mode = ((syncword0 & 0x000000C0) == 0x000000C0);
616   }
617
618   /**
619    * Reads the exact number of bytes from the source input stream into a byte
620    * array.
621    * 
622    * @param b
623    *          The byte array to read the specified number of bytes into.
624    * @param offs
625    *          The index in the array where the first byte read should be stored.
626    * @param len
627    *          the number of bytes to read.
628    * 
629    * @exception BitstreamException
630    *              is thrown if the specified number of bytes could not be read
631    *              from the stream.
632    */
633   
634   
635   private int readFully( byte[] b,  int offs,  int len)
636       throws BitstreamException {
637      int nRead = 0;
638     try {
639       while (len > 0) {
640          int bytesread = source.read(b, offs, len);
641         if (bytesread == -1) {
642           while (len-- > 0) {
643             b[offs++] = 0;
644           }
645           break;
646           // throw newBitstreamException(UNEXPECTED_EOF, new EOFException());
647         }
648         nRead = nRead + bytesread;
649         offs += bytesread;
650         len -= bytesread;
651       }
652     } catch (IOException ex) {
653       throw newBitstreamException(STREAM_ERROR, ex);
654     }
655     return nRead;
656   }
657
658   /**
659    * Simlar to readFully, but doesn't throw exception when EOF is reached.
660    */
661   
662   
663   private int readBytes( byte[] b,  int offs,  int len)
664       throws BitstreamException {
665      int totalBytesRead = 0;
666     try {
667       while (len > 0) {
668          int bytesread = source.read(b, offs, len);
669         if (bytesread == -1) {
670           break;
671         }
672         totalBytesRead += bytesread;
673         offs += bytesread;
674         len -= bytesread;
675       }
676     } catch (IOException ex) {
677       throw newBitstreamException(STREAM_ERROR, ex);
678     }
679     return totalBytesRead;
680   }
681
682   public SideInfoBuffer getSideInfoBuffer(int channelType) {
683
684     if (wordpointer < 0)
685       wordpointer = 0;
686
687     SideInfoBuffer sib = new SideInfoBuffer();
688
689     // first, store main_data_begin from the side inforamtion
690     main_data_begin = peek_bits(9);
691
692     int max;
693     if (channelType == 1) { // mono
694       max = wordpointer + 4;
695     } else {
696       max = wordpointer + 8;
697     }
698
699     try {
700       for (; wordpointer < max; wordpointer++) {
701         sib.setBuffer(wordpointer, framebuffer[wordpointer]);
702       }
703     } catch (ArrayIndexOutOfBoundsException e) {
704       System.out.print("wordpointer=" + wordpointer);
705       System.out.println("framebuffer length=" + framebuffer.length);
706     }
707
708     return sib;
709   }
710
711   public BitReserve getBitReserve(int nSlots) {
712
713     int flush_main;
714     int bytes_to_discard;
715     int i;
716
717     for (i = 0; i < nSlots; i++)
718       br.hputbuf(get_bits(8));
719
720     int main_data_end = br.hsstell() >>> 3; // of previous frame
721
722     if ((flush_main = (br.hsstell() & 7)) != 0) {
723       br.hgetbits(8 - flush_main);
724       main_data_end++;
725     }
726
727     bytes_to_discard = frame_start - main_data_end - main_data_begin;
728
729     frame_start += nSlots;
730
731     if (bytes_to_discard < 0) {
732       return null;
733     }
734
735     if (main_data_end > 4096) {
736       frame_start -= 4096;
737       br.rewindNbytes(4096);
738     }
739
740     for (; bytes_to_discard > 0; bytes_to_discard--)
741       br.hgetbits(8);
742
743     // resynch index by trusted code
744     br.buf_byte_idx = br.totbit % br.BUFSIZE;
745     return br;
746   }
747 }