Example usage for java.nio ByteBuffer getShort

List of usage examples for java.nio ByteBuffer getShort

Introduction

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

Prototype

public abstract short getShort();

Source Link

Document

Returns the short at the current position and increases the position by 2.

Usage

From source file:net.jenet.Connect.java

@Override
public void fromBuffer(ByteBuffer buffer) {
    super.fromBuffer(buffer);
    outgoingPeerID = buffer.getShort();
    mtu = buffer.getShort();/*from  w ww  .  j a v  a 2 s .  c  o  m*/
    windowSize = buffer.getInt();
    channelCount = buffer.getInt();
    incomingBandwidth = buffer.getInt();
    outgoingBandwidth = buffer.getInt();
    packetThrottleInterval = buffer.getInt();
    packetThrottleAcceleration = buffer.getInt();
    packetThrottleDeceleration = buffer.getInt();
}

From source file:net.pms.util.AudioUtils.java

/**
 * Parses the old RealAudio 1.0 and 2.0 formats that's not supported by
 * neither {@link org.jaudiotagger} nor MediaInfo. Returns {@code false} if
 * {@code channel} isn't one of these formats or the parsing fails.
 * <p>/* w  w  w.  j a  v  a  2 s.  c  o  m*/
 * Primary references:
 * <ul>
 * <li><a href="https://wiki.multimedia.cx/index.php/RealMedia">RealAudio on
 * MultimediaWiki</a></li>
 * <li><a
 * href="https://github.com/FFmpeg/FFmpeg/blob/master/libavformat/rmdec.c"
 * >FFmpeg rmdec.c</a></li>
 * </ul>
 *
 * @param channel the {@link Channel} containing the input. Size will only
 *            be parsed if {@code channel} is a {@link FileChannel}
 *            instance.
 * @param media the {@link DLNAMediaInfo} instance to write the parsing
 *            results to.
 * @return {@code true} if the {@code channel} input is in RealAudio 1.0 or
 *         2.0 format and the parsing succeeds; false otherwise
 */
