Java Code Examples for java.nio.Buffer

The following examples show how to use java.nio.Buffer. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: Monocle   Source File: NativeCursors.java    License: GNU General Public License v2.0 6 votes vote down vote up
/** Creates a shifted version of the source cursor. Buffers must be
 * ShortBuffers for a bit depth of 16 or IntBuffers for a bit depth of 32.
 *
 * @param sourceBuffer The original cursor to be shifted
 * @param destBuffer A buffer to receive the shifted cursor
 * @param offsetX the number of pixels the cursor is to be shifted right
 * @param offsetY the number of pixels the cursor is to be shifted down
 * @param width the pixel width of the cursor
 * @param height the pixel height of the cursor
 * @param depth the pixel depth of the cursor (16 or 32)
 * @param transparentPixel the color key used for transparent pixels
 */
static void offsetCursor(Buffer sourceBuffer,
                                Buffer destBuffer,
                                int offsetX, int offsetY,
                                int width, int height,
                                int depth, int transparentPixel) {
    switch (depth) {
        case 32:
            offsetCursor32((IntBuffer) sourceBuffer,
                           (IntBuffer) destBuffer,
                           offsetX, offsetY,
                           width, height,
                           transparentPixel);
            break;
        case 16:
            offsetCursor16((ShortBuffer) sourceBuffer,
                           (ShortBuffer) destBuffer,
                           offsetX, offsetY,
                           width, height,
                           transparentPixel);
            break;
        default:
            throw new UnsupportedOperationException();
    }
}
 
Example 2
Source Project: deeplearning4j   Source File: BaseLoader.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Load an ndarray from a blob
 *
 * @param blob the blob to load from
 * @return the loaded ndarray
 */
@Override
public INDArray load(Blob blob) throws SQLException {
    if (blob == null)
        return null;
    try(InputStream is = blob.getBinaryStream()) {
        ByteBuffer direct = ByteBuffer.allocateDirect((int) blob.length());
        ReadableByteChannel readableByteChannel = Channels.newChannel(is);
        readableByteChannel.read(direct);
        Buffer byteBuffer = (Buffer) direct;
        byteBuffer.rewind();
        return BinarySerde.toArray(direct);
    } catch (Exception e) {
       throw new RuntimeException(e);
    }


}
 
Example 3
/**
 * shortBuffer��������Ƶ�����ݺ���ʼλ��
 * @param shortBuffer
 */
private void record(ShortBuffer shortBuffer)
{
	try
	{
		synchronized (mAudioRecordLock)
		{
			if (videoRecorder != null)
			{
				this.mCount += shortBuffer.limit();
				videoRecorder.record(0,new Buffer[] {shortBuffer});
			}
			return;
		}
	}
	catch (FrameRecorder.Exception localException){}
}
 
Example 4
Source Project: sis   Source File: ChannelDataOutput.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Writes {@code length} characters from the array to the stream.
 *
 * @param  dataSize  the size of the Java primitive type which is the element of the array.
 * @param  offset    the starting position within {@code src} to write.
 * @param  length    the number of characters to write.
 * @throws IOException if an error occurred while writing the stream.
 */
final void writeFully(final int dataSize, int offset, int length) throws IOException {
    clearBitOffset(); // Actually needed only if length == 0.
    ensureBufferAccepts(Math.min(length * dataSize, buffer.capacity()));
    final Buffer view = createView(); // Must be after ensureBufferAccept
    int n = Math.min(view.remaining(), length);
    transfer(offset, n);
    skipInBuffer(n * dataSize);
    while ((length -= n) != 0) {
        offset += n;
        ensureBufferAccepts(Math.min(length, view.capacity()) * dataSize);
        view.rewind().limit(buffer.remaining() / dataSize);
        transfer(offset, n = view.remaining());
        skipInBuffer(n * dataSize);
    }
}
 
Example 5
Source Project: nd4j   Source File: BaseLoader.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Load an ndarray from a blob
 *
 * @param blob the blob to load from
 * @return the loaded ndarray
 */
