Home | History | Annotate | Download | only in objectdescriptors
      1 package com.googlecode.mp4parser.boxes.mp4.objectdescriptors;
      2 
      3 import java.nio.ByteBuffer;
      4 
      5 public class BitReaderBuffer {
      6 
      7     private ByteBuffer buffer;
      8     int initialPos;
      9     int position;
     10 
     11     public BitReaderBuffer(ByteBuffer buffer) {
     12         this.buffer = buffer;
     13         initialPos = buffer.position();
     14     }
     15 
     16     public int readBits(int i) {
     17         byte b = buffer.get(initialPos + position / 8);
     18         int v = b < 0 ? b + 256 : b;
     19         int left = 8 - position % 8;
     20         int rc;
     21         if (i <= left) {
     22             rc = (v << (position % 8) & 0xFF) >> ((position % 8) + (left - i));
     23             position += i;
     24         } else {
     25             int now = left;
     26             int then = i - left;
     27             rc = readBits(now);
     28             rc = rc << then;
     29             rc += readBits(then);
     30         }
     31         buffer.position(initialPos + (int) Math.ceil((double) position / 8));
     32         return rc;
     33     }
     34 
     35     public int getPosition() {
     36         return position;
     37     }
     38 
     39     public int byteSync() {
     40         int left = 8 - position % 8;
     41         if (left == 8) {
     42             left = 0;
     43         }
     44         readBits(left);
     45         return left;
     46     }
     47 
     48     public int remainingBits() {
     49         return buffer.limit() * 8 - position;
     50     }
     51 }
     52