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

The following are Jave code examples for showing how to use rewind() 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: CustomWorldGen   File: VertexBuffer.java   View Source Code Vote up 6 votes
private void growBuffer(int p_181670_1_)
{
    if (MathHelper.roundUp(p_181670_1_, 4) / 4 > this.rawIntBuffer.remaining() || this.vertexCount * this.vertexFormat.getNextOffset() + p_181670_1_ > this.byteBuffer.capacity())
    {
        int i = this.byteBuffer.capacity();
        int j = i + MathHelper.roundUp(p_181670_1_, 2097152);
        LOGGER.debug("Needed to grow BufferBuilder buffer: Old size {} bytes, new size {} bytes.", new Object[] {Integer.valueOf(i), Integer.valueOf(j)});
        int k = this.rawIntBuffer.position();
        ByteBuffer bytebuffer = GLAllocation.createDirectByteBuffer(j);
        this.byteBuffer.position(0);
        bytebuffer.put(this.byteBuffer);
        bytebuffer.rewind();
        this.byteBuffer = bytebuffer;
        this.rawFloatBuffer = this.byteBuffer.asFloatBuffer().asReadOnlyBuffer();
        this.rawIntBuffer = this.byteBuffer.asIntBuffer();
        this.rawIntBuffer.position(k);
        this.rawShortBuffer = this.byteBuffer.asShortBuffer();
        this.rawShortBuffer.position(k << 1);
    }
}
 
Example 2
Project: kafka-0.11.0.0-src-with-comment   File: ByteBufferSerializer.java   View Source Code Vote up 6 votes
public byte[] serialize(String topic, ByteBuffer data) {
    if (data == null)
        return null;

    data.rewind();

    if (data.hasArray()) {
        byte[] arr = data.array();
        if (data.arrayOffset() == 0 && arr.length == data.remaining()) {
            return arr;
        }
    }

    byte[] ret = new byte[data.remaining()];
    data.get(ret, 0, ret.length);
    data.rewind();
    return ret;
}
 
Example 3
Project: MetadataEditor   File: OggVorbisTagWriter.java   View Source Code Vote up 6 votes
/**
 * Calculate checkSum over the Page
 *
 * @param page
 */
private void calculateChecksumOverPage(ByteBuffer page)
{           
    //CRC should be zero before calculating it
    page.putInt(OggPageHeader.FIELD_PAGE_CHECKSUM_POS, 0);

    //Compute CRC over the  page  //TODO shouldnt really use array();
    byte[] crc = OggCRCFactory.computeCRC(page.array());
    for (int i = 0; i < crc.length; i++)
    {
        page.put(OggPageHeader.FIELD_PAGE_CHECKSUM_POS + i, crc[i]);
    }

    //Rewind to start of Page
    page.rewind();
}
 
Example 4
Project: crypto-core   File: NativeSecp256k1.java   View Source Code Vote up 6 votes
/**
 * Verifies the given secp256k1 signature in native code. Calling when enabled == false is undefined (probably
 * library not loaded)
 *
 * @param data The data which was signed, must be exactly 32 bytes
 * @param signature The signature
 * @param pub The public key which did the signing
 */
public static boolean verify(byte[] data, byte[] signature, byte[] pub) throws AssertFailException {
    Preconditions.checkArgument(data.length == 32 && signature.length <= 520 && pub.length <= 520);

    ByteBuffer byteBuff = nativeECDSABuffer.get();
    if (byteBuff == null || byteBuff.capacity() < 520) {
        byteBuff = ByteBuffer.allocateDirect(520);
        byteBuff.order(ByteOrder.nativeOrder());
        nativeECDSABuffer.set(byteBuff);
    }
    byteBuff.rewind();
    byteBuff.put(data);
    byteBuff.put(signature);
    byteBuff.put(pub);

    r.lock();
    try {
        return secp256k1_ecdsa_verify(byteBuff, Secp256k1Context.getContext(), signature.length, pub.length) == 1;
    } finally {
        r.unlock();
    }
}
 