@Override
public INDArray load(Blob blob) throws SQLException {
    if (blob == null)
        return null;
    try(InputStream is = blob.getBinaryStream()) {
        ByteBuffer direct = ByteBuffer.allocateDirect((int) blob.length());
        ReadableByteChannel readableByteChannel = Channels.newChannel(is);
        readableByteChannel.read(direct);
        Buffer byteBuffer = (Buffer) direct;
        byteBuffer.rewind();
        return BinarySerde.toArray(direct);
    } catch (Exception e) {
       throw new RuntimeException(e);
    }


}
 
Example 6
Source Project: mp4parser   Source File: MjpegTest.java    License: Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws IOException {
    IsoFile isofile = new IsoFile("C:\\content\\bbb-small\\output_320x180-mjpeg.mp4");
    ESDescriptorBox esDescriptorBox = Path.getPath(isofile, "/moov[0]/trak[0]/mdia[0]/minf[0]/stbl[0]/stsd[0]/mp4v[0]/esds[0]");
    byte[] d = new byte[((Buffer)esDescriptorBox.getData()).rewind().remaining()];
    esDescriptorBox.getData().get(d);
    System.err.println(Hex.encodeHex(d));

    Movie mRef = MovieCreator.build("C:\\content\\bbb-small\\output_320x180_150.mp4");
    Track refTrack = mRef.getTracks().get(0);

    File baseDir = new File("C:\\content\\bbb-small");
    File[] iFrameJpegs = baseDir.listFiles(new FilenameFilter() {
        public boolean accept(File dir, String name) {
            return name.endsWith(".jpg");
        }
    });
    Arrays.sort(iFrameJpegs);

    Movie mRes = new Movie();
    mRes.addTrack(new OneJpegPerIframe("iframes", iFrameJpegs, refTrack));

    new DefaultMp4Builder().build(mRes).writeContainer(new FileOutputStream("output-mjpeg.mp4").getChannel());
}
 
Example 7
Source Project: mp4parser   Source File: VTTCueBox.java    License: Apache License 2.0 6 votes vote down vote up
public void getBox(WritableByteChannel writableByteChannel) throws IOException {
    ByteBuffer header = ByteBuffer.allocate(8);
    IsoTypeWriter.writeUInt32(header, getSize());
    header.put(IsoFile.fourCCtoBytes(getType()));
    writableByteChannel.write((ByteBuffer) ((Buffer)header).rewind());
    if (cueSourceIDBox != null) {
        cueSourceIDBox.getBox(writableByteChannel);
    }
    if (cueIDBox != null) {
        cueIDBox.getBox(writableByteChannel);
    }
    if (cueTimeBox != null) {
        cueTimeBox.getBox(writableByteChannel);
    }
    if (cueSettingsBox != null) {
        cueSettingsBox.getBox(writableByteChannel);
    }
    if (cuePayloadBox != null) {
        cuePayloadBox.getBox(writableByteChannel);
    }
}
 
Example 8
Source Project: djl   Source File: OrtUtils.java    License: Apache License 2.0 6 votes vote down vote up
public static OnnxTensor toTensor(
        OrtEnvironment env, Buffer data, Shape shape, DataType dataType) throws OrtException {
    long[] sh = shape.getShape();
    switch (dataType) {
        case FLOAT32:
            return OnnxTensor.createTensor(env, (FloatBuffer) data, sh);
        case FLOAT64:
            return OnnxTensor.createTensor(env, (DoubleBuffer) data, sh);
        case INT32:
            return OnnxTensor.createTensor(env, (IntBuffer) data, sh);
        case INT64:
            return OnnxTensor.createTensor(env, (LongBuffer) data, sh);
        case INT8:
        case UINT8:
            return OnnxTensor.createTensor(env, (ByteBuffer) data, sh, OnnxJavaType.INT8);
        case BOOLEAN:
            return OnnxTensor.createTensor(env, (ByteBuffer) data, sh, OnnxJavaType.BOOL);
        case FLOAT16:
        default:
            throw new EngineException("Data type not supported: " + dataType);
    }
}
 
