Java Code Examples for java.nio.ByteBuffer.slice()

The following are Jave code examples for showing how to use slice() of the java.nio.ByteBuffer class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: rtmp-rtsp-stream-client-java   File: SrsFlvMuxer.java   View Source Code Vote up 6 votes
public SrsFlvFrameBytes demuxAnnexb(ByteBuffer bb, int size, boolean isOnlyChkHeader) {
  SrsFlvFrameBytes tbb = new SrsFlvFrameBytes();
  if (bb.position() < size - 4) {
    // each frame must prefixed by annexb format.
    // about annexb, @see H.264-AVC-ISO_IEC_14496-10.pdf, page 211.
    SrsAnnexbSearch tbbsc =
        isOnlyChkHeader ? searchStartcode(bb, size) : searchAnnexb(bb, size);
    // tbbsc.nb_start_code always 4 , after 00 00 00 01
    if (!tbbsc.match || tbbsc.nb_start_code < 3) {
      Log.e(TAG, "annexb not match.");
    } else {
      // the start codes.
      for (int i = 0; i < tbbsc.nb_start_code; i++) {
        bb.get();
      }

      // find out the frame size.
      tbb.data = bb.slice();
      tbb.size = size - bb.position();
    }
  }
  return tbb;
}
 
Example 2
Project: AppRTC-Android   File: JavaI420Buffer.java   View Source Code Vote up 6 votes
/** Allocates an empty I420Buffer suitable for an image of the given dimensions. */
public static JavaI420Buffer allocate(int width, int height) {
  int chromaHeight = (height + 1) / 2;
  int strideUV = (width + 1) / 2;
  int yPos = 0;
  int uPos = yPos + width * height;
  int vPos = uPos + strideUV * chromaHeight;

  ByteBuffer buffer = ByteBuffer.allocateDirect(width * height + 2 * strideUV * chromaHeight);

  buffer.position(yPos);
  buffer.limit(uPos);
  ByteBuffer dataY = buffer.slice();

  buffer.position(uPos);
  buffer.limit(vPos);
  ByteBuffer dataU = buffer.slice();

  buffer.position(vPos);
  buffer.limit(vPos + strideUV * chromaHeight);
  ByteBuffer dataV = buffer.slice();

  return new JavaI420Buffer(
      width, height, dataY, width, dataU, strideUV, dataV, strideUV, null /* releaseCallback */);
}
 
Example 3
Project: atlas   File: Dex.java   View Source Code Vote up 6 votes
/**
 * Creates a new dex from the contents of {@code bytes}. This API supports
 * both {@code .dex} and {@code .odex} input. Calling this constructor
 * transfers ownership of {@code bytes} to the returned Dex: it is an error
 * to access the buffer after calling this method.
 */
public static Dex create(ByteBuffer data) throws IOException {
    data.order(ByteOrder.LITTLE_ENDIAN);

    // if it's an .odex file, set position and limit to the .dex section
    if (data.get(0) == 'd' && data.get(1) == 'e' && data.get(2) == 'y' && data.get(3) == '\n') {
        data.position(8);
        int offset = data.getInt();
        int length = data.getInt();
        data.position(offset);
        data.limit(offset + length);
        data = data.slice();
    }

    return new Dex(data);
}
 
Example 4
Project: openaudible   File: Mp4MeanBox.java   View Source Code Vote up 6 votes
/**
 * @param header     parentHeader info
 * @param dataBuffer data of box (doesnt include parentHeader data)
 */
public Mp4MeanBox(Mp4BoxHeader header, ByteBuffer dataBuffer) {
    this.header = header;

    //Double check
    if (!header.getId().equals(IDENTIFIER)) {
        throw new RuntimeException("Unable to process data box because identifier is:" + header.getId());
    }

    //Make slice so operations here don't effect position of main buffer
    this.dataBuffer = dataBuffer.slice();

    //issuer
    this.issuer = Utils.getString(this.dataBuffer, PRE_DATA_LENGTH, header.getDataLength() - PRE_DATA_LENGTH, header.getEncoding());

}
 
