List of usage examples for java.nio ByteBuffer capacity
public final int capacity()
From source file:net.dv8tion.jda.audio.AudioConnection.java
private byte[] encodeToOpus(byte[] rawAudio) { ShortBuffer nonEncodedBuffer = ShortBuffer.allocate(rawAudio.length / 2); ByteBuffer encoded = ByteBuffer.allocate(4096); for (int i = 0; i < rawAudio.length; i += 2) { int firstByte = (0x000000FF & rawAudio[i]); //Promotes to int and handles the fact that it was unsigned. int secondByte = (0x000000FF & rawAudio[i + 1]); // //Combines the 2 bytes into a short. Opus deals with unsigned shorts, not bytes. short toShort = (short) ((firstByte << 8) | secondByte); nonEncodedBuffer.put(toShort);//from www . j av a2 s . c om } nonEncodedBuffer.flip(); //TODO: check for 0 / negative value for error. int result = Opus.INSTANCE.opus_encode(opusEncoder, nonEncodedBuffer, OPUS_FRAME_SIZE, encoded, encoded.capacity()); //ENCODING STOPS HERE byte[] audio = new byte[result]; encoded.get(audio); return audio; }
From source file:com.emc.ecs.smart.SmartUploader.java
private void doUploadSegment(int segmentNumber) throws IOException { // Calculate the segment long segmentStart = (long) segmentNumber * (long) segmentSize; int segmentLength = segmentSize; if (segmentStart + segmentLength > fileSize) { segmentLength = (int) (fileSize - segmentStart); }//from w w w .java 2 s . c o m LogMF.debug(l4j, "Segment {0} is {1} bytes at position {2}", segmentNumber, segmentLength, segmentStart); ByteBuffer buf; if (segmentLength == segmentSize) { buf = getBuffer(); } else { buf = ByteBuffer.allocateDirect(segmentLength); } int c; synchronized (fileChannel) { c = fileChannel.read(buf, segmentStart); } if (c == -1) { throw new EOFException("Unexpected EOF at offset " + segmentStart); } if (c != buf.capacity()) { // Didn't read expected number? throw new IOException( String.format("Read %d bytes, expected %d at offset %d", c, segmentLength, segmentStart)); } // Make an MD5 so we can use Content-MD5. String md5 = calculateMD5(buf); // We have our data. Now upload it. WebResource.Builder builder; try { builder = client.resource(uploadUrl.toURI()).getRequestBuilder(); } catch (URISyntaxException e) { // Shouldn't happen; by now we've already parsed the URI throw new RuntimeException("Could not construct request", e); } builder.header(HttpHeaders.CONTENT_LENGTH, segmentLength)//.header("Content-MD5", md5) .header(HttpHeaders.CONTENT_TYPE, contentType); if (segmentNumber != 0) { builder.header("Range", buildRange(segmentStart, segmentLength)); } builder.put(new ByteBufferInputStream(buf)); incrementUpload(segmentLength); printPercent(); if (segmentLength == segmentSize) { returnBuffer(buf); } }
From source file:de.rwhq.btree.LeafNode.java
/** * * adds an entry to this LeafNodes rawPage, does not sync! * * @param key//from ww w. j a va 2 s .c o m * @param value */ private void addEntry(final K key, final V value) { final ByteBuffer buf = rawPage().bufferForWriting(0); int offset = offsetOfKey(key, true); if (offset == -1) { offset = offsetBehindLastEntry(); } else { // move everything including pos backwards System.arraycopy(buf.array(), offset, buf.array(), offset + keySerializer.getSerializedLength() + valueSerializer.getSerializedLength(), buf.capacity() - (offset + keySerializer.getSerializedLength() + valueSerializer.getSerializedLength())); } // insert both buf.position(offset); buf.put(keySerializer.serialize(key)); buf.put(valueSerializer.serialize(value)); setNumberOfEntries(getNumberOfEntries() + 1); }
From source file:com.slytechs.capture.file.editor.AbstractRawIterator.java
public boolean verifyAdditionalRecords(final ByteBuffer buffer, final int count) throws EOFException, IOException { buffer.reset();// www . j a v a2 s . c om final int MAX_HEADER_LENGTH = 24; final ByteBuffer view = BufferUtils.duplicate(buffer); final int capacity = view.capacity(); boolean status = true; for (int i = 0; i < count && view.position() + MAX_HEADER_LENGTH < capacity; i++) { view.mark(); long length = headerReader.readLength(view); int p = view.position() + (int) length; if (pattern.match(view) == false) { status = false; break; } view.reset(); if (p + MAX_HEADER_LENGTH > view.capacity()) { break; } view.limit(p + MAX_HEADER_LENGTH); view.position(p); } return status; }
From source file:com.flexive.core.stream.BinaryUploadProtocol.java
/** * {@inheritDoc}// w w w .jav a2 s. c o m */ @Override public synchronized boolean receiveStream(ByteBuffer buffer) throws IOException { if (!buffer.hasRemaining()) { //this can only happen on remote clients if (LOG.isDebugEnabled()) LOG.debug("aborting (empty)"); return false; } if (!rcvStarted) { rcvStarted = true; if (LOG.isDebugEnabled()) LOG.debug("(internal serverside) receive start"); try { pout = getContentStorage().receiveTransitBinary(division, handle, mimeType, expectedLength, timeToLive); } catch (SQLException e) { LOG.error("SQL Error trying to receive binary stream: " + e.getMessage(), e); } catch (FxNotFoundException e) { LOG.error("Failed to lookup content storage for division #" + division + ": " + e.getLocalizedMessage()); } } if (LOG.isDebugEnabled() && count + buffer.remaining() > expectedLength) { LOG.debug("poss. overflow: pos=" + buffer.position() + " lim=" + buffer.limit() + " cap=" + buffer.capacity()); LOG.debug("Curr count: " + count + " count+rem=" + (count + buffer.remaining() + " delta:" + ((count + buffer.remaining()) - expectedLength))); } count += buffer.remaining(); pout.write(buffer.array(), buffer.position(), buffer.remaining()); buffer.clear(); if (expectedLength > 0 && count >= expectedLength) { if (LOG.isDebugEnabled()) LOG.debug("aborting"); return false; } return true; }
From source file:org.tensorflow.demo.Camera2BasicFragment.java
protected void fillBytes(final Image.Plane[] planes, final byte[][] yuvBytes) { // Because of the variable row stride it's not possible to know in // advance the actual necessary dimensions of the yuv planes. for (int i = 0; i < planes.length; ++i) { final ByteBuffer buffer = planes[i].getBuffer(); if (yuvBytes[i] == null) { LOGGER.d("Initializing buffer %d at size %d", i, buffer.capacity()); yuvBytes[i] = new byte[buffer.capacity()]; }/* w ww.j av a 2 s . c o m*/ buffer.get(yuvBytes[i]); } Log.d("predict_class", "fill_bytes end."); }
From source file:edu.hawaii.soest.kilonalu.adcp.EnsembleFixedLeader.java
/** * Constructor. This method populates the Fixed Leader fields from * the given ByteBuffer of data passed in as an argument, based on metadata * found in the EnsembleHeader.// w w w. ja v a 2s. c o m * * @param ensembleBuffer the ByteBuffer that contains the binary ensemble data * @param ensemble the parent ensemble for this fixed leader */ public EnsembleFixedLeader(ByteBuffer ensembleBuffer, Ensemble ensemble) { // prepare the ensemble buffer for reading ensembleBuffer.flip(); ensembleBuffer.limit(ensembleBuffer.capacity()); // position the cursor at the correct offset given the sequential location // of the fixed leader in the data stream. int typeNumber = ensemble.getDataTypeNumber(EnsembleDataType.FIXED_LEADER); int offset = ensemble.getDataTypeOffset(typeNumber); ensembleBuffer.position(offset); // define the temporary arrays for passing bytes byte[] oneByte = new byte[1]; byte[] twoBytes = new byte[2]; // set all of the FixedLeader fields in the order that they are read from // the byte stream ensembleBuffer.get(twoBytes); setFixedLeaderID(twoBytes); ensemble.addToByteSum(twoBytes); ensembleBuffer.get(oneByte); setCpuFirmwareVersion(oneByte); ensemble.addToByteSum(oneByte); ensembleBuffer.get(oneByte); setCpuFirmwareRevision(oneByte); ensemble.addToByteSum(oneByte); ensembleBuffer.get(twoBytes); setSystemConfiguration(twoBytes); ensemble.addToByteSum(twoBytes); ensembleBuffer.get(oneByte); setPdRealOrSimulatedFlag(oneByte); ensemble.addToByteSum(oneByte); ensembleBuffer.get(oneByte); setLagLength(oneByte); ensemble.addToByteSum(oneByte); ensembleBuffer.get(oneByte); setNumberOfBeams(oneByte); ensemble.addToByteSum(oneByte); ensembleBuffer.get(oneByte); setNumberOfCells(oneByte); ensemble.addToByteSum(oneByte); ensembleBuffer.get(twoBytes); setPingsPerEnsemble(twoBytes); ensemble.addToByteSum(twoBytes); ensembleBuffer.get(twoBytes); setDepthCellLength(twoBytes); ensemble.addToByteSum(twoBytes); ensembleBuffer.get(twoBytes); setBlankAfterTransmit(twoBytes); ensemble.addToByteSum(twoBytes); ensembleBuffer.get(oneByte); setProfilingMode(oneByte); ensemble.addToByteSum(oneByte); ensembleBuffer.get(oneByte); setLowCorrelationThreshold(oneByte); ensemble.addToByteSum(oneByte); ensembleBuffer.get(oneByte); setNumberOfCodeRepetitions(oneByte); ensemble.addToByteSum(oneByte); ensembleBuffer.get(oneByte); setPercentGoodMinimum(oneByte); ensemble.addToByteSum(oneByte); ensembleBuffer.get(twoBytes); setErrorVelocityThreshold(twoBytes); ensemble.addToByteSum(twoBytes); ensembleBuffer.get(oneByte); setPingMinutes(oneByte); ensemble.addToByteSum(oneByte); ensembleBuffer.get(oneByte); setPingSeconds(oneByte); ensemble.addToByteSum(oneByte); ensembleBuffer.get(oneByte); setPingHundredths(oneByte); ensemble.addToByteSum(oneByte); ensembleBuffer.get(oneByte); setCoordinateTransformParams(oneByte); ensemble.addToByteSum(oneByte); ensembleBuffer.get(twoBytes); setHeadingAlignment(twoBytes); ensemble.addToByteSum(twoBytes); ensembleBuffer.get(twoBytes); setHeadingBias(twoBytes); ensemble.addToByteSum(twoBytes); ensembleBuffer.get(oneByte); setSensorSource(oneByte); ensemble.addToByteSum(oneByte); ensembleBuffer.get(oneByte); setSensorAvailability(oneByte); ensemble.addToByteSum(oneByte); ensembleBuffer.get(twoBytes); setBinOneDistance(twoBytes); ensemble.addToByteSum(twoBytes); ensembleBuffer.get(twoBytes); setTransmitPulseLength(twoBytes); ensemble.addToByteSum(twoBytes); ensembleBuffer.get(oneByte); setReferenceLayerStart(oneByte); ensemble.addToByteSum(oneByte); ensembleBuffer.get(oneByte); setReferenceLayerEnd(oneByte); ensemble.addToByteSum(oneByte); ensembleBuffer.get(oneByte); setFalseTargetThreshold(oneByte); ensemble.addToByteSum(oneByte); ensembleBuffer.get(oneByte); setFixedLeaderSpare(oneByte); ensemble.addToByteSum(oneByte); ensembleBuffer.get(twoBytes); setTransmitLagDistance(twoBytes); ensemble.addToByteSum(twoBytes); byte[] boardSerialNumber = new byte[8]; ensembleBuffer.get(boardSerialNumber); // read 8 bytes setCpuBoardSerialNumber(boardSerialNumber); ensemble.addToByteSum(boardSerialNumber); ensembleBuffer.get(twoBytes); setSystemBandwidth(twoBytes); ensemble.addToByteSum(twoBytes); ensembleBuffer.get(oneByte); setSystemPower(oneByte); ensemble.addToByteSum(oneByte); // the following don't get called for Workhorse ADCPs // TODO: test for model and add fields if necessary //ensembleBuffer.get(oneByte); //setBaseFrequencyIndex(oneByte); //ensemble.addToByteSum(oneByte); //byte[] instrumentSerialNumber = new byte[4]; //ensembleBuffer.get(instrumentSerialNumber); // read 4 bytes //setSerialNumber(instrumentSerialNumber); //ensemble.addToByteSum(instrumentSerialNumber); //ensembleBuffer.get(oneByte); //setBeamAngle(oneByte); //ensemble.addToByteSum(oneByte); }
From source file:edu.mbl.jif.imaging.mmtiff.MultipageTiffReader.java
private int writeIndexMap(long filePosition) throws IOException { //Write 4 byte header, 4 byte number of entries, and 20 bytes for each entry int numMappings = indexMap_.size(); ByteBuffer buffer = ByteBuffer.allocate(8 + 20 * numMappings).order(byteOrder_); buffer.putInt(0, MultipageTiffWriter.INDEX_MAP_HEADER); buffer.putInt(4, numMappings);//from w w w . java 2s . c o m int position = 2; for (String label : indexMap_.keySet()) { String[] indecies = label.split("_"); for (String index : indecies) { buffer.putInt(4 * position, Integer.parseInt(index)); position++; } buffer.putInt(4 * position, indexMap_.get(label).intValue()); position++; } fileChannel_.write(buffer, filePosition); ByteBuffer header = ByteBuffer.allocate(8).order(byteOrder_); header.putInt(0, MultipageTiffWriter.INDEX_MAP_OFFSET_HEADER); header.putInt(4, (int) filePosition); fileChannel_.write(header, 8); return buffer.capacity(); }
From source file:org.onlab.util.ImmutableByteSequenceTest.java
@Test public void testCopy() throws Exception { byte byteValue = (byte) 1; short shortValue = byteValue; int intValue = byteValue; long longValue = byteValue; byte[] arrayValue = new byte[64]; arrayValue[63] = byteValue;/* www .ja va2 s.c o m*/ ByteBuffer bufferValue = ByteBuffer.allocate(64).put(arrayValue); ImmutableByteSequence bsByte = ImmutableByteSequence.copyFrom(byteValue); ImmutableByteSequence bsShort = ImmutableByteSequence.copyFrom(shortValue); ImmutableByteSequence bsInt = ImmutableByteSequence.copyFrom(intValue); ImmutableByteSequence bsLong = ImmutableByteSequence.copyFrom(longValue); ImmutableByteSequence bsArray = ImmutableByteSequence.copyFrom(arrayValue); ImmutableByteSequence bsBuffer = ImmutableByteSequence.copyFrom(bufferValue); assertThat("byte sequence of a byte value must have size 1", bsByte.size(), is(equalTo(1))); assertThat("byte sequence of a short value must have size 2", bsShort.size(), is(equalTo(2))); assertThat("byte sequence of an int value must have size 4", bsInt.size(), is(equalTo(4))); assertThat("byte sequence of a long value must have size 8", bsLong.size(), is(equalTo(8))); assertThat("byte sequence of a byte array value must have same size of the array", bsArray.size(), is(equalTo(arrayValue.length))); assertThat("byte sequence of a byte buffer value must have same size of the buffer", bsBuffer.size(), is(equalTo(bufferValue.capacity()))); String errStr = "incorrect byte sequence value"; assertThat(errStr, bsByte.asArray()[0], is(equalTo(byteValue))); assertThat(errStr, bsShort.asArray()[1], is(equalTo(byteValue))); assertThat(errStr, bsInt.asArray()[3], is(equalTo(byteValue))); assertThat(errStr, bsLong.asArray()[7], is(equalTo(byteValue))); assertThat(errStr, bsArray.asArray()[63], is(equalTo(byteValue))); assertThat(errStr, bsBuffer.asArray()[63], is(equalTo(byteValue))); }
From source file:jext2.DataInode.java
/** * Read Inode data//from w w w. j av a2s.com * @param size size of the data to be read * @param offset start address in data area * @return buffer of size size containing data. * @throws FileTooLarge * @throws IoError */ public ByteBuffer readData(int size, long fileOffset) throws JExt2Exception, FileTooLarge { /* Returning null may break things somewhere.. * Zero length buffer breaks something in jlowfuse's c code */ if (getSize() == 0) return ByteBuffer.allocateDirect(1); /* * size may be larger than the inode.size, it doesn't make sense to return * 4k of zeros */ if (size > getSize()) size = (int) getSize(); ByteBuffer buf = ByteBuffer.allocateDirect(size); int blocksize = superblock.getBlocksize(); long i = 0; long firstBlock = fileOffset / blocksize; long offset = fileOffset % blocksize; /* * just as size may be larger than the inode's data, the number of blocks * may also be. */ long approxBlocks = (size / blocksize) + 1; long maxBlocks = this.getBlocks() / (superblock.getBlocksize() / 512); if (approxBlocks > maxBlocks) approxBlocks = maxBlocks; while (i < approxBlocks) { long start = firstBlock + i; long stop = firstBlock + approxBlocks; LinkedList<Long> b = accessData().getBlocks(start, stop); int blocksRead; /* * Note on the sparse file support: * getBlocks will return null if there is no data block for this * logical address. So just move the position count blocks forward. */ if (b == null) { /* hole */ blocksRead = 1; int unboundedLimit = buf.position() + blocksize; int limit = Math.min(unboundedLimit, buf.capacity()); assert limit <= buf.capacity() : "New position, limit " + limit + " is beyond buffer's capacity, " + buf; buf.limit(limit); buf.position(limit); assert buf.limit() == buf.position(); } else { /* blocks */ blocksRead = b.size(); long pos = b.getFirst() * blocksize + offset; int unboundedLimit = buf.position() + blocksRead * blocksize; int limit = Math.min(unboundedLimit, buf.capacity()); assert limit <= buf.capacity() : "New limit " + limit + " is beyond buffer's capacity, " + buf; buf.limit(limit); blockAccess.readToBufferUnsynchronized(pos, buf); } i += blocksRead; offset = 0; /* This should be removed soon. IllegalMonitorStateException happen * occasionally for unknown reasons. */ try { accessData().getHierarchyLock().readLock().unlock(); } catch (IllegalMonitorStateException e) { Logger log = Filesystem.getLogger(); log.warning("IllegalMonitorStateException encountered in readData, inode=" + this); log.warning(String.format( "context for exception: blocks=%s i=%d approxBlocks=%d off=%d buf=%s readlock=%s lock.readlock.holds=%s", b, i, approxBlocks, fileOffset, buf, accessData().getHierarchyLock(), accessData().getHierarchyLock().getReadHoldCount())); } if (buf.capacity() == buf.limit()) break; } assert buf.position() == buf.limit() : "Buffer wasn't filled completely"; assert buf.limit() == size : "Read buffer size does not match request size"; if (buf.limit() > getSize()) buf.limit((int) getSize()); buf.rewind(); return buf; }