Example usage for java.nio ByteBuffer allocateDirect

List of usage examples for java.nio ByteBuffer allocateDirect

Introduction

In this page you can find the example usage for java.nio ByteBuffer allocateDirect.

Prototype

public static ByteBuffer allocateDirect(int capacity) 

Source Link

Document

Creates a direct byte buffer based on a newly allocated memory block.

Usage

From source file:org.ros.android.rviz_for_android.drawable.loader.ColladaLoader.java

private ETC1Texture compressBitmap(Bitmap uncompressedBitmap) {
    // Rescale the bitmap to be half its current size
    Bitmap uncompressedBitmapResize = Bitmap.createScaledBitmap(uncompressedBitmap,
            uncompressedBitmap.getWidth() / 4, uncompressedBitmap.getHeight() / 4, true);
    uncompressedBitmap.recycle();//from  w w  w.  ja v  a 2s.c o  m

    // Copy the bitmap to a byte buffer
    ByteBuffer uncompressedBytes = ByteBuffer.allocateDirect(uncompressedBitmapResize.getByteCount())
            .order(ByteOrder.nativeOrder());
    uncompressedBitmapResize.copyPixelsToBuffer(uncompressedBytes);
    uncompressedBytes.position(0);

    int width = uncompressedBitmapResize.getWidth();
    int height = uncompressedBitmapResize.getHeight();

    // Compress the texture
    int encodedSize = ETC1.getEncodedDataSize(width, height);
    ByteBuffer compressed = ByteBuffer.allocateDirect(encodedSize).order(ByteOrder.nativeOrder());
    ETC1.encodeImage(uncompressedBytes, width, height, 2, 2 * width, compressed);

    ETC1Texture retval = new ETC1Texture(width, height, compressed);

    // We're done with the uncompressed bitmap, release it
    uncompressedBitmapResize.recycle();

    return retval;
}

From source file:io.github.dsheirer.source.tuner.hackrf.HackRFTunerController.java

/**
 * Sends a request that doesn't have a data payload
 *//*from   w  w w. j a va2  s  .c  o  m*/
public void write(Request request, int value, int index) throws UsbException {
    write(request, value, index, ByteBuffer.allocateDirect(0));
}

From source file:org.mycore.common.content.util.MCRServletContentHelper.java

private static long copyChannel(final ReadableByteChannel src, final WritableByteChannel dest,
        final int bufferSize) throws IOException {
    if (src instanceof FileChannel) {
        return copyFileChannel((FileChannel) src, dest, bufferSize);
    }/*  ww w. j  av  a  2  s  .c o m*/
    long bytes = 0;
    final ByteBuffer buffer = ByteBuffer.allocateDirect(bufferSize);
    while (src.read(buffer) != -1) {
        // prepare the buffer to be drained
        buffer.flip();

        // write to the channel, may block
        bytes += dest.write(buffer);
        // If partial transfer, shift remainder down
        // If buffer is empty, same as doing clear()
        buffer.compact();
    }
    // EOF will leave buffer in fill state
    buffer.flip();
    // make sure the buffer is fully drained.
    while (buffer.hasRemaining()) {
        bytes += dest.write(buffer);
    }
    return bytes;
}

From source file:it.unimi.di.big.mg4j.index.DiskBasedIndex.java

/** Commodity method for loading from a channel a big list of binary longs with specified endianness into a {@linkplain LongBigArrays long big array}.
 * // ww w .ja  va  2 s. com
 * @param channel the channel.
 * @param byteOrder the endianness of the longs.
 * @return a big list of longs containing the longs returned by <code>channel</code>.
 */
public static LongBigArrayBigList loadLongBigList(final ReadableByteChannel channel, final long length,
        final ByteOrder byteOrder) throws IOException {
    final ByteBuffer byteBuffer = ByteBuffer.allocateDirect(BUFFER_SIZE).order(byteOrder);

    LongBigArrayBigList list = new LongBigArrayBigList(length);

    while (channel.read(byteBuffer) > 0) {
        byteBuffer.flip();
        while (byteBuffer.hasRemaining())
            list.add(byteBuffer.getLong());
        byteBuffer.clear();
    }

    return list;
}

From source file:org.gallery.web.controller.ImageController.java