Example 5
Project: MetadataEditor   File: Mp4MeanBox.java   View Source Code Vote up 6 votes
/**
 * @param header     parentHeader info
 * @param dataBuffer data of box (doesnt include parentHeader data)
 */
public Mp4MeanBox(Mp4BoxHeader header, ByteBuffer dataBuffer)
{
    this.header = header;

    //Double check
    if (!header.getId().equals(IDENTIFIER))
    {
        throw new RuntimeException("Unable to process data box because identifier is:" + header.getId());
    }

    //Make slice so operations here don't effect position of main buffer
    this.dataBuffer = dataBuffer.slice();

    //issuer
    this.issuer = Utils.getString(this.dataBuffer, PRE_DATA_LENGTH, header.getDataLength() - PRE_DATA_LENGTH, header.getEncoding());

}
 
Example 6
Project: ditb   File: CopyKeyDataBlockEncoder.java   View Source Code Vote up 6 votes
@Override
public ByteBuffer getFirstKeyInBlock(ByteBuffer block) {
  int keyLength = block.getInt(Bytes.SIZEOF_INT);
  ByteBuffer dup = block.duplicate();
  int pos = 3 * Bytes.SIZEOF_INT;
  dup.position(pos);
  dup.limit(pos + keyLength);
  return dup.slice();
}
 
Example 7
Project: monarch   File: HeapDataOutputStream.java   View Source Code Vote up 6 votes
private void moveBufferToChunks() {
  final ByteBuffer oldBuffer = this.buffer;
  if (this.chunks == null) {
    this.chunks = new LinkedList<ByteBuffer>();
  }
  if (oldBuffer.position() == 0) {
    // if position is zero then nothing has been written (yet) to buffer so no need to move it to
    // chunks
    return;
  }
  oldBuffer.flip();
  this.size += oldBuffer.remaining();
  ByteBuffer bufToAdd = oldBuffer.slice();
  this.chunks.add(bufToAdd);
  int newPos = oldBuffer.limit();
  if ((oldBuffer.capacity() - newPos) <= 0) {
    this.buffer = ByteBuffer.allocate(MIN_CHUNK_SIZE);
  } else {
    oldBuffer.limit(oldBuffer.capacity());
    oldBuffer.position(newPos);
    this.buffer = oldBuffer.slice();
  }
}
 
Example 8
Project: openaudible   File: ID3v22Tag.java   View Source Code Vote up 6 votes
/**
 * {@inheritDoc}
 */
@Override
public void read(ByteBuffer byteBuffer) throws TagException {
    int size;
    if (!seek(byteBuffer)) {
        throw new TagNotFoundException("ID3v2.20 tag not found");
    }
    logger.config(getLoggingFilename() + ":" + "Reading tag from file");

    //Read the flags
    readHeaderFlags(byteBuffer);

    // Read the size
    size = ID3SyncSafeInteger.bufferToValue(byteBuffer);

    //Slice Buffer, so position markers tally with size (i.e do not include tagheader)
    ByteBuffer bufferWithoutHeader = byteBuffer.slice();

    //We need to synchronize the buffer
    if (unsynchronization) {
        bufferWithoutHeader = ID3Unsynchronization.synchronize(bufferWithoutHeader);
    }
    readFrames(bufferWithoutHeader, size);
    logger.config(getLoggingFilename() + ":" + "Loaded Frames,there are:" + frameMap.keySet().size());
}
 