public static boolean parseRealAudio(ReadableByteChannel channel, DLNAMediaInfo media) {
    final byte[] magicBytes = { 0x2E, 0x72, 0x61, (byte) 0xFD };
    ByteBuffer buffer = ByteBuffer.allocate(8);
    buffer.order(ByteOrder.BIG_ENDIAN);
    DLNAMediaAudio audio = new DLNAMediaAudio();
    try {
        int count = channel.read(buffer);
        if (count < 4) {
            LOGGER.trace("Input is too short to be RealAudio");
            return false;
        }
        buffer.flip();
        byte[] signature = new byte[4];
        buffer.get(signature);
        if (!Arrays.equals(magicBytes, signature)) {
            if (LOGGER.isTraceEnabled()) {
                LOGGER.trace("Input signature ({}) mismatches RealAudio version 1.0 or 2.0",
                        new String(signature, StandardCharsets.US_ASCII));
            }
            return false;
        }
        media.setContainer(FormatConfiguration.RA);
        short version = buffer.getShort();
        int reportedHeaderSize = 0;
        int reportedDataSize = 0;
        if (version == 3) {
            audio.setCodecA(FormatConfiguration.REALAUDIO_14_4);
            audio.getAudioProperties().setNumberOfChannels(1);
            audio.getAudioProperties().setSampleFrequency(8000);
            short headerSize = buffer.getShort();

            buffer = ByteBuffer.allocate(headerSize);
            channel.read(buffer);
            buffer.flip();
            buffer.position(8);
            int bytesPerMinute = buffer.getShort() & 0xFFFF;
            reportedDataSize = buffer.getInt();
            byte b = buffer.get();
            if (b != 0) {
                byte[] title = new byte[b & 0xFF];
                buffer.get(title);
                String titleString = new String(title, StandardCharsets.US_ASCII);
                audio.setSongname(titleString);
                audio.setAudioTrackTitleFromMetadata(titleString);
            }
            b = buffer.get();
            if (b != 0) {
                byte[] artist = new byte[b & 0xFF];
                buffer.get(artist);
                audio.setArtist(new String(artist, StandardCharsets.US_ASCII));
            }
            audio.setBitRate(bytesPerMinute * 8 / 60);
            media.setBitrate(bytesPerMinute * 8 / 60);
        } else if (version == 4 || version == 5) {
            buffer = ByteBuffer.allocate(14);
            channel.read(buffer);
            buffer.flip();
            buffer.get(signature);
            if (!".ra4".equals(new String(signature, StandardCharsets.US_ASCII))) {
                LOGGER.debug("Invalid RealAudio 2.0 signature \"{}\"",
                        new String(signature, StandardCharsets.US_ASCII));
                return false;
            }
            reportedDataSize = buffer.getInt();
            buffer.getShort(); //skip version repeated
            reportedHeaderSize = buffer.getInt();

            buffer = ByteBuffer.allocate(reportedHeaderSize);
            channel.read(buffer);
            buffer.flip();
            buffer.getShort(); // skip codec flavor
            buffer.getInt(); // skip coded frame size
            buffer.getInt(); // skip unknown
            long bytesPerMinute = buffer.getInt() & 0xFFFFFFFFL;
            buffer.getInt(); // skip unknown
            buffer.getShort(); // skip sub packet
            buffer.getShort(); // skip frame size
            buffer.getShort(); // skip sub packet size
            buffer.getShort(); // skip unknown
            if (version == 5) {
                buffer.position(buffer.position() + 6); // skip unknown
            }
            short sampleRate = buffer.getShort();
            buffer.getShort(); // skip unknown
            short sampleSize = buffer.getShort();
            short nrChannels = buffer.getShort();
            byte[] fourCC;
            if (version == 4) {
                buffer.position(buffer.get() + buffer.position()); // skip interleaver id
                fourCC = new byte[buffer.get()];
                buffer.get(fourCC);
            } else {
                buffer.getFloat(); // skip deinterlace id
                fourCC = new byte[4];
                buffer.get(fourCC);
            }
            String fourCCString = new String(fourCC, StandardCharsets.US_ASCII).toLowerCase(Locale.ROOT);
            switch (fourCCString) {
            case "lpcJ":
                audio.setCodecA(FormatConfiguration.REALAUDIO_14_4);
                break;
            case "28_8":
                audio.setCodecA(FormatConfiguration.REALAUDIO_28_8);
                break;
            case "dnet":
                audio.setCodecA(FormatConfiguration.AC3);
                break;
            case "sipr":
                audio.setCodecA(FormatConfiguration.SIPRO);
                break;
            case "cook":
                audio.setCodecA(FormatConfiguration.COOK);
            case "atrc":
                audio.setCodecA(FormatConfiguration.ATRAC);
            case "ralf":
                audio.setCodecA(FormatConfiguration.RALF);
            case "raac":
                audio.setCodecA(FormatConfiguration.AAC_LC);
            case "racp":
                audio.setCodecA(FormatConfiguration.HE_AAC);
            default:
                LOGGER.debug("Unknown RealMedia codec FourCC \"{}\" - parsing failed", fourCCString);
                return false;
            }

            if (buffer.hasRemaining()) {
                parseRealAudioMetaData(buffer, audio, version);
            }

            audio.setBitRate((int) (bytesPerMinute * 8 / 60));
            media.setBitrate((int) (bytesPerMinute * 8 / 60));
            audio.setBitsperSample(sampleSize);
            audio.getAudioProperties().setNumberOfChannels(nrChannels);
            audio.getAudioProperties().setSampleFrequency(sampleRate);
        } else {
            LOGGER.error("Could not parse RealAudio format - unknown format version {}", version);
            return false;
        }

        media.getAudioTracksList().add(audio);
        long fileSize = 0;
        if (channel instanceof FileChannel) {
            fileSize = ((FileChannel) channel).size();
            media.setSize(fileSize);
        }
        // Duration is estimated based on bitrate and might not be accurate
        if (audio.getBitRate() > 0) {
            int dataSize;
            if (fileSize > 0 && reportedHeaderSize > 0) {
                int fullHeaderSize = reportedHeaderSize + (version == 3 ? 8 : 16);
                if (reportedDataSize > 0) {
                    dataSize = (int) Math.min(reportedDataSize, fileSize - fullHeaderSize);
                } else {
                    dataSize = (int) (fileSize - fullHeaderSize);
                }
            } else {
                dataSize = reportedDataSize;
            }
            media.setDuration((double) dataSize / audio.getBitRate() * 8);
        }

    } catch (IOException e) {
        LOGGER.debug("Error while trying to parse RealAudio version 1 or 2: {}", e.getMessage());
        LOGGER.trace("", e);
        return false;
    }
    if (PMS.getConfiguration() != null
            && !PMS.getConfiguration().getAudioThumbnailMethod().equals(CoverSupplier.NONE)
            && (StringUtils.isNotBlank(media.getFirstAudioTrack().getSongname())
                    || StringUtils.isNotBlank(media.getFirstAudioTrack().getArtist()))) {
        ID3v1Tag tag = new ID3v1Tag();
        if (StringUtils.isNotBlank(media.getFirstAudioTrack().getSongname())) {
            tag.setTitle(media.getFirstAudioTrack().getSongname());
        }
        if (StringUtils.isNotBlank(media.getFirstAudioTrack().getArtist())) {
            tag.setArtist(media.getFirstAudioTrack().getArtist());
        }
        try {
            media.setThumb(DLNAThumbnail.toThumbnail(CoverUtil.get().getThumbnail(tag), 640, 480, ScaleType.MAX,
                    ImageFormat.SOURCE, false));
        } catch (IOException e) {
            LOGGER.error("An error occurred while generating thumbnail for RealAudio source: [\"{}\", \"{}\"]",
                    tag.getFirstTitle(), tag.getFirstArtist());
        }
    }
    media.setThumbready(true);
    media.setMediaparsed(true);

    return true;
}