Example 9
Source Project: sis   Source File: ImageRenderer.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Sets the data as vectors. The number of vectors must be equal to the {@linkplain #getNumBands() expected number of bands}.
 * All vectors must be backed by arrays (indirectly, through {@linkplain Vector#buffer() buffers} backed by arrays) and have
 * the same {@linkplain Vector#size() size}.
 * This method wraps the underlying arrays of a primitive type into a Java2D buffer; data are not copied.
 *
 * <p><b>Implementation note:</b> the NIO buffers are set by a call to {@link #setData(int, Buffer...)},
 * which can be overridden by subclasses if desired.</p>
 *
 * @param  data  the vectors wrapping arrays of primitive type.
 * @throws NullArgumentException if {@code data} is null or one of {@code data} element is null.
 * @throws MismatchedCoverageRangeException if the number of specified vectors is not equal to the number of bands.
 * @throws UnsupportedOperationException if a vector is not backed by an accessible array or is read-only.
 * @throws RasterFormatException if vectors do not have the same size.
 * @throws ArithmeticException if a buffer position overflows the 32 bits integer capacity.
 */
public void setData(final Vector... data) {
    ArgumentChecks.ensureNonNull("data", data);
    ensureExpectedBandCount(data.length, true);
    final Buffer[] buffers = new Buffer[data.length];
    int dataType = DataBuffer.TYPE_UNDEFINED;
    for (int i=0; i<data.length; i++) {
        final Vector v = data[i];
        ArgumentChecks.ensureNonNullElement("data", i, v);
        final int t = RasterFactory.getType(v.getElementType(), v.isUnsigned());
        if (dataType != t) {
            if (i != 0) {
                throw new RasterFormatException(Resources.format(Resources.Keys.MismatchedDataType));
            }
            dataType = t;
        }
        buffers[i] = v.buffer().orElseThrow(UnsupportedOperationException::new);
    }
    setData(dataType, buffers);
}
 
Example 10
/**
 * Called to initialize the data in the <code>VertexBuffer</code>. Must only
 * be called once.
 * 
 * @param usage The usage for the data, or how often will the data
 * be updated per frame. See the {@link Usage} enum.
 * @param components The number of components per element.
 * @param format The {@link Format format}, or data-type of a single
 * component.
 * @param data A native buffer, the format of which matches the {@link Format}
 * argument.
 */
public void setupData(Usage usage, int components, Format format, Buffer data){
    if (id != -1)
        throw new UnsupportedOperationException("Data has already been sent. Cannot setupData again.");

    if (usage == null || format == null || data == null)
        throw new IllegalArgumentException("None of the arguments can be null");
        
    if (components < 1 || components > 4)
        throw new IllegalArgumentException("components must be between 1 and 4");

    this.data = data;
    this.components = components;
    this.usage = usage;
    this.format = format;
    this.componentsLength = components * format.getComponentSize();
    this.lastLimit = data.limit();
    setUpdateNeeded();
}
 
Example 11
Source Project: DataVec   Source File: ImageWritable.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public boolean equals(Object obj) {
    if (obj instanceof ImageWritable) {
        Frame f2 = ((ImageWritable) obj).getFrame();

        Buffer[] b1 = this.frame.image;
        Buffer[] b2 = f2.image;

        if (b1.length != b2.length)
            return false;

        for (int i = 0; i < b1.length; i++) {
            if (!b1[i].equals(b2[i]))
                return false;
        }

        return true;
    } else {
        return false;
    }
}
 
Example 12
Source Project: mp4parser   Source File: TemporalLevelEntry.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public ByteBuffer get() {
    ByteBuffer content = ByteBuffer.allocate(1);
    content.put((byte) (levelIndependentlyDecodable ? 0x80 : 0x00));
    ((Buffer)content).rewind();
    return content;
}
 
Example 13
Source Project: snowblossom   Source File: LayerWorkThread.java    License: Apache License 2.0 5 votes vote down vote up
protected void runPass() throws Exception
{
   PartialWork pw = null;
   pw=queue.poll();

   if (pw == null)
   {
     WorkUnit wu = arktika.getWorkUnit();
     if (wu == null)
     {
       sleep(250);
       return;
     }
     if (is_mem)
     {
       long t1 = System.nanoTime();
       yield();
       long t_diff = System.nanoTime() - t1;
       /*if (t_diff > 10000)
       {
         synchronized(queue)
         {
           queue.wait(10000);
         } 
         return;
       }*/
     }

     pw = new PartialWork(wu, rnd, md, total_words);
   }
   else
   {
     ((Buffer)word_bb).clear();
     fs.readWord(pw.next_word_idx, word_bb);
     pw.doPass(word_buff, md, total_words);
   }
   processPw(pw);
}
 
Example 14
Source Project: snowflake-jdbc   Source File: ResultJsonParserV2.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Continue parsing with the given data
 *
 * @param in readOnly byteBuffer backed by an array (the data to be reed is from position to limit)
 */
public void continueParsing(ByteBuffer in) throws SnowflakeSQLException
{
  if (state == State.UNINITIALIZED)
  {
    throw new SnowflakeSQLException(SqlState.INTERNAL_ERROR,
                                    ErrorCode.INTERNAL_ERROR.getMessageCode(),
                                    "Json parser hasn't been initialized!");
  }

  // If stopped during a \\u, continue here
  if (((Buffer) partialEscapedUnicode).position() > 0)
  {
    int lenToCopy = Math.min(12 - ((Buffer) partialEscapedUnicode).position(), in.remaining());
    if (lenToCopy > partialEscapedUnicode.remaining())
    {
      resizePartialEscapedUnicode(lenToCopy);
    }
    partialEscapedUnicode.put(in.array(), in.arrayOffset() + ((Buffer) in).position(), lenToCopy);
    ((Buffer) in).position(((Buffer) in).position() + lenToCopy);

    if (((Buffer) partialEscapedUnicode).position() < 12)
    {
      // Not enough data to parse escaped unicode
      return;
    }
    ByteBuffer toBeParsed = partialEscapedUnicode.duplicate();
    ((Buffer) toBeParsed).flip();
    continueParsingInternal(toBeParsed, false);
    ((Buffer) partialEscapedUnicode).clear();
  }
  continueParsingInternal(in, false);
}
 
Example 15
Source Project: BetterBackdoor   Source File: FTP.java    License: MIT License 5 votes vote down vote up
/**
 * Receives file with path {@code filePath} using {@code socketChannel} and
 * {@code fileChannel}.
 *
 * @param filePath      path of file to receive
 * @param socketChannel {@link java.nio.channels.SocketChannel} to use for
 *                      receiving
 * @throws IOException
 */
private static void rec(String filePath, SocketChannel socketChannel) throws IOException {
	RandomAccessFile file = new RandomAccessFile(filePath, "rw");
	FileChannel fileChannel = file.getChannel();
	ByteBuffer buffer = ByteBuffer.allocate(1024);
	while (socketChannel.read(buffer) > 0) {
		((Buffer) buffer).flip();
		fileChannel.write(buffer);
		((Buffer) buffer).clear();
	}
	file.close();
	fileChannel.close();
}
 
Example 16
Source Project: constellation   Source File: Batch.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new Batch for the specified GL primitive type.
 *
 * @param primitive A primitive drawing type: see OpenGL 3.3 section 2.6.1
 * and the definition of DrawArrays.
 */
public Batch(final int primitive) {

    this.primitiveType = primitive;
    bufferNames = new int[ShaderManager.ATTRIBUTE_LAST][];
    bufferIsFloat = new boolean[ShaderManager.ATTRIBUTE_LAST];
    bufferIsLocal = new boolean[ShaderManager.ATTRIBUTE_LAST];
    bufferSizePerVertex = new int[ShaderManager.ATTRIBUTE_LAST];
    buffers = new Buffer[ShaderManager.ATTRIBUTE_LAST];
    Arrays.fill(bufferNames, new int[0]);
}
 
Example 17
@Override
public void parse(ReadableByteChannel dataSource, ByteBuffer header, long contentSize, BoxParser boxParser) throws IOException {
    ByteBuffer bb = ByteBuffer.allocate(8);
    dataSource.read(bb);
    ((Buffer)bb).position(6);// ignore 6 reserved bytes;
    dataReferenceIndex = IsoTypeReader.readUInt16(bb);
    initContainer(dataSource, contentSize - 8, boxParser);
}
 
Example 18
Source Project: PanoramaGL   Source File: GLWrapper.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void glCompressedTexSubImage2D(int target, int level, int xoffset,
		int yoffset, int width, int height, int format, int imageSize,
		Buffer data)
{
	mGL.glCompressedTexSubImage2D(target, level, xoffset, yoffset, width, height, format, imageSize, data);
}
 
Example 19
Source Project: mzmine3   Source File: RawDataFileImpl.java    License: GNU General Public License v2.0 5 votes vote down vote up
public synchronized DataPoint[] readDataPoints(int ID) throws IOException {

    final Long currentOffset = dataPointsOffsets.get(ID);
    final Integer numOfDataPoints = dataPointsLengths.get(ID);

    if ((currentOffset == null) || (numOfDataPoints == null)) {
      throw new IllegalArgumentException("Unknown storage ID " + ID);
    }

    final int numOfBytes = numOfDataPoints * 2 * 4;

    if (buffer.capacity() < numOfBytes) {
      buffer = ByteBuffer.allocate(numOfBytes * 2);
    } else {
      // JDK 9 breaks compatibility with JRE8: need to cast
      // https://stackoverflow.com/questions/48693695/java-nio-buffer-not-loading-clear-method-on-runtime
      ((Buffer) buffer).clear();
    }

    dataPointsFile.seek(currentOffset);
    dataPointsFile.read(buffer.array(), 0, numOfBytes);

    FloatBuffer floatBuffer = buffer.asFloatBuffer();

    DataPoint dataPoints[] = new DataPoint[numOfDataPoints];

    for (int i = 0; i < numOfDataPoints; i++) {
      float mz = floatBuffer.get();
      float intensity = floatBuffer.get();
      dataPoints[i] = new SimpleDataPoint(mz, intensity);
    }

    return dataPoints;

  }
 
Example 20
Source Project: OSPREY3   Source File: GpuStream.java    License: GNU General Public License v2.0 5 votes vote down vote up
public <T extends Buffer> CUBuffer<T> makeOrExpandBuffer(CUBuffer<T> dest, T src) {
	if (dest == null) {
		return makeBuffer(src);
	}
	dest.expand(src);
	return dest;
}
 
Example 21
void resetToBind() {
    for (Geometry geometry : targets) {
        Mesh mesh = geometry.getMesh();
        if (mesh != null && mesh.isAnimated()) {
            Buffer bwBuff = mesh.getBuffer(Type.BoneWeight).getData();
            Buffer biBuff = mesh.getBuffer(Type.BoneIndex).getData();
            if (!biBuff.hasArray() || !bwBuff.hasArray()) {
                mesh.prepareForAnim(true); // prepare for software animation
            }
            VertexBuffer bindPos = mesh.getBuffer(Type.BindPosePosition);
            VertexBuffer bindNorm = mesh.getBuffer(Type.BindPoseNormal);
            VertexBuffer pos = mesh.getBuffer(Type.Position);
            VertexBuffer norm = mesh.getBuffer(Type.Normal);
            FloatBuffer pb = (FloatBuffer) pos.getData();
            FloatBuffer nb = (FloatBuffer) norm.getData();
            FloatBuffer bpb = (FloatBuffer) bindPos.getData();
            FloatBuffer bnb = (FloatBuffer) bindNorm.getData();
            pb.clear();
            nb.clear();
            bpb.clear();
            bnb.clear();

            //reseting bind tangents if there is a bind tangent buffer
            VertexBuffer bindTangents = mesh.getBuffer(Type.BindPoseTangent);
            if (bindTangents != null) {
                VertexBuffer tangents = mesh.getBuffer(Type.Tangent);
                FloatBuffer tb = (FloatBuffer) tangents.getData();
                FloatBuffer btb = (FloatBuffer) bindTangents.getData();
                tb.clear();
                btb.clear();
                tb.put(btb).clear();
            }


            pb.put(bpb).clear();
            nb.put(bnb).clear();
        }
    }
}
 
Example 22
private static void checkLimit(Buffer buffer) {
    if (buffer == null) {
        return;
    }
    if (buffer.limit() == 0) {
        throw new RendererException("Attempting to upload empty buffer (limit = 0), that's an error");
    }
    if (buffer.remaining() == 0) {
        throw new RendererException("Attempting to upload empty buffer (remaining = 0), that's an error");
    }
}
 
Example 23
Source Project: edireader   Source File: EDITokenizer.java    License: GNU General Public License v3.0 5 votes vote down vote up
/**
     * Look ahead into the source of input chars and return the next n chars to
     * be seen, without disturbing the normal operation of getChar().
     *
     * @param n number of chars to return
     * @return char[] containing upcoming input chars
     * @throws IOException for problem reading EDI data
     */
    public char[] lookahead(int n) throws IOException {
        logger.debug("EDITokenizer.lookahead({})", n);
        char[] rval = new char[n];

        // The 1st char is grabbed using the tokenizer's built-in
        // getChar() / ungetChar() mechanism. This allows things to work
        // properly whether or not the next char has already been gotten.
        getChar();
        rval[0] = cChar;
        ungetChar();

        // The minus 1 is because we have already filled the first char of the return value, so we only need n-1 more
        if (charBuffer.remaining() < n - 1) {
            logger.debug("Buffering more data to satisfy lookahead({}})", n);
            readUntilBufferProvidesAtLeast(n - 1);
        }

        // Move chars from the buffer into the return value
        int j = 1;
        for (int i = charBuffer.position(); i < ((Buffer) charBuffer).limit() && j < n; i++)
            rval[j++] = charBuffer.get(i);

        // If more lookahead chars were requested than were satisfied for any reason,
        // then fill the return value with '?' to the requested length.
        for (; j < n; ) {
            rval[j++] = '?';
//            throw new RuntimeException("problem with lookahead " + n);
        }

        return rval;
    }
 
Example 24
Source Project: mp4parser   Source File: SampleImpl.java    License: Apache License 2.0 5 votes vote down vote up
public ByteBuffer asByteBuffer() {
    byte[] bCopy = new byte[l2i(size)];
    ByteBuffer copy = ByteBuffer.wrap(bCopy);
    for (ByteBuffer b : data) {
        copy.put(b.duplicate());
    }
    ((Buffer)copy).rewind();
    return copy;
}
 
Example 25
void resetToBind() {
    for (Mesh mesh : targets) {
        if (mesh.isAnimated()) {
            Buffer bwBuff = mesh.getBuffer(Type.BoneWeight).getData();
            Buffer biBuff = mesh.getBuffer(Type.BoneIndex).getData();
            if (!biBuff.hasArray() || !bwBuff.hasArray()) {
                mesh.prepareForAnim(true); // prepare for software animation
            }
            VertexBuffer bindPos = mesh.getBuffer(Type.BindPosePosition);
            VertexBuffer bindNorm = mesh.getBuffer(Type.BindPoseNormal);
            VertexBuffer pos = mesh.getBuffer(Type.Position);
            VertexBuffer norm = mesh.getBuffer(Type.Normal);
            FloatBuffer pb = (FloatBuffer) pos.getData();
            FloatBuffer nb = (FloatBuffer) norm.getData();
            FloatBuffer bpb = (FloatBuffer) bindPos.getData();
            FloatBuffer bnb = (FloatBuffer) bindNorm.getData();
            pb.clear();
            nb.clear();
            bpb.clear();
            bnb.clear();

            //reseting bind tangents if there is a bind tangent buffer
            VertexBuffer bindTangents = mesh.getBuffer(Type.BindPoseTangent);
            if (bindTangents != null) {
                VertexBuffer tangents = mesh.getBuffer(Type.Tangent);
                FloatBuffer tb = (FloatBuffer) tangents.getData();
                FloatBuffer btb = (FloatBuffer) bindTangents.getData();
                tb.clear();
                btb.clear();
                tb.put(btb).clear();
            }


            pb.put(bpb).clear();
            nb.put(bnb).clear();
        }
    }
}
 
Example 26
Source Project: djl   Source File: OrtUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static NDArray toNDArray(NDManager manager, OnnxTensor tensor) {
    if (manager instanceof OrtNDManager) {
        return ((OrtNDManager) manager).create(tensor);
    }
    ByteBuffer bb = tensor.getByteBuffer();
    bb.order(ByteOrder.nativeOrder());
    DataType dataType = OrtUtils.toDataType(tensor.getInfo().type);
    Shape shape = new Shape(tensor.getInfo().getShape());
    Buffer buf = dataType.asDataType(bb);
    tensor.close();
    return manager.create(buf, shape, dataType);
}
 
Example 27
Source Project: Ultraino   Source File: BufferUtils.java    License: MIT License 5 votes vote down vote up
@Override
public void run() {
    try {
        while (true) {
            Reference<? extends Buffer> toclean = BufferUtils.removeCollected.remove();
            BufferUtils.trackedBuffers.remove(toclean);
        }

    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}
 
Example 28
Source Project: edireader   Source File: EDITokenizer.java    License: GNU General Public License v3.0 5 votes vote down vote up
/**
 * Returns a String representation of the current state of the tokenizer
 * for testing and debugging purposes.
 *
 * @return String representation
 */
@Override
public String toString() {
    String result = "tokenizer state:";
    result += " segmentCount=" + segmentCount;
    result += " charCount=" + charCount;
    result += " segTokenCount=" + segTokenCount;
    result += " segCharCount=" + segCharCount;
    result += " currentToken=" + currentToken;
    result += " buffer.limit=" + ((Buffer) charBuffer).limit();
    result += " buffer.position=" + charBuffer.position();
    return result;
}
 
Example 29
Source Project: mp4parser   Source File: SampleDescriptionBox.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void parse(ReadableByteChannel dataSource, ByteBuffer header, long contentSize, BoxParser boxParser) throws IOException {
    ByteBuffer versionFlagNumOfChildBoxes = ByteBuffer.allocate(8);
    dataSource.read(versionFlagNumOfChildBoxes);
    ((Buffer)versionFlagNumOfChildBoxes).rewind();
    version = IsoTypeReader.readUInt8(versionFlagNumOfChildBoxes);
    flags = IsoTypeReader.readUInt24(versionFlagNumOfChildBoxes);
    // number of child boxes is not required
    initContainer(dataSource, contentSize - 8, boxParser);
}
 
Example 30
public void updateBufferData(VertexBuffer vb) {
    int bufId = vb.getId();
    if (bufId == -1) {
        // create buffer
        gl.glGenBuffers(1, ib1);
        bufId = ib1.get(0);
        vb.setId(bufId);
        objManager.registerForCleanup(vb);
    }

    int target;
    if (vb.getBufferType() == VertexBuffer.Type.Index) {
        target = gl.GL_ELEMENT_ARRAY_BUFFER;
        if (context.boundElementArrayVBO != bufId) {
            gl.glBindBuffer(target, bufId);
            context.boundElementArrayVBO = bufId;
        }
    } else {
        target = gl.GL_ARRAY_BUFFER;
        if (context.boundArrayVBO != bufId) {
            gl.glBindBuffer(target, bufId);
            context.boundArrayVBO = bufId;
        }
    }

    int usage = convertUsage(vb.getUsage());
    Buffer data = vb.getData();
    data.rewind();

    gl.glBufferData(target,
            data.capacity() * vb.getFormat().getComponentSize(),
            data,
            usage);

    vb.clearUpdateNeeded();
}