Example 9
Project: rocketmq-rocketmq-all-4.1.0-incubating   File: MappedFile.java   View Source Code Vote up 6 votes
public SelectMappedBufferResult selectMappedBuffer(int pos, int size) {
    int readPosition = getReadPosition();
    if ((pos + size) <= readPosition) {

        if (this.hold()) {
            ByteBuffer byteBuffer = this.mappedByteBuffer.slice();
            byteBuffer.position(pos);
            ByteBuffer byteBufferNew = byteBuffer.slice();
            byteBufferNew.limit(size);
            return new SelectMappedBufferResult(this.fileFromOffset + pos, byteBufferNew, size, this);
        } else {
            log.warn("matched, but hold failed, request pos: " + pos + ", fileFromOffset: "
                + this.fileFromOffset);
        }
    } else {
        log.warn("selectMappedBuffer request pos invalid, request pos: " + pos + ", size: " + size
            + ", fileFromOffset: " + this.fileFromOffset);
    }

    return null;
}
 
Example 10
Project: openaudible   File: VbriFrame.java   View Source Code Vote up 6 votes
/**
 * IS this a VBRI frame
 *
 * @param bb
 * @param mpegFrameHeader
 * @return raw header if this is a VBRI frame
 */
public static ByteBuffer isVbriFrame(ByteBuffer bb, MPEGFrameHeader mpegFrameHeader) {

    //We store this so can return here after scanning through buffer
    int startPosition = bb.position();
    MP3File.logger.finest("Checking VBRI Frame at" + startPosition);

    bb.position(startPosition + VBRI_OFFSET);

    //Create header from here
    ByteBuffer header = bb.slice();

    // Return Buffer to start Point
    bb.position(startPosition);

    //Check Identifier
    byte[] identifier = new byte[VBRI_IDENTIFIER_BUFFER_SIZE];
    header.get(identifier);
    if ((!Arrays.equals(identifier, VBRI_VBR_ID))) {
        return null;
    }
    MP3File.logger.finest("Found VBRI Frame");
    return header;
}
 
Example 11
Project: Backmemed   File: Shaders.java   View Source Code Vote up 5 votes
private static ByteBuffer nextByteBuffer(int size)
{
    ByteBuffer bytebuffer = bigBuffer;
    int i = bytebuffer.limit();
    bytebuffer.position(i).limit(i + size);
    return bytebuffer.slice();
}
 
Example 12
Project: MetadataEditor   File: ID3v23Tag.java   View Source Code Vote up 5 votes
/**
 * {@inheritDoc}
 */
@Override
public void read(ByteBuffer buffer) throws TagException
{
    int size;
    if (!seek(buffer))
    {
        throw new TagNotFoundException(getIdentifier() + " tag not found");
    }
    logger.config(getLoggingFilename() + ":" + "Reading ID3v23 tag");

    readHeaderFlags(buffer);

    // Read the size, this is size of tag not including the tag header
    size = ID3SyncSafeInteger.bufferToValue(buffer);
    logger.config(ErrorMessage.ID_TAG_SIZE.getMsg(getLoggingFilename(),size));

    //Extended Header
    if (extended)
    {
        readExtendedHeader(buffer, size);
    }

    //Slice Buffer, so position markers tally with size (i.e do not include tagHeader)
    ByteBuffer bufferWithoutHeader = buffer.slice();
    //We need to synchronize the buffer
    if (isUnsynchronization())
    {
        bufferWithoutHeader = ID3Unsynchronization.synchronize(bufferWithoutHeader);
    }

    readFrames(bufferWithoutHeader, size);
    logger.config(getLoggingFilename() + ":Loaded Frames,there are:" + frameMap.keySet().size());

}
 
Example 13
Project: walle   File: ApkUtil.java   View Source Code Vote up 5 votes
/**
 * Returns new byte buffer whose content is a shared subsequence of this buffer's content
 * between the specified start (inclusive) and end (exclusive) positions. As opposed to
 * {@link ByteBuffer#slice()}, the returned buffer's byte order is the same as the source
 * buffer's byte order.
 */