From source file:org.opendaylight.controller.protocol_plugin.openflow.vendorextension.v6extension.V6StatsReply.java

@Override
public void readFrom(ByteBuffer data) {
    short i;// ww w .  java 2  s.com
    this.length = data.getShort();
    if (length < MINIMUM_LENGTH)
        return; //TBD - Spurious Packet?
    this.tableId = data.get();
    data.get(); // pad
    this.durationSeconds = data.getInt();
    this.durationNanoseconds = data.getInt();
    this.priority = data.getShort();
    this.idleTimeout = data.getShort();
    this.hardTimeout = data.getShort();
    this.match_len = data.getShort();
    this.idleAge = data.getShort();
    this.hardAge = data.getShort();
    this.cookie = data.getLong();
    this.packetCount = data.getLong();
    this.byteCount = data.getLong();
    if (this.length == MINIMUM_LENGTH) {
        return; //TBD - can this happen??
    }
    if (this.match == null)
        this.match = new V6Match();
    ByteBuffer mbuf = ByteBuffer.allocate(match_len);
    for (i = 0; i < match_len; i++) {
        mbuf.put(data.get());
    }
    mbuf.rewind();
    this.match.readFrom(mbuf);
    if (this.actionFactory == null)
        throw new RuntimeException("OFActionFactory not set");
    /*
     * action list may be preceded by a padding of 0 to 7 bytes based upon this:
     */
    short pad_size = (short) (((match_len + 7) / 8) * 8 - match_len);
    for (i = 0; i < pad_size; i++)
        data.get();
    int action_len = this.length - MINIMUM_LENGTH - (match_len + pad_size);
    if (action_len > 0)
        this.actions = this.actionFactory.parseActions(data, action_len);
}

From source file:com.navercorp.pinpoint.collector.receiver.thrift.udp.SpanStreamUDPPacketHandlerFactory.java

private byte[] getComponentData(ByteBuffer buffer, HeaderTBaseDeserializer deserializer) {
    if (buffer.remaining() < 2) {
        logger.warn("Can't available {} fixed buffer.", 2);
        return null;
    }//from  w  ww . j a  v  a  2  s.com

    int componentSize = 0xffff & buffer.getShort();
    if (buffer.remaining() < componentSize) {
        logger.warn("Can't available {} fixed buffer.", buffer.remaining());
        return null;
    }

    byte[] componentData = new byte[componentSize];
    buffer.get(componentData);

    return componentData;
}