Example 5
Project: openjdk-jdk10   File: LargeFileAvailable.java   View Source Code Vote up 6 votes
private static void createLargeFile(long filesize,
                                    File file) throws Exception {
    // Recreate a large file as a sparse file if possible
    Files.delete(file.toPath());

    try (FileChannel fc =
         FileChannel.open(file.toPath(),
                          CREATE_NEW, WRITE, SPARSE)) {
        ByteBuffer bb = ByteBuffer.allocate(1).put((byte)1);
        bb.rewind();
        System.out.println("  Writing large file...");
        long t0 = System.nanoTime();
        int rc = fc.write(bb, filesize - 1);
        long t1 = System.nanoTime();
        System.out.printf("  Wrote large file in %d ns (%d ms) %n",
            t1 - t0, TimeUnit.NANOSECONDS.toMillis(t1 - t0));

        if (rc != 1) {
            throw new RuntimeException("Failed to write 1 byte"
                                       + " to the large file");
        }
    }
    return;
}
 
Example 6
Project: LearningOfThinkInJava   File: GetData.java   View Source Code Vote up 5 votes
public static void main(String[] args) {
    ByteBuffer bb=ByteBuffer.allocate(BSIZE);
    int i=0;
    while (i++<bb.limit()){
        if(bb.get()!=0){
            print("nonzero");
        }
        print("i="+i);
    }
    bb.rewind();

    bb.asCharBuffer().put("Howdy!");
    char c;
    while ((c=bb.getChar())!=0){
        printnb(c+"");
    }
    print();
    bb.rewind();
    bb.asShortBuffer().put((short)471142);
    print(bb.getShort());
    bb.rewind();

    bb.asIntBuffer().put(99471142);
    print(bb.getShort());
    bb.rewind();

    bb.asLongBuffer().put(99471142);
    print(bb.getLong());
    bb.rewind();

    bb.asFloatBuffer().put(99471142);
    print(bb.getFloat());
    bb.rewind();

    bb.asDoubleBuffer().put(99471142);
    print(bb.getDouble());
    bb.rewind();

}
 
Example 7
Project: BaseClient   File: WorldRenderer.java   View Source Code Vote up 5 votes
private void func_181670_b(int p_181670_1_)
{
    if (Config.isShaders())
    {
        p_181670_1_ *= 2;
    }

    if (p_181670_1_ > this.rawIntBuffer.remaining())
    {
        int i = this.byteBuffer.capacity();
        int j = i % 2097152;
        int k = j + (((this.rawIntBuffer.position() + p_181670_1_) * 4 - j) / 2097152 + 1) * 2097152;
        LogManager.getLogger().warn("Needed to grow BufferBuilder buffer: Old size " + i + " bytes, new size " + k + " bytes.");
        int l = this.rawIntBuffer.position();
        ByteBuffer bytebuffer = GLAllocation.createDirectByteBuffer(k);
        this.byteBuffer.position(0);
        bytebuffer.put(this.byteBuffer);
        bytebuffer.rewind();
        this.byteBuffer = bytebuffer;
        this.rawFloatBuffer = this.byteBuffer.asFloatBuffer();
        this.rawIntBuffer = this.byteBuffer.asIntBuffer();
        this.rawIntBuffer.position(l);
        this.field_181676_c = this.byteBuffer.asShortBuffer();
        this.field_181676_c.position(l << 1);

        if (this.quadSprites != null)
        {
            TextureAtlasSprite[] atextureatlassprite = this.quadSprites;
            int i1 = this.getBufferQuadSize();
            this.quadSprites = new TextureAtlasSprite[i1];
            System.arraycopy(atextureatlassprite, 0, this.quadSprites, 0, Math.min(atextureatlassprite.length, this.quadSprites.length));
            this.quadSpritesPrev = null;
        }
    }
}
 