@RequestMapping(value = "/colortheme/{id}", method = RequestMethod.GET)
@ResponseBody//  ww w.jav  a  2s.  com
public ColorThemeVO colorTheme(@PathVariable("id") Long id)
        throws JsonParseException, JsonMappingException, IOException, SQLException {
    ImageEntity entity = imageDao.getById(id);
    ThumbnailSize thumbnail_Enum = ThumbnailSize.SMALL_SIZE;
    String srcImagePath = fileUploadDirectory + File.separator + thumbnail_Enum.getId()
            + entity.getNewFilename() + "." + thumbnail_Enum.getFormatName();

    Pointer<Byte> srcImageName = pointerToCString(srcImagePath);
    log.debug("Read Image:" + srcImagePath.toString());
    // Memory allocated from Java using Pointer.allocateXXX and
    // Pointer.pointerToXXX methods has known valid bounds. Pointers that
    // wrap direct NIO buffers also have known valid bounds that they take
    // from the buffer.
    int colorNum = ImageConvertDllLibrary.getColorNum(srcImageName);
    ByteBuffer rBuf = ByteBuffer.allocateDirect(colorNum);
    ByteBuffer gBuf = ByteBuffer.allocateDirect(colorNum);
    ByteBuffer bBuf = ByteBuffer.allocateDirect(colorNum);
    Pointer<Byte> r = pointerToBytes(rBuf);
    Pointer<Byte> g = pointerToBytes(gBuf);
    Pointer<Byte> b = pointerToBytes(bBuf);
    Pointer<Double> percent = allocateDoubles(colorNum);
    ImageConvertDllLibrary.getColorTheme(srcImageName, r, g, b, percent);

    // Serialize and Deserialize
    ColorThemeEntity colorThemeEntity = new ColorThemeEntity(colorNum, r, g, b, percent);
    ColorThemeVO result = new ColorThemeVO(colorThemeEntity);
    return result;
}

From source file:org.vast.stt.renderer.opengl.TextureManager.java

/**
 * Create a texture based on data passed by styler
 * @param styler//  www  . j  a va  2 s  . co m
 * @param tex
 * @param texInfo
 */
protected void fillTexData(TextureStyler styler, RasterTileGraphic tex, GLTexture texInfo) {
    int paddedWidth = tex.width;
    int paddedHeight = tex.height;
    int initialWidth = tex.width;
    int initialHeight = tex.height;

    // handle case of padding for npot
    if (!npotSupported) {
        // determine closest power of 2
        paddedWidth = closestHigherPowerOfTwo(initialWidth);
        paddedHeight = closestHigherPowerOfTwo(initialHeight);

        // display warning message if padding is needed
        if (paddedWidth != initialWidth || paddedHeight != initialHeight) {
            MessageSystem.display("Texture will be padded to have a power of two size.\n" + "    initial size: "
                    + initialWidth + " x " + initialHeight + "\n" + "     padded size: " + paddedWidth + " x "
                    + paddedHeight, false);

            texInfo.widthPadding = paddedWidth - initialWidth;
            texInfo.heightPadding = paddedHeight - initialHeight;
        }

        if (log.isDebugEnabled())
            log.debug(
                    "Creating " + paddedWidth + " x " + paddedHeight + " Texture with " + tex.bands + " bands");
    }

    // create byte buffer of the right size
    ByteBuffer buffer = ByteBuffer.allocateDirect(paddedWidth * paddedHeight * tex.bands);
    int index = 0;

    for (int j = 0; j < initialHeight; j++) {
        for (int i = 0; i < initialWidth; i++) {
            RasterPixelGraphic pixel = styler.getPixel(i + tex.xPos, j + tex.yPos);
            buffer.put(index, (byte) pixel.r);
            index++;

            // only if RGB
            if (tex.bands > 2) {
                buffer.put(index, (byte) pixel.g);
                index++;
                buffer.put(index, (byte) pixel.b);
                index++;
            }

            // only if RGBA
            if (tex.bands == 2 || tex.bands == 4) {
                buffer.put(index, (byte) pixel.a);
                index++;
            }
        }

        // skip padding bytes
        index += texInfo.widthPadding * tex.bands;
    }

    tex.rasterData = buffer;
    tex.hasRasterData = true;
}

From source file:io.github.dsheirer.source.tuner.hackrf.HackRFTunerController.java

public void setSampleRateManual(int frequency, int divider) throws UsbException {
    ByteBuffer buffer = ByteBuffer.allocateDirect(8);

    buffer.order(ByteOrder.LITTLE_ENDIAN);

    buffer.putInt(frequency);/*from   www  .ja va  2  s. co  m*/
    buffer.putInt(divider);

    write(Request.SET_SAMPLE_RATE, 0, 0, buffer);
}

From source file:com.tumblr.cardboard.Tumblr3DActivity.java

/**
 * Creates the buffers we use to store information about the 3D world. OpenGL doesn't use Java
 * arrays, but rather needs data in a format it can understand. Hence we use ByteBuffers.
 *
 * @param config The EGL configuration used when creating the surface.
 *//*from www . j av  a2s .c  om*/