From source file:com.tc.simple.apn.factories.FeedbackFactory.java

public List<Feedback> createFeedback(InputStream in) {
    List<Feedback> list = new ArrayList<Feedback>();
    try {//from  w  w w .  j  a  v a 2s  .  c  o  m

        byte[] byteMe = IOUtils.toByteArray(in);

        int startRange = 0;

        int endRange = 38; //38 byte chunks per feedback item.

        while (startRange < byteMe.length) {

            //init the value object to hold the feedback data.
            Feedback feedback = new Feedback();

            //build the item based on range
            byte[] item = Arrays.copyOfRange(byteMe, startRange, endRange);//38 byte chunks.

            byte[] date = Arrays.copyOfRange(item, 0, 4);

            byte[] size = Arrays.copyOfRange(item, 4, 6);

            byte[] token = Arrays.copyOfRange(item, 6, item.length);

            ByteBuffer dateWrap = ByteBuffer.wrap(date);

            ByteBuffer javaSize = ByteBuffer.wrap(size);

            //set the date (returns number of seconds from unix epoch date)
            feedback.setDate(new Date(dateWrap.getInt() * 1000L));

            //get the size of the token (should always be 32)
            feedback.setSize(javaSize.getShort());

            //drop in our encoded token (will be used as our key for marking the user's token doc as failed)
            feedback.setToken(String.valueOf(Hex.encodeHex(token)));

            //add it to our collection
            list.add(feedback);

            //increment the start range
            startRange = startRange + 38;

            //increment the end range.
            endRange = endRange + 38;

        }

    } catch (Exception e) {
        logger.log(Level.SEVERE, null, e);

    }

    return list;

}

From source file:org.opendaylight.lispflowmapping.implementation.serializer.LocatorRecordSerializer.java

protected LocatorRecord deserialize(ByteBuffer buffer) {
    LocatorRecordBuilder builder = new LocatorRecordBuilder();
    builder.setPriority((short) ByteUtil.getUnsignedByte(buffer));
    builder.setWeight((short) ByteUtil.getUnsignedByte(buffer));
    builder.setMulticastPriority((short) ByteUtil.getUnsignedByte(buffer));
    builder.setMulticastWeight((short) ByteUtil.getUnsignedByte(buffer));
    byte flags = (byte) buffer.getShort();
    builder.setLocalLocator(ByteUtil.extractBit(flags, Flags.LOCAL_LOCATOR));
    builder.setRlocProbed(ByteUtil.extractBit(flags, Flags.RLOC_PROBED));
    builder.setRouted(ByteUtil.extractBit(flags, Flags.ROUTED));
    LispAFIAddress afiAddress = LispAddressSerializer.getInstance().deserialize(buffer);
    builder.setLispAddressContainer(LispAFIConvertor.toContainer(afiAddress));
    return builder.build();
}

From source file:org.opendaylight.lispflowmapping.lisp.serializer.LocatorRecordSerializer.java

protected LocatorRecord deserialize(ByteBuffer buffer) {
    LocatorRecordBuilder builder = new LocatorRecordBuilder();
    builder.setPriority((short) ByteUtil.getUnsignedByte(buffer));
    builder.setWeight((short) ByteUtil.getUnsignedByte(buffer));
    builder.setMulticastPriority((short) ByteUtil.getUnsignedByte(buffer));
    builder.setMulticastWeight((short) ByteUtil.getUnsignedByte(buffer));
    byte flags = (byte) buffer.getShort();
    builder.setLocalLocator(ByteUtil.extractBit(flags, Flags.LOCAL_LOCATOR));
    builder.setRlocProbed(ByteUtil.extractBit(flags, Flags.RLOC_PROBED));
    builder.setRouted(ByteUtil.extractBit(flags, Flags.ROUTED));
    Rloc rloc = LispAddressSerializer.getInstance().deserializeRloc(buffer);
    builder.setRloc(rloc);//from w  w w.j  av a  2  s  .  c o  m
    builder.setLocatorId(LispAddressStringifier.getString(rloc));
    return builder.build();
}