Example 8
Project: ndbc   File: EncodingRegistryTest.java   View Source Code Vote up 5 votes
@Test
public void decode() {
  final IntegerValue value = new IntegerValue(213);
  final EncodingRegistry reg = new EncodingRegistry(Optional.empty());
  final ByteBuffer buf = ByteBuffer.allocate(1000);
  (new IntegerEncoding()).encode(Format.BINARY, value, new TestBufferWriter(buf));
  buf.rewind();
  final Value<?> decoded = reg.decode(Oid.INT4, Format.BINARY, new TestBufferReader(buf));
  assertEquals(value, decoded);
}
 
Example 9
Project: gnirehtet   File: IPv4Packet.java   View Source Code Vote up 5 votes
public IPv4Packet(ByteBuffer raw) {
    this.raw = raw;
    raw.rewind();

    ipv4Header = new IPv4Header(raw.duplicate());
    if (!ipv4Header.isSupported()) {
        Log.d(TAG, "Unsupported IPv4 headers");
        transportHeader = null;
        return;
    }
    transportHeader = createTransportHeader();
    raw.limit(ipv4Header.getTotalLength());
}
 
Example 10
Project: ark-java-smart-bridge-listener   File: HttpArkClient.java   View Source Code Vote up 5 votes
private byte[] getBytes(CreateArkTransactionRequest createArkTransactionRequest, String senderPublicKey) {
    ByteBuffer buffer = ByteBuffer.allocate(1000);
    buffer.order(ByteOrder.LITTLE_ENDIAN);

    buffer.put(createArkTransactionRequest.getType());
    buffer.putInt((int) createArkTransactionRequest.getTimestamp()); // todo: fix downcast
    buffer.put(BaseEncoding.base16().lowerCase().decode(senderPublicKey));

    if(createArkTransactionRequest.getRecipientId() != null){
        buffer.put(Base58.decodeChecked(createArkTransactionRequest.getRecipientId()));
    } else {
        buffer.put(new byte[21]);
    }

    if (createArkTransactionRequest.getVendorField() != null) {
        byte[] vbytes = createArkTransactionRequest.getVendorField().getBytes();
        if(vbytes.length < 65){
            buffer.put(vbytes);
            buffer.put(new byte[64-vbytes.length]);
        }
    } else {
        buffer.put(new byte[64]);
    }

    buffer.putLong(createArkTransactionRequest.getAmount());
    buffer.putLong(createArkTransactionRequest.getFee());

    byte[] outBuffer = new byte[buffer.position()];
    buffer.rewind();
    buffer.get(outBuffer);

    return outBuffer;
}
 
Example 11
Project: hadoop   File: YarnClientImpl.java   View Source Code Vote up 5 votes
private void addTimelineDelegationToken(
    ContainerLaunchContext clc) throws YarnException, IOException {
  Credentials credentials = new Credentials();
  DataInputByteBuffer dibb = new DataInputByteBuffer();
  ByteBuffer tokens = clc.getTokens();
  if (tokens != null) {
    dibb.reset(tokens);
    credentials.readTokenStorageStream(dibb);
    tokens.rewind();
  }
  // If the timeline delegation token is already in the CLC, no need to add
  // one more
  for (org.apache.hadoop.security.token.Token<? extends TokenIdentifier> token : credentials
      .getAllTokens()) {
    if (token.getKind().equals(TimelineDelegationTokenIdentifier.KIND_NAME)) {
      return;
    }
  }
  org.apache.hadoop.security.token.Token<TimelineDelegationTokenIdentifier>
      timelineDelegationToken = getTimelineDelegationToken();
  if (timelineDelegationToken == null) {
    return;
  }
  credentials.addToken(timelineService, timelineDelegationToken);
  if (LOG.isDebugEnabled()) {
    LOG.debug("Add timline delegation token into credentials: "
        + timelineDelegationToken);
  }
  DataOutputBuffer dob = new DataOutputBuffer();
  credentials.writeTokenStorageToStream(dob);
  tokens = ByteBuffer.wrap(dob.getData(), 0, dob.getLength());
  clc.setTokens(tokens);
}
 