private static ByteBuffer sliceFromTo(final ByteBuffer source, final int start, final int end) {
    if (start < 0) {
        throw new IllegalArgumentException("start: " + start);
    }
    if (end < start) {
        throw new IllegalArgumentException("end < start: " + end + " < " + start);
    }
    final int capacity = source.capacity();
    if (end > source.capacity()) {
        throw new IllegalArgumentException("end > capacity: " + end + " > " + capacity);
    }
    final int originalLimit = source.limit();
    final int originalPosition = source.position();
    try {
        source.position(0);
        source.limit(end);
        source.position(start);
        final ByteBuffer result = source.slice();
        result.order(source.order());
        return result;
    } finally {
        source.position(0);
        source.limit(originalLimit);
        source.position(originalPosition);
    }
}
 
Example 14
Project: live_master   File: SampleGroupDescriptionBox.java   View Source Code Vote up 5 votes
@Override
protected void _parseDetails(ByteBuffer content) {
    parseVersionAndFlags(content);
    if (this.getVersion() != 1) {
        throw new RuntimeException("SampleGroupDescriptionBox are only supported in version 1");
    }
    groupingType = IsoTypeReader.read4cc(content);
    if (this.getVersion() == 1) {
        defaultLength = l2i(IsoTypeReader.readUInt32(content));
    }
    long entryCount = IsoTypeReader.readUInt32(content);
    while (entryCount-- > 0) {
        int length = defaultLength;
        if (this.getVersion() == 1) {
            if (defaultLength == 0) {
                descriptionLength = l2i(IsoTypeReader.readUInt32(content));
                length = descriptionLength;
            }
        } else {
            throw new RuntimeException("This should be implemented");
        }
        int finalPos = content.position() + length;
        ByteBuffer parseMe = content.slice();
        parseMe.limit(length);
        groupEntries.add(parseGroupEntry(parseMe, groupingType));
        content.position(finalPos);
    }

}
 
Example 15
Project: openjdk-jdk10   File: NativeArrayBuffer.java   View Source Code Vote up 5 votes
private static ByteBuffer cloneBuffer(final ByteBuffer original, final int begin, final int end) {
    final ByteBuffer clone = ByteBuffer.allocateDirect(original.capacity());
    original.rewind();//copy from the beginning
    clone.put(original);
    original.rewind();
    clone.flip();
    clone.position(begin);
    clone.limit(end);
    return clone.slice();
}
 
Example 16
Project: openaudible   File: XingFrame.java   View Source Code Vote up 5 votes
/**
 * IS this a Xing frame
 *
 * @param bb
 * @param mpegFrameHeader
 * @return true if this is a Xing frame
 */
public static ByteBuffer isXingFrame(ByteBuffer bb, MPEGFrameHeader mpegFrameHeader) {
    //We store this so can return here after scanning through buffer
    int startPosition = bb.position();

    //Get to Start of where Xing Frame Should be ( we dont know if it is one at this point)
    if (mpegFrameHeader.getVersion() == MPEGFrameHeader.VERSION_1) {
        if (mpegFrameHeader.getChannelMode() == MPEGFrameHeader.MODE_MONO) {
            bb.position(startPosition + MPEG_VERSION_1_MODE_MONO_OFFSET);
        } else {
            bb.position(startPosition + MPEG_VERSION_1_MODE_STEREO_OFFSET);
        }
    }
    //MPEGVersion 2 and 2.5
    else {
        if (mpegFrameHeader.getChannelMode() == MPEGFrameHeader.MODE_MONO) {
            bb.position(startPosition + MPEG_VERSION_2_MODE_MONO_OFFSET);
        } else {
            bb.position(startPosition + MPEG_VERSION_2_MODE_STEREO_OFFSET);
        }
    }

    //Create header from here
    ByteBuffer header = bb.slice();

    // Return Buffer to start Point
    bb.position(startPosition);

    //Check Identifier
    byte[] identifier = new byte[XING_IDENTIFIER_BUFFER_SIZE];
    header.get(identifier);
    if ((!Arrays.equals(identifier, XING_VBR_ID)) && (!Arrays.equals(identifier, XING_CBR_ID))) {
        return null;
    }
    MP3File.logger.finest("Found Xing Frame");
    return header;
}
 
