/** {@inheritDoc} */
public void encode(IoSession session, Object message, ProtocolEncoderOutput out) throws ProtocolCodecException {
// get the connection from the session
String sessionId = (String) session.getAttribute(RTMPConnection.RTMP_SESSION_ID);
log.trace("Session id: {}", sessionId);
RTMPConnection conn = (RTMPConnection) RTMPConnManager.getInstance().getConnectionBySessionId(sessionId);
if (conn != null) {
// look for and compare the connection local; set it from the session
if (!conn.equals((RTMPConnection) Red5.getConnectionLocal())) {
log.debug("Connection local ({}) didn't match io session ({})", (Red5.getConnectionLocal() != null ? Red5.getConnectionLocal().getSessionId() : "null"), sessionId);
Red5.setConnectionLocal(conn);
}
final Semaphore lock = conn.getEncoderLock();
try {
// acquire the decoder lock
log.trace("Encoder lock acquiring.. {}", conn.getSessionId());
lock.acquire();
log.trace("Encoder lock acquired {}", conn.getSessionId());
// get the buffer
final IoBuffer buf = message instanceof IoBuffer ? (IoBuffer) message : encoder.encode(message);
if (buf != null) {
int requestedWriteChunkSize = conn.getState().getWriteChunkSize();
log.trace("Requested chunk size: {} target chunk size: {}", requestedWriteChunkSize, targetChunkSize);
if (buf.remaining() <= targetChunkSize * 2) {
log.trace("Writing output data");
out.write(buf);
} else {
/*
LinkedList<IoBuffer> chunks = Chunker.chunk(buf, requestedWriteChunkSize, targetChunkSize);
log.trace("Writing output data in {} chunks", chunks.size());
for (IoBuffer chunk : chunks) {
out.write(chunk);
}
chunks.clear();
chunks = null;
*/
int sentChunks = Chunker.chunkAndWrite(out, buf, requestedWriteChunkSize, targetChunkSize);
log.trace("Wrote {} chunks", sentChunks);
}
} else {
log.trace("Response buffer was null after encoding");
}
// WriteFuture future = out.flush();
// if (future != null) {
// future.addListener(new IoFutureListener<WriteFuture>() {
// @Override
// public void operationComplete(WriteFuture future) {
// //log.debug("Buffer freed");
// buf.free();
// }
// });
// }
} catch (Exception ex) {
log.error("Exception during encode", ex);
} finally {
log.trace("Encoder lock releasing.. {}", conn.getSessionId());
lock.release();
}
} else {
log.debug("Connection is no longer available for encoding, may have been closed already");
}