Example 12
Project: openjdk-jdk10   File: ImageBufferCache.java   View Source Code Vote up 5 votes
static ByteBuffer getBuffer(long size) {
    if (size < 0 || Integer.MAX_VALUE < size) {
        throw new IndexOutOfBoundsException("size");
    }

    ByteBuffer result = null;

    if (size > LARGE_BUFFER) {
        result = allocateBuffer(size);
    } else {
        BufferReference[] cache = CACHE.get();

        // buffers are ordered by decreasing capacity
        // cache[MAX_CACHED_BUFFERS] is always null
        for (int i = MAX_CACHED_BUFFERS - 1; i >= 0; i--) {
            BufferReference reference = cache[i];

            if (reference != null) {
                ByteBuffer buffer = reference.get();

                if (buffer != null && size <= buffer.capacity()) {
                    cache[i] = null;
                    result = buffer;
                    result.rewind();
                    break;
                }
            }
        }

        if (result == null) {
            result = allocateBuffer(size);
        }
    }

    result.limit((int)size);

    return result;
}
 
Example 13
Project: MetadataEditor   File: VbriFrame.java   View Source Code Vote up 5 votes
/**
 * Read the VBRI Properties from the buffer
 */
private VbriFrame(ByteBuffer header)
{
    this.header=header;
    //Go to start of Buffer
    header.rewind();
    header.position(10);
    setAudioSize();
    setFrameCount();
}
 
Example 14
Project: creacoinj   File: NativeSecp256k1.java   View Source Code Vote up 5 votes
/**
 * libsecp256k1 Create an ECDSA signature.
 *
 * @param data Message hash, 32 bytes
 * @param key Secret key, 32 bytes
 * @return sig byte array of signature
 */
public static byte[] sign(byte[] data, byte[] sec) throws AssertFailException {
    Preconditions.checkArgument(data.length == 32 && sec.length <= 32);

    ByteBuffer byteBuff = nativeECDSABuffer.get();
    if (byteBuff == null || byteBuff.capacity() < 32 + 32) {
        byteBuff = ByteBuffer.allocateDirect(32 + 32);
        byteBuff.order(ByteOrder.nativeOrder());
        nativeECDSABuffer.set(byteBuff);
    }
    byteBuff.rewind();
    byteBuff.put(data);
    byteBuff.put(sec);

    byte[][] retByteArray;

    r.lock();
    try {
        retByteArray = secp256k1_ecdsa_sign(byteBuff, Secp256k1Context.getContext());
    } finally {
        r.unlock();
    }

    byte[] sigArr = retByteArray[0];
    int sigLen = new BigInteger(new byte[] { retByteArray[1][0] }).intValue();
    int retVal = new BigInteger(new byte[] { retByteArray[1][1] }).intValue();

    assertEquals(sigArr.length, sigLen, "Got bad signature length.");

    return retVal == 0 ? new byte[0] : sigArr;
}
 
Example 15
Project: kafka-0.11.0.0-src-with-comment   File: StreamThreadTest.java   View Source Code Vote up 5 votes
private ByteBuffer subscriptionUserData() {
    final UUID uuid = UUID.randomUUID();
    final ByteBuffer buf = ByteBuffer.allocate(4 + 16 + 4 + 4);
    // version
    buf.putInt(1);
    // encode client processId
    buf.putLong(uuid.getMostSignificantBits());
    buf.putLong(uuid.getLeastSignificantBits());
    // previously running tasks
    buf.putInt(0);
    // cached tasks
    buf.putInt(0);
    buf.rewind();
    return buf;
}
 