Example 17
Project: rskj   File: RLPElementView.java   View Source Code Vote up 5 votes
private static long readBigEndianLong(ByteBuffer data) {
    // 0-based
    data = data.slice();
    byte pow = (byte) (data.remaining() - 1);
    long length = 0;
    for (int i = 0; i < data.remaining(); i++) {
        length += Byte.toUnsignedLong(data.get(i)) << (8 * pow);
        pow--;
    }

    return length;
}
 
Example 18
Project: jdk8u-jdk   File: Type1Font.java   View Source Code Vote up 5 votes
public synchronized ByteBuffer readBlock(int offset, int length) {
    ByteBuffer mappedBuf = null;
    try {
        mappedBuf = getBuffer();
        if (offset > fileSize) {
            offset = fileSize;
        }
        mappedBuf.position(offset);
        return mappedBuf.slice();
    } catch (FontFormatException e) {
        return null;
    }
}
 
Example 19
Project: ditb   File: IndexFile.java   View Source Code Vote up 4 votes
/**
 * @param metaBlockName
 * @param cacheBlock Add block to cache, if found
 * @return Block wrapped in a ByteBuffer
 * @throws IOException
 */
public ByteBuffer getMetaBlock(String metaBlockName, boolean cacheBlock)
throws IOException {
  if (trailer.metaIndexCount == 0) {
    return null; // there are no meta blocks
  }
  if (metaIndex == null) {
    throw new IOException("Meta index not loaded");
  }

  byte [] mbname = Bytes.toBytes(metaBlockName);
  int block = metaIndex.blockContainingKey(mbname, 0, mbname.length);
  if (block == -1)
    return null;
  long blockSize;
  if (block == metaIndex.count - 1) {
    blockSize = trailer.fileinfoOffset - metaIndex.blockOffsets[block];
  } else {
    blockSize = metaIndex.blockOffsets[block+1] - metaIndex.blockOffsets[block];
  }

  long now = System.currentTimeMillis();

  // Per meta key from any given file, synchronize reads for said block
  synchronized (metaIndex.blockKeys[block]) {
    metaLoads++;
    // Check cache for block.  If found return.
    if (cache != null) {
      ByteBuffer cachedBuf = cache.getBlock(name + "meta" + block,
          cacheBlock);
      if (cachedBuf != null) {
        // Return a distinct 'shallow copy' of the block,
        // so pos doesnt get messed by the scanner
        cacheHits++;
        return cachedBuf.duplicate();
      }
      // Cache Miss, please load.
    }

    ByteBuffer buf = decompress(metaIndex.blockOffsets[block],
      longToInt(blockSize), metaIndex.blockDataSizes[block], true);
    byte [] magic = new byte[METABLOCKMAGIC.length];
    buf.get(magic, 0, magic.length);

    if (! Arrays.equals(magic, METABLOCKMAGIC)) {
      throw new IOException("Meta magic is bad in block " + block);
    }

    // Create a new ByteBuffer 'shallow copy' to hide the magic header
    buf = buf.slice();

    readTime += System.currentTimeMillis() - now;
    readOps++;

    // Cache the block
    if(cacheBlock && cache != null) {
      cache.cacheBlock(name + "meta" + block, buf.duplicate(), inMemory);
    }

    return buf;
  }
}
 
Example 20
Project: ApkMultiChannelPlugin   File: ByteBufferDataSource.java   View Source Code Vote up 4 votes
/**
 * Constructs a new {@code ByteBufferDigestSource} based on the data contained in the provided
 * buffer between the buffer's position and limit.
 */
private ByteBufferDataSource(ByteBuffer buffer, boolean sliceRequired) {
    mBuffer = (sliceRequired) ? buffer.slice() : buffer;
    mSize = buffer.remaining();
}