List of usage examples for java.nio.channels ReadableByteChannel read
public int read(ByteBuffer dst) throws IOException;
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 a 2s.co 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.alfresco.repo.transfer.HttpClientTransmitterImpl.java
private static void channelCopy(final ReadableByteChannel src, final WritableByteChannel dest) throws IOException { final ByteBuffer buffer = ByteBuffer.allocateDirect(2 * 1024); while (src.read(buffer) != -1) { // prepare the buffer to be drained buffer.flip();/* w ww .j av a 2s .c om*/ // write to the channel, may block 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()) { dest.write(buffer); } }
From source file:org.geoserver.rest.util.IOUtils.java
/** * Copies the content of the source channel onto the destination channel. * /* w ww .j a va 2 s. c o m*/ * @param bufferSize size of the temp buffer to use for this copy. * @param source the source {@link ReadableByteChannel}. * @param destination the destination {@link WritableByteChannel};. * @throws IOException in case something bad happens. */ public static void copyChannel(int bufferSize, ReadableByteChannel source, WritableByteChannel destination) throws IOException { inputNotNull(source, destination); if (!source.isOpen() || !destination.isOpen()) throw new IllegalStateException("Source and destination channels must be open."); final java.nio.ByteBuffer buffer = java.nio.ByteBuffer.allocateDirect(bufferSize); while (source.read(buffer) != -1) { //prepare the buffer for draining buffer.flip(); //write to destination while (buffer.hasRemaining()) destination.write(buffer); //clear buffer.clear(); } }
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}. * //from www . j a v a 2s . 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:com.sastix.cms.server.services.cache.CacheFileUtilsServiceImpl.java
@Override public byte[] downloadResource(URL url) throws IOException { //create buffer with capacity in bytes ByteArrayOutputStream baos = new ByteArrayOutputStream(); try {//from w w w . j av a2s. co m ByteBuffer bufIn = ByteBuffer.allocate(1024); ReadableByteChannel rbc = Channels.newChannel(url.openStream()); int bytesRead; while ((bytesRead = rbc.read(bufIn)) > 0) { baos.write(bufIn.array(), 0, bytesRead); bufIn.rewind(); } bufIn.clear(); return baos.toByteArray(); } finally { baos.close(); } }
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); }/*w w w. jav a 2 s . co 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:rascal.object.AbstractObjectFactory.java
public GitObject createObject(String name) throws IOException, CorruptedObjectException { ReadableByteChannel channel = getChannel(name); byte[] buffer = new byte[OBJECT_HEADER_BUFFER_LENGTH]; channel.read(ByteBuffer.wrap(buffer)); channel.close();//from w w w . j a v a 2s. c o m int headerSpaceIndex; int headerEndIndex; if ((headerSpaceIndex = ArrayUtils.indexOf(buffer, (byte) ' ')) == ArrayUtils.INDEX_NOT_FOUND || (headerEndIndex = ArrayUtils.indexOf(buffer, (byte) 0)) == ArrayUtils.INDEX_NOT_FOUND || headerSpaceIndex >= headerEndIndex) { throw new CorruptedObjectException(name, "Corrupted object header"); } try { return createObject(name, buffer, headerSpaceIndex, headerEndIndex); } catch (UnknownObjectTypeException e) { throw new CorruptedObjectException(name, e); } catch (NumberFormatException e) { throw new CorruptedObjectException(name, e); } }
From source file:com.web.searchlocal.flashpaper.thread.Covnert2SwfTask.java
/** * /* ww w . j a va2 s .c o m*/ */ public void excute() { String tmpOutFile = outFile.getPath().concat(File.separator) .concat(inFile.getName().replaceAll("[.]{1}.*$", ".swf")); List<String> commandArray = new ArrayList<String>(); commandArray.add(defaultCommand); commandArray.add(inFile.getPath()); commandArray.add("-o"); commandArray.add(tmpOutFile); ProcessBuilder pbObj = new ProcessBuilder(); pbObj.command(commandArray); pbObj.directory(outFile); pbObj.redirectErrorStream(true); try { Process proObj = pbObj.start(); final InputStream ins = proObj.getInputStream(); final ByteBuffer byteBuffer = ByteBuffer.allocate(1024); Thread th = new Thread() { public void run() { ReadableByteChannel rbcObj = Channels.newChannel(ins); try { while (rbcObj.read(byteBuffer) != -1) { byteBuffer.flip(); logger.info(java.nio.charset.Charset.defaultCharset().decode(byteBuffer)); byteBuffer.clear(); } } catch (IOException e) { logger.error(e); } } }; th.setDaemon(true); th.start(); try { proObj.waitFor(); logger.error("??." + tmpOutFile); } catch (InterruptedException e) { logger.error(e); } } catch (IOException e) { logger.error(e); } }
From source file:com.bennavetta.appsite.file.ResourceService.java
private void copy(ReadableByteChannel src, WritableByteChannel dest) throws IOException { ByteBuffer buffer = ByteBuffer.allocateDirect(bufferSize.get()); while (src.read(buffer) != -1 || buffer.position() != 0) { buffer.flip();/*w ww . j av a 2 s.c o m*/ dest.write(buffer); buffer.compact(); } }
From source file:com.github.matthesrieke.jprox.JProxViaParameterServlet.java
private void copyChannel(final ReadableByteChannel src, final WritableByteChannel dest) throws IOException { final ByteBuffer buffer = ByteBuffer.allocateDirect(16 * 1024); while (src.read(buffer) != -1) { buffer.flip();/*from w w w .ja v a 2s.c o m*/ dest.write(buffer); buffer.compact(); } buffer.flip(); while (buffer.hasRemaining()) { dest.write(buffer); } }