Example 16
Project: iTAP-controller   File: ICMP.java   View Source Code Vote up 4 votes
/**
 * Serializes the packet. Will compute and set the following fields if they
 * are set to specific values at the time serialize is called:
 *      -checksum : 0
 *      -length : 0
 */
@Override
public byte[] serialize() {
    short padding = 0;
    if (paddingMap.containsKey(this.icmpType))
        padding = paddingMap.get(this.icmpType);

    int length = 4 + padding;
    byte[] payloadData = null;
    if (payload != null) {
        payload.setParent(this);
        payloadData = payload.serialize();
        length += payloadData.length;
    }

    byte[] data = new byte[length];
    ByteBuffer bb = ByteBuffer.wrap(data);

    bb.put(this.icmpType);
    bb.put(this.icmpCode);
    bb.putShort(this.checksum);
    for (int i = 0; i < padding; i++)
        bb.put((byte) 0);

    if (payloadData != null)
        bb.put(payloadData);

    if (this.parent != null && this.parent instanceof IPv4)
        ((IPv4)this.parent).setProtocol(IpProtocol.ICMP);

    // compute checksum if needed
    if (this.checksum == 0) {
        bb.rewind();
        int accumulation = 0;

        for (int i = 0; i < length / 2; ++i) {
            accumulation += 0xffff & bb.getShort();
        }
        // pad to an even number of shorts
        if (length % 2 > 0) {
            accumulation += (bb.get() & 0xff) << 8;
        }

        accumulation = ((accumulation >> 16) & 0xffff)
                + (accumulation & 0xffff);
        this.checksum = (short) (~accumulation & 0xffff);
        bb.putShort(2, this.checksum);
    }
    return data;
}
 
Example 17
Project: Cybernet-VPN   File: LogItem.java   View Source Code Vote up 4 votes
public byte[] getMarschaledBytes() throws UnsupportedEncodingException, BufferOverflowException {
    ByteBuffer bb = ByteBuffer.allocate(16384);
    bb.put((byte) 0x0);               //version
    bb.putLong(logtime);              //8
    bb.putInt(mVerbosityLevel);      //4
    bb.putInt(mLevel.getInt());
    bb.putInt(mRessourceId);
    if (mMessage == null || mMessage.length() == 0) {
        bb.putInt(0);
    } else {
        marschalString(mMessage, bb);
    }
    if (mArgs == null || mArgs.length == 0) {
        bb.putInt(0);
    } else {
        bb.putInt(mArgs.length);
        for (Object o : mArgs) {
            if (o instanceof String) {
                bb.putChar('s');
                marschalString((String) o, bb);
            } else if (o instanceof Integer) {
                bb.putChar('i');
                bb.putInt((Integer) o);
            } else if (o instanceof Float) {
                bb.putChar('f');
                bb.putFloat((Float) o);
            } else if (o instanceof Double) {
                bb.putChar('d');
                bb.putDouble((Double) o);
            } else if (o instanceof Long) {
                bb.putChar('l');
                bb.putLong((Long) o);
            } else if (o == null) {
                bb.putChar('0');
            } else {
                VpnStatus.logDebug("Unknown object for LogItem marschaling " + o);
                bb.putChar('s');
                marschalString(o.toString(), bb);
            }
        }
    }
    int pos = bb.position();
    bb.rewind();
    return Arrays.copyOf(bb.array(), pos);
}
 