@Override
public void onSurfaceCreated(EGLConfig config) {
    Log.i(TAG, "onSurfaceCreated");
    GLES20.glClearColor(0.1f, 0.1f, 0.1f, 0.5f); // Dark background so text shows up well

    ByteBuffer bbVertices = ByteBuffer.allocateDirect(WorldLayoutData.RECT_COORDS.length * 4);
    bbVertices.order(ByteOrder.nativeOrder());
    mRectVertices = bbVertices.asFloatBuffer();
    mRectVertices.put(WorldLayoutData.RECT_COORDS);
    mRectVertices.position(0);

    ByteBuffer bbColors = ByteBuffer.allocateDirect(WorldLayoutData.RECT_COLORS.length * 4);
    bbColors.order(ByteOrder.nativeOrder());
    mRectColors = bbColors.asFloatBuffer();
    mRectColors.put(WorldLayoutData.RECT_COLORS);
    mRectColors.position(0);

    ByteBuffer bbFoundColors = ByteBuffer.allocateDirect(WorldLayoutData.RECT_FOUND_COLORS.length * 4);
    bbFoundColors.order(ByteOrder.nativeOrder());
    mRectFoundColors = bbFoundColors.asFloatBuffer();
    mRectFoundColors.put(WorldLayoutData.RECT_FOUND_COLORS);
    mRectFoundColors.position(0);

    ByteBuffer bbNormals = ByteBuffer.allocateDirect(WorldLayoutData.RECT_NORMALS.length * 4);
    bbNormals.order(ByteOrder.nativeOrder());
    mRectNormals = bbNormals.asFloatBuffer();
    mRectNormals.put(WorldLayoutData.RECT_NORMALS);
    mRectNormals.position(0);

    ByteBuffer bbTextureCoordinates = ByteBuffer.allocateDirect(WorldLayoutData.RECT_TEX_COORDS.length * 4);
    bbTextureCoordinates.order(ByteOrder.nativeOrder());
    mRectTexCoords = bbTextureCoordinates.asFloatBuffer();
    mRectTexCoords.put(WorldLayoutData.RECT_TEX_COORDS);
    mRectTexCoords.position(0);

    // make a floor
    ByteBuffer bbFloorVertices = ByteBuffer.allocateDirect(WorldLayoutData.FLOOR_COORDS.length * 4);
    bbFloorVertices.order(ByteOrder.nativeOrder());
    mFloorVertices = bbFloorVertices.asFloatBuffer();
    mFloorVertices.put(WorldLayoutData.FLOOR_COORDS);
    mFloorVertices.position(0);

    ByteBuffer bbFloorNormals = ByteBuffer.allocateDirect(WorldLayoutData.FLOOR_NORMALS.length * 4);
    bbFloorNormals.order(ByteOrder.nativeOrder());
    mFloorNormals = bbFloorNormals.asFloatBuffer();
    mFloorNormals.put(WorldLayoutData.FLOOR_NORMALS);
    mFloorNormals.position(0);

    ByteBuffer bbFloorColors = ByteBuffer.allocateDirect(WorldLayoutData.FLOOR_COLORS.length * 4);
    bbFloorColors.order(ByteOrder.nativeOrder());
    mFloorColors = bbFloorColors.asFloatBuffer();
    mFloorColors.put(WorldLayoutData.FLOOR_COLORS);
    mFloorColors.position(0);

    int vertexShader = loadGLShader(GLES20.GL_VERTEX_SHADER, R.raw.light_vertex);
    int gridShader = loadGLShader(GLES20.GL_FRAGMENT_SHADER, R.raw.flat_fragment);

    mGlProgram = GLES20.glCreateProgram();
    GLES20.glAttachShader(mGlProgram, vertexShader);
    GLES20.glAttachShader(mGlProgram, gridShader);
    GLES20.glLinkProgram(mGlProgram);

    GLES20.glEnable(GLES20.GL_DEPTH_TEST);

    Matrix.setIdentityM(mModelFloor, 0);
    Matrix.translateM(mModelFloor, 0, 0, -FLOOR_DEPTH, 0); // Floor appears below user

    checkGLError("onSurfaceCreated");
}

From source file:org.apache.orc.impl.RecordReaderUtils.java

/**
 * Read the list of ranges from the file.
 * @param file the file to read/*from   www.  j  ava  2  s.  c o  m*/
 * @param base the base of the stripe
 * @param range the disk ranges within the stripe to read
 * @return the bytes read for each disk range, which is the same length as
 *    ranges
 * @throws IOException
 */