From source file:org.opendaylight.lispflowmapping.implementation.serializer.MapReplySerializer.java

public MapReply deserialize(ByteBuffer replyBuffer) {
    MapReplyBuilder builder = new MapReplyBuilder();
    byte typeAndFlags = replyBuffer.get();
    builder.setProbe(ByteUtil.extractBit(typeAndFlags, Flags.PROBE));
    builder.setEchoNonceEnabled(ByteUtil.extractBit(typeAndFlags, Flags.ECHO_NONCE_ENABLED));
    builder.setSecurityEnabled(ByteUtil.extractBit(typeAndFlags, Flags.SECURITY_ENABLED));
    replyBuffer.getShort();
    int recordCount = ByteUtil.getUnsignedByte(replyBuffer);
    builder.setNonce(replyBuffer.getLong());
    builder.setEidToLocatorRecord(new ArrayList<EidToLocatorRecord>());
    for (int i = 0; i < recordCount; i++) {
        builder.getEidToLocatorRecord().add(new EidToLocatorRecordBuilder(
                EidToLocatorRecordSerializer.getInstance().deserialize(replyBuffer)).build());
    }/*from   w w  w . j a va2 s. co  m*/

    return builder.build();
}

From source file:org.opendaylight.lispflowmapping.lisp.serializer.MapReplySerializer.java

public MapReply deserialize(ByteBuffer replyBuffer) {
    MapReplyBuilder builder = new MapReplyBuilder();
    byte typeAndFlags = replyBuffer.get();
    builder.setProbe(ByteUtil.extractBit(typeAndFlags, Flags.PROBE));
    builder.setEchoNonceEnabled(ByteUtil.extractBit(typeAndFlags, Flags.ECHO_NONCE_ENABLED));
    builder.setSecurityEnabled(ByteUtil.extractBit(typeAndFlags, Flags.SECURITY_ENABLED));
    replyBuffer.getShort();
    int recordCount = ByteUtil.getUnsignedByte(replyBuffer);
    builder.setNonce(replyBuffer.getLong());
    builder.setMappingRecordItem(new ArrayList<MappingRecordItem>());
    for (int i = 0; i < recordCount; i++) {
        builder.getMappingRecordItem().add(new MappingRecordItemBuilder()
                .setMappingRecord(MappingRecordSerializer.getInstance().deserialize(replyBuffer)).build());
    }/*from   ww w .  j  ava2  s  .  c  om*/

    return builder.build();
}

From source file:com.offbynull.portmapper.natpmp.NatPmpResponse.java

/**
 * Constructs a {@link NatPmpResponse} object by parsing a buffer.
 * @param buffer buffer containing NAT-PMP response data
 * @throws NullPointerException if any argument is {@code null}
 * @throws BufferUnderflowException if not enough data is available in {@code buffer}
 * @throws IllegalArgumentException if the version doesn't match the expected version (must always be {@code 0}), or if the op is
 * {@code < 128}, or if there's an unsuccessful/unrecognized result code
 *///  ww  w  .ja  v a 2  s. c  o m
NatPmpResponse(ByteBuffer buffer) {
    Validate.notNull(buffer);

    if (buffer.remaining() < 2) {
        throw new IllegalArgumentException("Bad packet size: " + buffer.remaining());
    }

    int version = buffer.get() & 0xFF;
    Validate.isTrue(version == 0, "Unknown version: %d", version);

    op = buffer.get() & 0xFF;
    Validate.isTrue(op >= 128, "Op must be >= 128: %d", op);

    int resultCodeNum = buffer.getShort() & 0xFFFF;
    NatPmpResultCode[] resultCodes = NatPmpResultCode.values();

    Validate.isTrue(resultCodeNum < resultCodes.length, "Unknown result code encountered: %d", resultCodeNum);
    Validate.isTrue(resultCodeNum == NatPmpResultCode.SUCCESS.ordinal(), "Unsuccessful result code: %s [%s]",
            resultCodes[resultCodeNum].toString(), resultCodes[resultCodeNum].getMessage());

    secondsSinceStartOfEpoch = buffer.getInt() & 0xFFFFFFFFL;
}