Example 18
Project: jaer   File: SimpleDepthCameraViewer.java   View Source Code Vote up 4 votes
@Override
public synchronized void onFrameReady(VideoStream stream) {
    if (mLastFrame != null) {
        mLastFrame.release();
        mLastFrame = null;
    }

    mLastFrame = mVideoStream.readFrame();
    ByteBuffer frameData = mLastFrame.getData().order(ByteOrder.LITTLE_ENDIAN);

    // make sure we have enough room
    if (mImagePixels == null || mImagePixels.length < mLastFrame.getWidth() * mLastFrame.getHeight()) {
        mImagePixels = new int[mLastFrame.getWidth() * mLastFrame.getHeight()];
    }

    switch (mLastFrame.getVideoMode().getPixelFormat()) {
        case DEPTH_1_MM:
        case DEPTH_100_UM:
        case SHIFT_9_2:
        case SHIFT_9_3:
            calcHist(frameData);
            frameData.rewind();
            int pos = 0;
            while (frameData.remaining() > 0) {
                int depth = (int) frameData.getShort() & 0xFFFF;
                short pixel = (short) mHistogram[depth];
                mImagePixels[pos] = 0xFF000000 | (pixel << 16) | (pixel << 8);
                pos++;
            }
            break;
        case RGB888:
            pos = 0;
            while (frameData.remaining() > 0) {
                int red = (int) frameData.get() & 0xFF;
                int green = (int) frameData.get() & 0xFF;
                int blue = (int) frameData.get() & 0xFF;
                mImagePixels[pos] = 0xFF000000 | (red << 16) | (green << 8) | blue;
                pos++;
            }
            break;
        default:
            // don't know how to draw
            mLastFrame.release();
            mLastFrame = null;
    }

    repaint();
}
 
Example 19
Project: MetadataEditor   File: Mp4StcoBox.java   View Source Code Vote up 4 votes
public static Mp4StcoBox getStco(RandomAccessFile raf) throws IOException, CannotReadException
{
    FileChannel fc = raf.getChannel();
    Mp4BoxHeader moovHeader = Mp4BoxHeader.seekWithinLevel(fc, Mp4AtomIdentifier.MOOV.getFieldName());
    if (moovHeader == null)
    {
        throw new CannotReadException("This file does not appear to be an audio file");
    }
    ByteBuffer moovBuffer = ByteBuffer.allocate(moovHeader.getLength() - Mp4BoxHeader.HEADER_LENGTH);
    fc.read(moovBuffer);
    moovBuffer.rewind();

    //Level 2-Searching for "mvhd" somewhere within "moov", we make a slice after finding header
    //so all getFields() methods will be relative to mvdh positions
    Mp4BoxHeader boxHeader = Mp4BoxHeader.seekWithinLevel(moovBuffer, Mp4AtomIdentifier.MVHD.getFieldName());
    if (boxHeader == null)
    {
        throw new CannotReadException("This file does not appear to be an audio file");
    }
    ByteBuffer mvhdBuffer = moovBuffer.slice();
    Mp4MvhdBox mvhd = new Mp4MvhdBox(boxHeader, mvhdBuffer);
    mvhdBuffer.position(mvhdBuffer.position() + boxHeader.getDataLength());

    //Level 2-Searching for "trak" within "moov"
    boxHeader = Mp4BoxHeader.seekWithinLevel(mvhdBuffer, Mp4AtomIdentifier.TRAK.getFieldName());
    int endOfFirstTrackInBuffer = mvhdBuffer.position() + boxHeader.getDataLength();

    if (boxHeader == null)
    {
        throw new CannotReadException("This file does not appear to be an audio file");
    }
    //Level 3-Searching for "mdia" within "trak"
    boxHeader = Mp4BoxHeader.seekWithinLevel(mvhdBuffer, Mp4AtomIdentifier.MDIA.getFieldName());
    if (boxHeader == null)
    {
        throw new CannotReadException("This file does not appear to be an audio file");
    }

    //Level 4-Searching for "mdhd" within "mdia"
    boxHeader = Mp4BoxHeader.seekWithinLevel(mvhdBuffer, Mp4AtomIdentifier.MDHD.getFieldName());
    if (boxHeader == null)
    {
        throw new CannotReadException("This file does not appear to be an audio file");
    }

    //Level 4-Searching for "minf" within "mdia"
    mvhdBuffer.position(mvhdBuffer.position() + boxHeader.getDataLength());
    boxHeader = Mp4BoxHeader.seekWithinLevel(mvhdBuffer, Mp4AtomIdentifier.MINF.getFieldName());
    if (boxHeader == null)
    {
        throw new CannotReadException("This file does not appear to be an audio file");
    }

    //Level 5-Searching for "smhd" within "minf"
    //Only an audio track would have a smhd frame
    boxHeader = Mp4BoxHeader.seekWithinLevel(mvhdBuffer, Mp4AtomIdentifier.SMHD.getFieldName());
    if (boxHeader == null)
    {
        throw new CannotReadException("This file does not appear to be an audio file");
    }
    mvhdBuffer.position(mvhdBuffer.position() + boxHeader.getDataLength());

    //Level 5-Searching for "stbl within "minf"
    boxHeader = Mp4BoxHeader.seekWithinLevel(mvhdBuffer, Mp4AtomIdentifier.STBL.getFieldName());
    if (boxHeader == null)
    {
        throw new CannotReadException("This file does not appear to be an audio file");
    }

    //Level 6-Searching for "stco within "stbl"
    boxHeader = Mp4BoxHeader.seekWithinLevel(mvhdBuffer, Mp4AtomIdentifier.STCO.getFieldName());
    if (boxHeader == null)
    {
        throw new CannotReadException("This file does not appear to be an audio file");
    }
    Mp4StcoBox stco = new Mp4StcoBox(boxHeader, mvhdBuffer);
    return stco;
}
 
