List of usage examples for java.nio ByteBuffer order
Endianness order
To view the source code for java.nio ByteBuffer order.
Click Source Link
From source file:com.DorsetEggs.waver.communicatorService.java
public static byte[] toByteArray(KeyframePacket obj) throws IOException { ByteBuffer bytes = ByteBuffer.allocate(4); bytes.order(ByteOrder.LITTLE_ENDIAN); bytes.put(obj.servoToApplyTo);/*w w w . ja v a2 s. com*/ bytes.put(obj.degreesToReach); bytes.putShort(obj.timeToPosition); return bytes.array(); }
From source file:com.google.android.apps.body.LayersLoader.java
private static ShortBuffer decodeIndexBuffer(DrawGroup drawGroup, char[] data, int start, int length) { ByteBuffer byteBuffer = ByteBuffer.allocateDirect(length * 2); byteBuffer.order(ByteOrder.nativeOrder()); ShortBuffer indexData = byteBuffer.asShortBuffer(); int prev = 0; for (int i = 0; i < length;) { int limit = Math.min(length - i, BUFSIZE); int s = start + i; for (int j = 0; j < limit; ++j) { int word = data[s + j]; prev += (word >> 1) ^ (-(word & 1)); mBuffer[j] = (short) prev; }//from w ww. j a v a 2 s .c om i += limit; indexData.put(mBuffer, 0, limit); } indexData.rewind(); return indexData; }
From source file:org.onlab.util.ImmutableByteSequence.java
/** * Creates a new immutable byte sequence copying bytes from the given * ByteBuffer {@link ByteBuffer}. If the byte buffer order is not big-endian * bytes will be copied in reverse order. * * @param original a byte buffer/*from ww w. j ava 2 s . co m*/ * @return a new byte buffer object */ public static ImmutableByteSequence copyFrom(ByteBuffer original) { checkArgument(original != null && original.capacity() > 0, "Cannot copy from an empty or null byte buffer"); byte[] bytes = new byte[original.capacity()]; // copy bytes from original buffer original.rewind(); original.get(bytes); if (original.order() == ByteOrder.LITTLE_ENDIAN) { // FIXME: this can be improved, e.g. read bytes in reverse order from original reverse(bytes); } return new ImmutableByteSequence(ByteBuffer.wrap(bytes)); }
From source file:com.github.nlloyd.hornofmongo.util.BSONizer.java
@SuppressWarnings("deprecation") public static Object convertBSONtoJS(MongoScope mongoScope, Object bsonObject) { Object jsObject = null;//w w w . j a v a 2s . c o m if (bsonObject instanceof List<?>) { List<?> bsonList = (List<?>) bsonObject; Scriptable jsArray = (Scriptable) MongoRuntime.call(new NewInstanceAction(mongoScope, bsonList.size())); int index = 0; for (Object bsonEntry : bsonList) { ScriptableObject.putProperty(jsArray, index, convertBSONtoJS(mongoScope, bsonEntry)); index++; } jsObject = jsArray; } else if (bsonObject instanceof BSONObject) { Scriptable jsObj = (Scriptable) MongoRuntime.call(new NewInstanceAction(mongoScope)); BSONObject bsonObj = (BSONObject) bsonObject; for (String key : bsonObj.keySet()) { Object value = convertBSONtoJS(mongoScope, bsonObj.get(key)); MongoRuntime.call(new JSPopulatePropertyAction(jsObj, key, value)); } jsObject = jsObj; } else if (bsonObject instanceof Symbol) { jsObject = ((Symbol) bsonObject).getSymbol(); } else if (bsonObject instanceof Date) { jsObject = MongoRuntime.call( new NewInstanceAction(mongoScope, "Date", new Object[] { ((Date) bsonObject).getTime() })); } else if (bsonObject instanceof Pattern) { Pattern regex = (Pattern) bsonObject; String source = regex.pattern(); String options = Bytes.regexFlags(regex.flags()); jsObject = MongoRuntime .call(new NewInstanceAction(mongoScope, "RegExp", new Object[] { source, options })); } else if (bsonObject instanceof org.bson.types.ObjectId) { jsObject = MongoRuntime.call(new NewInstanceAction(mongoScope, "ObjectId")); ((ObjectId) jsObject).setRealObjectId((org.bson.types.ObjectId) bsonObject); } else if (bsonObject instanceof org.bson.types.MinKey) { jsObject = MongoRuntime.call(new NewInstanceAction(mongoScope, "MinKey")); } else if (bsonObject instanceof org.bson.types.MaxKey) { jsObject = MongoRuntime.call(new NewInstanceAction(mongoScope, "MaxKey")); } else if (bsonObject instanceof com.mongodb.DBRef) { com.mongodb.DBRef dbRef = (com.mongodb.DBRef) bsonObject; Object id = convertBSONtoJS(mongoScope, dbRef.getId()); jsObject = MongoRuntime.call( new NewInstanceAction(mongoScope, "DBRef", new Object[] { dbRef.getCollectionName(), id })); } else if (bsonObject instanceof BSONTimestamp) { BSONTimestamp bsonTstamp = (BSONTimestamp) bsonObject; jsObject = MongoRuntime.call(new NewInstanceAction(mongoScope, "Timestamp", new Object[] { bsonTstamp.getTime(), bsonTstamp.getInc() })); } else if (bsonObject instanceof Long) { jsObject = MongoRuntime.call(new NewInstanceAction(mongoScope, "NumberLong")); ((NumberLong) jsObject).setRealLong((Long) bsonObject); } else if (bsonObject instanceof Integer) { jsObject = Double.valueOf((Integer) bsonObject); } else if (bsonObject instanceof Code) { jsObject = ((Code) bsonObject).getCode(); } else if (bsonObject instanceof byte[]) { jsObject = MongoRuntime.call(new NewInstanceAction(mongoScope, "BinData")); ((BinData) jsObject).setValues(0, (byte[]) bsonObject); } else if (bsonObject instanceof Binary) { jsObject = MongoRuntime.call(new NewInstanceAction(mongoScope, "BinData")); ((BinData) jsObject).setValues(((Binary) bsonObject).getType(), ((Binary) bsonObject).getData()); } else if (bsonObject instanceof UUID) { jsObject = MongoRuntime.call(new NewInstanceAction(mongoScope, "BinData")); UUID uuid = (UUID) bsonObject; ByteBuffer dataBuffer = ByteBuffer.allocate(16); // mongodb wire protocol is little endian dataBuffer.order(ByteOrder.LITTLE_ENDIAN); dataBuffer.putLong(uuid.getMostSignificantBits()); dataBuffer.putLong(uuid.getLeastSignificantBits()); ((BinData) jsObject).setValues(BSON.B_UUID, dataBuffer.array()); } else { jsObject = bsonObject; } return jsObject; }
From source file:net.pms.util.OpenSubtitle.java
private static long computeHashForChunk(ByteBuffer buffer) { LongBuffer longBuffer = buffer.order(ByteOrder.LITTLE_ENDIAN).asLongBuffer(); long hash = 0; while (longBuffer.hasRemaining()) { hash += longBuffer.get();/*from ww w. ja va2s . c om*/ } return hash; }
From source file:com.google.android.apps.body.LayersLoader.java
private static ShortBuffer decodeVertexBuffer(DrawGroup drawGroup, char[] data, int start, int length) { ByteBuffer byteBuffer = ByteBuffer.allocateDirect(length * 2); byteBuffer.order(ByteOrder.nativeOrder()); ShortBuffer vertexData = byteBuffer.asShortBuffer(); short prev0 = 0, prev1 = 0, prev2 = 0, prev3 = 0; short prev4 = 0, prev5 = 0, prev6 = 0, prev7 = 0; for (int i = 0; i < length;) { int limit = Math.min(length - i, BUFSIZE); int s = start + i; for (int j = 0; j < limit;) { short word = (short) data[s + j]; prev0 += (word >> 1) ^ (-(word & 1)); mBuffer[j++] = (short) (prev0 - 8192); word = (short) data[s + j]; prev1 += (word >> 1) ^ (-(word & 1)); mBuffer[j++] = (short) (prev1 - 4096); word = (short) data[s + j]; prev2 += (word >> 1) ^ (-(word & 1)); mBuffer[j++] = (short) (prev2 - 8192); word = (short) data[s + j]; prev3 += (word >> 1) ^ (-(word & 1)); mBuffer[j++] = (short) ((prev3 - 256) << 7); word = (short) data[s + j]; prev4 += (word >> 1) ^ (-(word & 1)); mBuffer[j++] = (short) ((prev4 - 256) << 7); word = (short) data[s + j]; prev5 += (word >> 1) ^ (-(word & 1)); mBuffer[j++] = (short) ((prev5 - 256) << 7); word = (short) data[s + j]; prev6 += (word >> 1) ^ (-(word & 1)); mBuffer[j++] = (short) prev6; word = (short) data[s + j]; prev7 += (word >> 1) ^ (-(word & 1)); // The web version flips the tex images instead. mBuffer[j++] = (short) (512 - prev7); }//from w w w. j a v a 2 s .com i += limit; vertexData.put(mBuffer, 0, limit); } vertexData.rewind(); return vertexData; }
From source file:Main.java
public static ByteBuffer cloneByteBuffer(final ByteBuffer original) { // Create clone with same capacity as original. final ByteBuffer clone = (original.isDirect()) ? ByteBuffer.allocateDirect(original.capacity()) : ByteBuffer.allocate(original.capacity()); // Create a read-only copy of the original. // This allows reading from the original without modifying it. final ByteBuffer readOnlyCopy = original.asReadOnlyBuffer(); // Flip and read from the original. readOnlyCopy.flip();//ww w. jav a2 s . c om clone.put(readOnlyCopy); clone.position(original.position()); clone.limit(original.limit()); clone.order(original.order()); return clone; }
From source file:Main.java
private static byte[] encodeUrnUuid(String urn, int position, ByteBuffer bb) { String uuidString = urn.substring(position, urn.length()); UUID uuid;//www . j av a2s . c o m try { uuid = UUID.fromString(uuidString); } catch (IllegalArgumentException e) { //Log.w(TAG, "encodeUrnUuid invalid urn:uuid format - " + urn); return null; } // UUIDs are ordered as byte array, which means most significant first bb.order(ByteOrder.BIG_ENDIAN); bb.putLong(uuid.getMostSignificantBits()); bb.putLong(uuid.getLeastSignificantBits()); return byteBufferToArray(bb); }
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>/*ww w. j a v a2s.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.apache.htrace.impl.PackedBuffer.java
/** * Write the fixed-length request frame which starts packed RPC messages. *//* w ww. j a v a2 s. c o m*/ static void writeReqFrame(ByteBuffer bb, int methodId, long seq, int length) throws IOException { int oldPos = bb.position(); boolean success = false; try { bb.order(ByteOrder.LITTLE_ENDIAN); bb.putInt(HRPC_MAGIC); bb.putInt(methodId); bb.putLong(seq); bb.putInt(length); success = true; } finally { if (!success) { bb.position(oldPos); } } }