Java Code Examples for org.apache.mina.core.buffer.IoBuffer#free()
The following examples show how to use
org.apache.mina.core.buffer.IoBuffer#free() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ByteArray.java From red5-io with Apache License 2.0 | 6 votes |
/** * Compress contents using zlib. */ public void compress() { IoBuffer tmp = IoBuffer.allocate(0); tmp.setAutoExpand(true); byte[] tmpData = new byte[data.limit()]; data.position(0); data.get(tmpData); try (DeflaterOutputStream deflater = new DeflaterOutputStream(tmp.asOutputStream(), new Deflater(Deflater.BEST_COMPRESSION))) { deflater.write(tmpData); deflater.finish(); } catch (IOException e) { //docs state that free is optional tmp.free(); throw new RuntimeException("could not compress data", e); } data.free(); data = tmp; data.flip(); prepareIO(); }
Example 2
Source File: ByteArray.java From red5-io with Apache License 2.0 | 6 votes |
/** * Decompress contents using zlib. */ public void uncompress() { data.position(0); byte[] buffer = new byte[8192]; IoBuffer tmp = IoBuffer.allocate(0); tmp.setAutoExpand(true); try (InflaterInputStream inflater = new InflaterInputStream(data.asInputStream())) { while (inflater.available() > 0) { int decompressed = inflater.read(buffer); if (decompressed <= 0) { // Finished decompression break; } tmp.put(buffer, 0, decompressed); } } catch (IOException e) { tmp.free(); throw new RuntimeException("could not uncompress data", e); } data.free(); data = tmp; data.flip(); prepareIO(); }
Example 3
Source File: BufferedWriteFilter.java From neoscada with Eclipse Public License 1.0 | 5 votes |
/** * Internal method that actually frees the {@link IoBuffer} that contains * the buffered data that has not been flushed. * * @param session the session we operate on */ private void free(IoSession session) { IoBuffer buf = buffersMap.remove(session); if (buf != null) { buf.free(); } }
Example 4
Source File: StatusObjectService.java From red5-server-common with Apache License 2.0 | 5 votes |
/** * Cache status objects */ public void cacheStatusObjects() { cachedStatusObjects = new HashMap<String, byte[]>(); String statusCode; IoBuffer out = IoBuffer.allocate(256); out.setAutoExpand(true); for (String s : statusObjects.keySet()) { statusCode = s; StatusObject statusObject = statusObjects.get(statusCode); if (statusObject instanceof RuntimeStatusObject) { continue; } serializeStatusObject(out, statusObject); out.flip(); if (log.isTraceEnabled()) { log.trace(HexDump.formatHexDump(out.getHexDump())); } byte[] cachedBytes = new byte[out.limit()]; out.get(cachedBytes); out.clear(); cachedStatusObjects.put(statusCode, cachedBytes); } out.free(); out = null; }
Example 5
Source File: Aggregate.java From red5-server-common with Apache License 2.0 | 5 votes |
/** {@inheritDoc} */ @Override protected void releaseInternal() { if (data != null) { final IoBuffer localData = data; // null out the data first so we don't accidentally // return a valid reference first data = null; localData.clear(); localData.free(); } }
Example 6
Source File: VideoData.java From red5-server-common with Apache License 2.0 | 5 votes |
/** {@inheritDoc} */ @Override protected void releaseInternal() { if (data != null) { final IoBuffer localData = data; // null out the data first so we don't accidentally // return a valid reference first data = null; localData.clear(); localData.free(); } }
Example 7
Source File: Channel.java From red5-server-common with Apache License 2.0 | 5 votes |
/** * Discard an event routed to this channel. * * @param event */ @SuppressWarnings("unused") private void discard(IRTMPEvent event) { if (event instanceof IStreamData<?>) { log.debug("Discarding: {}", ((IStreamData<?>) event).toString()); IoBuffer data = ((IStreamData<?>) event).getData(); if (data != null) { log.trace("Freeing discarded event data"); data.free(); data = null; } } event.setHeader(null); }
Example 8
Source File: CacheableImpl.java From red5-io with Apache License 2.0 | 5 votes |
public CacheableImpl(Object obj) { IoBuffer tmp = IoBuffer.allocate(128).setAutoExpand(true); tmp.putObject(obj); tmp.flip(); bytes = new byte[tmp.remaining()]; tmp.get(bytes); cached = true; tmp.free(); tmp = null; }
Example 9
Source File: IOUtilsTest.java From red5-io with Apache License 2.0 | 5 votes |
@Test public void testWriteReverseInt() { final int ok = -771489792; // reversed int of 1234 int source = 1234; IoBuffer out = IoBuffer.allocate(4); IOUtils.writeReverseInt(out, source); out.flip(); int result = out.getInt(); System.out.printf("Results - source: %d result: %d\n", source, result); out.flip(); assertTrue(ok == result); // old method out.mark(); byte[] bytes = new byte[4]; IoBuffer rev = IoBuffer.allocate(4); rev.putInt(source); rev.flip(); bytes[3] = rev.get(); bytes[2] = rev.get(); bytes[1] = rev.get(); bytes[0] = rev.get(); out.put(bytes); rev.free(); rev = null; out.reset(); result = out.getInt(); System.out.printf("Result #1 - result: %d\n", result); out.flip(); assertTrue(ok == result); // optimized out.mark(); out.putInt((int) ((source & 0xFF) << 24 | ((source >> 8) & 0x00FF) << 16 | ((source >>> 16) & 0x000000FF) << 8 | ((source >>> 24) & 0x000000FF))); out.reset(); result = out.getInt(); System.out.printf("Result #2 - result: %d\n", result); out.flip(); out.free(); assertTrue(ok == result); }
Example 10
Source File: RTMPEIoFilter.java From red5-client with Apache License 2.0 | 5 votes |
@Override public void filterWrite(NextFilter nextFilter, IoSession session, WriteRequest request) throws Exception { RTMPMinaConnection conn = (RTMPMinaConnection) RTMPConnManager.getInstance().getConnectionBySessionId((String) session.getAttribute(RTMPConnection.RTMP_SESSION_ID)); // filter based on current connection state if (conn.getState().getState() == RTMP.STATE_CONNECTED && session.containsAttribute(RTMPConnection.RTMPE_CIPHER_OUT)) { Cipher cipher = (Cipher) session.getAttribute(RTMPConnection.RTMPE_CIPHER_OUT); IoBuffer message = (IoBuffer) request.getMessage(); if (!message.hasRemaining()) { if (log.isTraceEnabled()) { log.trace("Ignoring empty message"); } nextFilter.filterWrite(session, request); } else { if (log.isDebugEnabled()) { log.debug("Encrypting message: {}", message); } byte[] plain = new byte[message.remaining()]; message.get(plain); message.clear(); message.free(); // encrypt and write byte[] encrypted = cipher.update(plain); IoBuffer messageEncrypted = IoBuffer.wrap(encrypted); if (log.isDebugEnabled()) { log.debug("Encrypted message: {}", messageEncrypted); } nextFilter.filterWrite(session, new EncryptedWriteRequest(request, messageEncrypted)); } } else { log.trace("Non-encrypted message"); nextFilter.filterWrite(session, request); } }
Example 11
Source File: RTMPProtocolEncoder.java From red5-server-common with Apache License 2.0 | 4 votes |
/** * Encode packet. * * @param packet * RTMP packet * @return Encoded data */ public IoBuffer encodePacket(Packet packet) { IoBuffer out = null; Header header = packet.getHeader(); int channelId = header.getChannelId(); //log.trace("Channel id: {}", channelId); IRTMPEvent message = packet.getMessage(); if (message instanceof ChunkSize) { ChunkSize chunkSizeMsg = (ChunkSize) message; ((RTMPConnection) Red5.getConnectionLocal()).getState().setWriteChunkSize(chunkSizeMsg.getSize()); } // normally the message is expected not to be dropped if (!dropMessage(channelId, message)) { //log.trace("Header time: {} message timestamp: {}", header.getTimer(), message.getTimestamp()); IoBuffer data = encodeMessage(header, message); if (data != null) { RTMP rtmp = ((RTMPConnection) Red5.getConnectionLocal()).getState(); // set last write packet rtmp.setLastWritePacket(channelId, packet); // ensure we're at the beginning if (data.position() != 0) { data.flip(); } else { data.rewind(); } // length of the data to be chunked int dataLen = data.limit(); header.setSize(dataLen); //if (log.isTraceEnabled()) { //log.trace("Message: {}", data); //} // chunk size for writing int chunkSize = rtmp.getWriteChunkSize(); // number of chunks to write int numChunks = (int) Math.ceil(dataLen / (float) chunkSize); // get last header Header lastHeader = rtmp.getLastWriteHeader(channelId); if (log.isTraceEnabled()) { log.trace("Channel id: {} chunkSize: {}", channelId, chunkSize); } // attempt to properly guess the size of the buffer we'll need int bufSize = dataLen + 18 + (numChunks * 2); //log.trace("Allocated buffer size: {}", bufSize); out = IoBuffer.allocate(bufSize, false); out.setAutoExpand(true); do { // encode the header encodeHeader(header, lastHeader, out); // write a chunk byte[] buf = new byte[Math.min(chunkSize, data.remaining())]; data.get(buf); //log.trace("Buffer: {}", Hex.encodeHexString(buf)); out.put(buf); // move header over to last header lastHeader = header.clone(); } while (data.hasRemaining()); // collapse the time stamps on the last header after decode is complete lastHeader.setTimerBase(lastHeader.getTimer()); // clear the delta lastHeader.setTimerDelta(0); // set last write header rtmp.setLastWriteHeader(channelId, lastHeader); data.free(); out.flip(); data = null; } } message.release(); return out; }
Example 12
Source File: NioProcessor.java From jane with GNU Lesser General Public License v3.0 | 4 votes |
void flushNow(NioSession session) { if (session.isClosing()) return; try { WriteRequestQueue writeQueue = session.getWriteRequestQueue(); for (WriteRequest req; (req = writeQueue.peek()) != null; writeQueue.poll()) { Object message = req.writeRequestMessage(); if (message instanceof IoBuffer) { IoBuffer buf = (IoBuffer)message; if (buf.hasRemaining()) { session.getChannel().write(buf.buf()); if (buf.hasRemaining()) { session.setInterestedInWrite(true); return; } } req.writeRequestFuture().setWritten(); buf.free(); } else if (message instanceof FileRegion) { FileRegion region = (FileRegion)message; long len = region.getRemainingBytes(); if (len > 0) { region.update(region.getFileChannel().transferTo(region.getPosition(), len, session.getChannel())); if (region.getRemainingBytes() > 0) { session.setInterestedInWrite(true); return; } } req.writeRequestFuture().setWritten(); } else if (req == NioSession.CLOSE_REQUEST) { session.closeNow(); break; } else if (req == NioSession.SHUTDOWN_REQUEST) { session.getChannel().shutdownOutput(); break; } else throw new IllegalStateException("unknown message type for writting: " + message.getClass().getName() + ": " + message); } session.setInterestedInWrite(false); } catch (Exception e) { session.closeNow(); session.removeNow(e); } }
Example 13
Source File: SslFilter.java From jane with GNU Lesser General Public License v3.0 | 4 votes |
@Override public void messageReceived(NextFilter nextFilter, IoSession session, Object message) throws Exception { SslHandler sslHandler = getSslSessionHandler(session); synchronized (sslHandler) { if (!isSslStarted(session) && sslHandler.isInboundDone()) { // The SSL session must be established first before we can push data to the application. // Store the incoming data into a queue for a later processing sslHandler.scheduleMessageReceived(nextFilter, message); } else { IoBuffer buf = (IoBuffer)message; boolean bufUsed = false; try { if (sslHandler.isOutboundDone()) { sslHandler.destroy(); throw new SSLException("outbound done"); } // forward read encrypted data to SSL handler sslHandler.messageReceived(nextFilter, buf.buf()); // Handle data to be forwarded to application or written to net // LOGGER.debug("{}: Processing the SSL Data ", getSessionInfo(sslHandler.getSession())); // Flush any buffered write requests occurred before handshaking. if (sslHandler.isHandshakeComplete()) sslHandler.flushPreHandshakeEvents(); // Write encrypted data to be written (if any) sslHandler.writeNetBuffer(nextFilter, false); // handle app. data read (if any) IoBuffer readBuffer = sslHandler.fetchAppBuffer(); // forward read app data if (readBuffer.hasRemaining()) sslHandler.scheduleMessageReceived(nextFilter, readBuffer); if (sslHandler.isInboundDone()) { if (sslHandler.isOutboundDone()) sslHandler.destroy(); else initiateClosure(nextFilter, session, false); if (buf.hasRemaining()) { bufUsed = true; sslHandler.scheduleMessageReceived(nextFilter, buf); // forward the data received after closure } } } catch (SSLException se) { if (!sslHandler.isHandshakeComplete()) { SSLException newSe = new SSLHandshakeException("SSL handshake failed"); newSe.initCause(se); se = newSe; session.closeNow(); // close the session immediately, the handshake has failed } else sslHandler.release(); // free the SSL Handler buffers throw se; } finally { if (!bufUsed) buf.free(); } } } sslHandler.flushScheduledEvents(); }
Example 14
Source File: FLVWriter.java From red5-io with Apache License 2.0 | 4 votes |
private Map<String, ?> getMetaData(Path path, int maxTags) throws IOException { Map<String, ?> meta = null; // attempt to read the metadata SeekableByteChannel channel = Files.newByteChannel(path, StandardOpenOption.READ); long size = channel.size(); log.debug("Channel open: {} size: {} position: {}", channel.isOpen(), size, channel.position()); if (size > 0L) { // skip flv signature 4b, flags 1b, data offset 4b (9b), prev tag size (4b) channel.position(appendOffset); // flv tag header size 11b ByteBuffer dst = ByteBuffer.allocate(11); do { int read = channel.read(dst); if (read > 0) { dst.flip(); byte tagType = (byte) (dst.get() & 31); // 1 int bodySize = IOUtils.readUnsignedMediumInt(dst); // 3 int timestamp = IOUtils.readExtendedMediumInt(dst); // 4 int streamId = IOUtils.readUnsignedMediumInt(dst); // 3 log.debug("Data type: {} timestamp: {} stream id: {} body size: {}", new Object[] { tagType, timestamp, streamId, bodySize }); if (tagType == ITag.TYPE_METADATA) { ByteBuffer buf = ByteBuffer.allocate(bodySize); read = channel.read(buf); if (read > 0) { buf.flip(); // construct the meta IoBuffer ioBuf = IoBuffer.wrap(buf); Input input = new Input(ioBuf); String metaType = Deserializer.deserialize(input, String.class); log.debug("Metadata type: {}", metaType); meta = Deserializer.deserialize(input, Map.class); input = null; ioBuf.clear(); ioBuf.free(); if (meta.containsKey("duration")) { appendOffset = channel.position() + 4L; break; } } buf.compact(); } // advance beyond prev tag size channel.position(channel.position() + 4L); //int prevTagSize = dst.getInt(); // 4 //log.debug("Previous tag size: {} {}", prevTagSize, (bodySize - 11)); dst.compact(); } } while (--maxTags > 0); // read up-to "max" tags looking for duration channel.close(); } return meta; }
Example 15
Source File: Segment.java From red5-hls-plugin with Apache License 2.0 | 4 votes |
public ByteBuffer read() { ByteBuffer buf = null; if (buffer != null) { Integer readPos = readPositionHolder.get(); log.trace("Current buffer position: {}", readPos); int newPos = readPos + CHUNK_SIZE; int currentPosition = buffer.position(); if (newPos < currentPosition) { byte[] chunk = new byte[CHUNK_SIZE]; if (lock.tryLock()) { try { currentPosition = buffer.position(); IoBuffer slice = buffer.getSlice(readPos, CHUNK_SIZE); //log.trace("Slice - size: {} {}", slice.limit(), slice.getHexDump()); buffer.position(currentPosition); slice.get(chunk); slice.free(); } finally { lock.unlock(); } buf = ByteBuffer.wrap(chunk); } //set back to thread local readPositionHolder.set(newPos); } else { //set previous value back in th readPositionHolder.set(readPos); } } else { FileChannel readChannel = readChannelHolder.get(); try { //size the buffer for an mpegts chunk buf = ByteBuffer.allocate(CHUNK_SIZE); //read from the file readChannel.read(buf); //flip buf.flip(); } catch (IOException e) { e.printStackTrace(); } //set back to thread local readChannelHolder.set(readChannel); } return buf; }
Example 16
Source File: Segment.java From red5-hls-plugin with Apache License 2.0 | 4 votes |
public ByteBuffer read(ByteBuffer buf) { if (buffer != null) { Integer readPos = readPositionHolder.get(); log.trace("Current buffer read position: {}", readPos); int newPos = readPos + CHUNK_SIZE; int currentPosition = buffer.position(); if (newPos < currentPosition) { byte[] chunk = new byte[CHUNK_SIZE]; if (lock.tryLock()) { try { currentPosition = buffer.position(); IoBuffer slice = buffer.getSlice(readPos, CHUNK_SIZE); //log.trace("Slice - size: {} {}", slice.limit(), slice.getHexDump()); buffer.position(currentPosition); slice.get(chunk); slice.free(); } finally { lock.unlock(); } buf.put(chunk); buf.flip(); } //set back to thread local readPositionHolder.set(newPos); } else { //set previous value back in th readPositionHolder.set(readPos); //set the position to the end as an indicator buf.position(CHUNK_SIZE - 1); } } else { FileChannel readChannel = readChannelHolder.get(); try { //read from the file readChannel.read(buf); buf.flip(); } catch (IOException e) { e.printStackTrace(); } //set back to thread local readChannelHolder.set(readChannel); } return buf; }