Example 20
Project: imageio-jnr   File: TurboJpeg.java   View Source Code Vote up 4 votes
/** Encode an image to JPEG **/
public ByteBuffer encode(Raster img, int quality) throws TurboJpegException {
  Pointer codec = null;
  Pointer bufPtr = null;
  try {
    TJPF pixelFmt;
    switch (img.getNumBands()) {
      case 4:
        pixelFmt = TJPF.TJPF_BGRX; // 4BYTE_BGRA
        break;
      case 3:
        pixelFmt = TJPF.TJPF_BGR;  // 3BYTE_BGR
        break;
      case 1:
        pixelFmt = TJPF.TJPF_GRAY; // 1BYTE_GRAY
        break;
      default:
        throw new IllegalArgumentException("Illegal sample format");
    }
    TJSAMP sampling = pixelFmt == TJPF.TJPF_GRAY ? TJSAMP.TJSAMP_GRAY : TJSAMP.TJSAMP_444;
    codec = lib.tjInitCompress();

    // Allocate JPEG target buffer
    int bufSize = (int) lib.tjBufSize(img.getWidth(), img.getHeight(), sampling);
    bufPtr = lib.tjAlloc(bufSize);
    NativeLongByReference lenPtr = new NativeLongByReference(bufSize);

    // Wrap source image data buffer with ByteBuffer to pass it over the ABI
    ByteBuffer inBuf = ByteBuffer.wrap(((DataBufferByte) img.getDataBuffer()).getData())
        .order(runtime.byteOrder());
    int rv = lib.tjCompress2(
        codec, inBuf, img.getWidth(), 0, img.getHeight(),  pixelFmt,
        new PointerByReference(bufPtr), lenPtr, sampling, quality, 0);
    if (rv != 0) {
      LOG.error("Could not compress image (dimensions: {}x{}, format: {}, sampling: {}, quality: {}",
                img.getWidth(), img.getHeight(), pixelFmt, sampling, quality);
      throw new TurboJpegException(lib.tjGetErrorStr());
    }
    ByteBuffer outBuf = ByteBuffer.allocate(lenPtr.getValue().intValue()).order(runtime.byteOrder());
    bufPtr.get(0, outBuf.array(), 0, lenPtr.getValue().intValue());
    outBuf.rewind();
    return outBuf;
  } finally {
    if (codec != null && codec.address() != 0) lib.tjDestroy(codec);
    if (bufPtr != null && bufPtr.address() != 0) lib.tjFree(bufPtr);
  }
}