static DiskRangeList readDiskRanges(FSDataInputStream file, HadoopShims.ZeroCopyReaderShim zcr, long base,
        DiskRangeList range, boolean doForceDirect) throws IOException {
    if (range == null)
        return null;
    DiskRangeList prev = range.prev;
    if (prev == null) {
        prev = new MutateHelper(range);
    }
    while (range != null) {
        if (range.hasData()) {
            range = range.next;
            continue;
        }
        int len = (int) (range.getEnd() - range.getOffset());
        long off = range.getOffset();
        if (zcr != null) {
            file.seek(base + off);
            boolean hasReplaced = false;
            while (len > 0) {
                ByteBuffer partial = zcr.readBuffer(len, false);
                BufferChunk bc = new BufferChunk(partial, off);
                if (!hasReplaced) {
                    range.replaceSelfWith(bc);
                    hasReplaced = true;
                } else {
                    range.insertAfter(bc);
                }
                range = bc;
                int read = partial.remaining();
                len -= read;
                off += read;
            }
        } else {
            // Don't use HDFS ByteBuffer API because it has no readFully, and is buggy and pointless.
            byte[] buffer = new byte[len];
            file.readFully((base + off), buffer, 0, buffer.length);
            ByteBuffer bb = null;
            if (doForceDirect) {
                bb = ByteBuffer.allocateDirect(len);
                bb.put(buffer);
                bb.position(0);
                bb.limit(len);
            } else {
                bb = ByteBuffer.wrap(buffer);
            }
            range = range.replaceSelfWith(new BufferChunk(bb, range.getOffset()));
        }
        range = range.next;
    }
    return prev.next;
}

From source file:com.ibm.crail.tools.CrailBenchmark.java

void readSequentialAsync(String filename, int size, int loop, int batch) throws Exception {
    System.out.println("readSequentialAsync, filename " + filename + ", size " + size + ", loop " + loop
            + ", batch " + batch);

    ConcurrentLinkedQueue<CrailBuffer> bufferQueue = new ConcurrentLinkedQueue<CrailBuffer>();
    for (int i = 0; i < batch; i++) {
        CrailBuffer buf = null;//from  w w  w.java  2  s  . c  o  m
        if (size == CrailConstants.BUFFER_SIZE) {
            buf = fs.allocateBuffer();
        } else if (size < CrailConstants.BUFFER_SIZE) {
            CrailBuffer _buf = fs.allocateBuffer();
            _buf.clear().limit(size);
            buf = _buf.slice();
        } else {
            buf = OffHeapBuffer.wrap(ByteBuffer.allocateDirect(size));
        }
        bufferQueue.add(buf);
    }

    //warmup
    warmUp(filename, warmup, bufferQueue);

    //benchmark
    System.out.println("starting benchmark...");
    double sumbytes = 0;
    double ops = 0;
    fs.getStatistics().reset();
    CrailFile file = fs.lookup(filename).get().asFile();
    CrailInputStream directStream = file.getDirectInputStream(file.getCapacity());
    HashMap<Integer, CrailBuffer> futureMap = new HashMap<Integer, CrailBuffer>();
    LinkedBlockingQueue<Future<CrailResult>> futureQueue = new LinkedBlockingQueue<Future<CrailResult>>();
    long start = System.currentTimeMillis();
    for (int i = 0; i < batch - 1 && ops < loop; i++) {
        CrailBuffer buf = bufferQueue.poll();
        buf.clear();
        Future<CrailResult> future = directStream.read(buf);
        futureQueue.add(future);
        futureMap.put(future.hashCode(), buf);
        ops = ops + 1.0;
    }
    while (ops < loop) {
        CrailBuffer buf = bufferQueue.poll();
        buf.clear();
        Future<CrailResult> future = directStream.read(buf);
        futureQueue.add(future);
        futureMap.put(future.hashCode(), buf);

        future = futureQueue.poll();
        CrailResult result = future.get();
        buf = futureMap.get(future.hashCode());
        bufferQueue.add(buf);

        sumbytes = sumbytes + result.getLen();
        ops = ops + 1.0;
    }
    while (!futureQueue.isEmpty()) {
        Future<CrailResult> future = futureQueue.poll();
        CrailResult result = future.get();
        futureMap.get(future.hashCode());
        sumbytes = sumbytes + result.getLen();
        ops = ops + 1.0;
    }
    long end = System.currentTimeMillis();
    double executionTime = ((double) (end - start)) / 1000.0;
    double throughput = 0.0;
    double latency = 0.0;
    double sumbits = sumbytes * 8.0;
    if (executionTime > 0) {
        throughput = sumbits / executionTime / 1000.0 / 1000.0;
        latency = 1000000.0 * executionTime / ops;
    }
    directStream.close();

    System.out.println("execution time " + executionTime);
    System.out.println("ops " + ops);
    System.out.println("sumbytes " + sumbytes);
    System.out.println("throughput " + throughput);
    System.out.println("latency " + latency);

    fs.getStatistics().print("close");
}