Java Code Examples for org.red5.server.api.Red5#setConnectionLocal()

The following examples show how to use org.red5.server.api.Red5#setConnectionLocal() . 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: ReceivedMessageTask.java    From red5-server-common with Apache License 2.0 6 votes vote down vote up
public Packet call() throws Exception {
    //keep a ref for executor thread
    taskThread = Thread.currentThread();
    // set connection to thread local
    Red5.setConnectionLocal(conn);
    try {
        // pass message to the handler
        handler.messageReceived(conn, packet);
        // if we get this far, set done / completed flag
        packet.setProcessed(true);
    } finally {
        // clear thread local
        Red5.setConnectionLocal(null);
    }
    if (log.isDebugEnabled()) {
        log.debug("Processing message for {} is processed: {} packet #{}", sessionId, packet.isProcessed(), packetNumber);
    }
    return packet;
}
 
Example 2
Source File: RTMPClientProtocolDecoderTest.java    From red5-client with Apache License 2.0 6 votes vote down vote up
@Test
public void testDecodeBufferExTS() {
    //log.debug("\testDecodeBufferExTS");
    RTMPProtocolDecoder dec = new RTMPProtocolDecoder();
    RTMPConnection conn = new RTMPMinaConnection();
    Red5.setConnectionLocal(conn);
    RTMP rtmp = conn.getState();
    rtmp.setState(RTMP.STATE_CONNECTED);
    // lastHeader: Header [streamId=1, channelId=4, dataType=18, timerBase=0, timerDelta=0, size=309, extended=false]
    // get the local decode state
    RTMPDecodeState state = conn.getDecoderState();
    // meta and audio 4x chunks
    IoBuffer in = IoBuffer.wrap(IOUtils.hexStringToByteArray(
            "04000000000135120100000002000d40736574446174614672616d6502000a6f6e4d65746144617461080000000d00086475726174696f6e0040d518000000000000057769647468004064000000000000000668656967687400405e000000000000000d766964656f64617461726174650040686a000000000000096672616d657261746500403900000000c40000000c766964656f636f6465636964004000000000000000000d617564696f6461746172617465000000000000000000000f617564696f73616d706c65726174650040d5888000000000000f617564696f73616d706c6573697a65004030000000000000000673746572656f0100000c617564696f636f6465636964004000c40000000000000007656e636f64657202000d4c61766635362e31352e313032000866696c6573697a650000000000000000000000090400000000006908010000002afff340c400104002e62d4110009080200830107ea04cfa810710e0987f820ec130fc401897c1c0c70ff502008020eea04c1f0fe7fcb9fc10ff90d107c1f82008021feb07c1c04010041c20f89c1fff6b6edad93d99d8da6cd42a08e459095589d4b5fb9a4e679a1f4400001a00006a082afff342c41a19c91f225d89300055a47640c62cee7ccc85c08c42cadb6b56daebe65989f78c3ef3cfbd694ac0c34aa855ee0598a031f0a0686212d43631a4c59a926383c2d5201c5e9b7377"));
    Packet packet = null;
    do {
        packet = dec.decodePacket(conn, state, in);
    } while (packet == null);
    assertNotNull(packet);
    assertTrue(packet.getMessage() instanceof Notify);
    do {
        packet = dec.decodePacket(conn, state, in);
    } while (packet == null);
    assertNotNull(packet);
    assertTrue(packet.getMessage() instanceof AudioData);
}
 
Example 3
Source File: RTMPConnManager.java    From red5-client with Apache License 2.0 5 votes vote down vote up
/** {@inheritDoc} */
@Override
public RTMPConnection removeConnection(String sessionId) {
    log.debug("Removing connection with session id: {}", sessionId);
    if (log.isTraceEnabled()) {
        log.trace("Connections ({}) at pre-remove: {}", connMap.size(), connMap.values());
    }
    // remove from map
    RTMPConnection conn = connMap.remove(sessionId);
    if (conn != null) {
        log.trace("Connections: {}", conns.decrementAndGet());
        Red5.setConnectionLocal(null);
    }
    return conn;
}
 
Example 4
Source File: RTMPMinaCodecFactory.java    From red5-client with Apache License 2.0 5 votes vote down vote up
@Override
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) {
        Red5.setConnectionLocal(conn);
        final Semaphore lock = conn.getEncoderLock();
        try {
            // acquire the encoder lock
            lock.acquire();
            // get the buffer
            final IoBuffer buf = message instanceof IoBuffer ? (IoBuffer) message : getEncoder().encode(message);
            if (buf != null) {
                if (log.isTraceEnabled()) {
                    log.trace("Writing output data: {}", Hex.encodeHexString(buf.array()));
                }
                out.write(buf);
            } else {
                log.trace("Response buffer was null after encoding");
            }
        } catch (Exception ex) {
            log.error("Exception during encode", ex);
        } finally {
            lock.release();
            Red5.setConnectionLocal(null);
        }
    } else {
        log.debug("Connection is no longer available for encoding, may have been closed already");
    }
}
 
Example 5
Source File: RTMPMinaIoHandler.java    From red5-client with Apache License 2.0 5 votes vote down vote up
/** {@inheritDoc} */
@Override
public void messageReceived(IoSession session, Object message) throws Exception {
    log.debug("messageReceived");
    if (message instanceof Packet && message != null) {
        String sessionId = (String) session.getAttribute(RTMPConnection.RTMP_SESSION_ID);
        log.trace("Session id: {}", sessionId);
        RTMPMinaConnection conn = (RTMPMinaConnection) getConnectionManager(session).getConnectionBySessionId(sessionId);
        Red5.setConnectionLocal(conn);
        conn.handleMessageReceived((Packet) message);
        Red5.setConnectionLocal(null);
    } else {
        log.debug("Not packet type: {}", message);
    }
}
 
Example 6
Source File: BaseRTMPTConnection.java    From red5-client with Apache License 2.0 5 votes vote down vote up
/**
 * Send RTMP packet down the connection.
 *
 * @param packet
 *            the packet to send
 */
@Override
public void write(final Packet packet) {
    log.debug("write - state: {}", state);
    if (closing || state.getState() == RTMP.STATE_DISCONNECTED) {
        // Connection is being closed, don't send any new packets
        return;
    }
    IoBuffer data;
    try {
        Red5.setConnectionLocal(this);
        data = encoder.encode(packet);
    } catch (Exception e) {
        log.error("Could not encode message {}", packet, e);
        return;
    } finally {
        Red5.setConnectionLocal(null);
    }

    if (data != null) {
        // Mark packet as being written
        writingMessage(packet);
        //add to pending
        pendingMessages.add(new PendingData(data, packet));
    } else {
        log.info("Response buffer was null after encoding");
    }
}
 
Example 7
Source File: RTMPConnection.java    From red5-server-common with Apache License 2.0 4 votes vote down vote up
/** {@inheritDoc} */
@Override
public void close() {
    if (closing.compareAndSet(false, true)) {
        if (log.isDebugEnabled()) {
            log.debug("close: {}", sessionId);
        }
        stopWaitForHandshake();
        stopRoundTripMeasurement();
        // update our state
        if (state != null) {
            final byte s = getStateCode();
            switch (s) {
                case RTMP.STATE_DISCONNECTED:
                    if (log.isDebugEnabled()) {
                        log.debug("Already disconnected");
                    }
                    return;
                default:
                    if (log.isDebugEnabled()) {
                        log.debug("State: {}", RTMP.states[s]);
                    }
                    setStateCode(RTMP.STATE_DISCONNECTING);
            }
        }
        Red5.setConnectionLocal(this);
        IStreamService streamService = (IStreamService) ScopeUtils.getScopeService(scope, IStreamService.class, StreamService.class);
        if (streamService != null) {
            //in the end of call streamService.deleteStream we do streams.remove
            for (Iterator<IClientStream> it = streams.values().iterator(); it.hasNext();) {
                IClientStream stream = it.next();
                if (log.isDebugEnabled()) {
                    log.debug("Closing stream: {}", stream.getStreamId());
                }
                streamService.deleteStream(this, stream.getStreamId());
            }
        } else {
            if (log.isDebugEnabled()) {
                log.debug("Stream service was not found for scope: {}", (scope != null ? scope.getName() : "null or non-existant"));
            }
        }
        // close the base connection - disconnect scopes and unregister client
        super.close();
        // kill all the collections etc
        channels.clear();
        streams.clear();
        pendingCalls.clear();
        deferredResults.clear();
        pendingVideos.clear();
        streamBuffers.clear();
        if (log.isTraceEnabled()) {
            // dump memory stats
            log.trace("Memory at close - free: {}K total: {}K", Runtime.getRuntime().freeMemory() / 1024, Runtime.getRuntime().totalMemory() / 1024);
        }
    } else if (log.isDebugEnabled()) {
        log.debug("Already closing..");
    }
}
 
Example 8
Source File: RTMPMinaProtocolDecoder.java    From red5-server-common with Apache License 2.0 4 votes vote down vote up
/** {@inheritDoc} */
public void decode(IoSession session, IoBuffer in, ProtocolDecoderOutput out) throws ProtocolCodecException {
    // get the connection from the session
    String sessionId = (String) session.getAttribute(RTMPConnection.RTMP_SESSION_ID);
    log.trace("Session id: {}", sessionId);
    // connection verification routine
    @SuppressWarnings("unchecked")
    IConnectionManager<RTMPConnection> connManager = (IConnectionManager<RTMPConnection>) ((WeakReference<?>) session.getAttribute(RTMPConnection.RTMP_CONN_MANAGER)).get();
    RTMPConnection conn = (RTMPConnection) connManager.getConnectionBySessionId(sessionId);
    RTMPConnection connLocal = (RTMPConnection) Red5.getConnectionLocal();
    if (connLocal == null || !conn.getSessionId().equals(connLocal.getSessionId())) {
        if (log.isDebugEnabled() && connLocal != null) {
            log.debug("Connection local didn't match session");
        }
    }
    if (conn != null) {
        // set the connection to local if its referred to by this session
        Red5.setConnectionLocal(conn);
        // copy data range from incoming
        if (log.isTraceEnabled()) {
            log.trace("Incoming: in.position {}, in.limit {}, in.remaining {}", new Object[] { in.position(), in.limit(), in.remaining() });
        }
        byte[] arr = new byte[in.remaining()];
        in.get(arr);
        // create a buffer and store it on the session
        IoBuffer buf = (IoBuffer) session.getAttribute("buffer");
        if (buf == null) {
            buf = IoBuffer.allocate(arr.length);
            buf.setAutoExpand(true);
            session.setAttribute("buffer", buf);
        }
        // copy incoming into buffer
        buf.put(arr);
        // flip so we can read
        buf.flip();
        if (log.isTraceEnabled()) {
            //log.trace("Buffer before: {}", Hex.encodeHexString(arr));
            log.trace("Buffers info before: buf.position {}, buf.limit {}, buf.remaining {}", new Object[] { buf.position(), buf.limit(), buf.remaining() });
        }
        // get the connections decoder lock
        final Semaphore lock = conn.getDecoderLock();
        try {
            // acquire the decoder lock
            lock.acquire();
            // construct any objects from the decoded bugger
            List<?> objects = decoder.decodeBuffer(conn, buf);
            log.trace("Decoded: {}", objects);
            if (objects != null) {
                int writeCount = 0;
                for (Object object : objects) {
                    out.write(object);
                    writeCount++;
                }
                log.trace("Wrote {} objects", writeCount);
            }
        } catch (Exception e) {
            log.error("Error during decode", e);
        } finally {
            lock.release();
            // clear local
            Red5.setConnectionLocal(null);
        }
        if (log.isTraceEnabled()) {
            //log.trace("Buffer after: {}", Hex.encodeHexString(Arrays.copyOfRange(buf.array(), buf.position(), buf.limit())));
            log.trace("Buffers info after: buf.position {}, buf.limit {}, buf.remaining {}", new Object[] { buf.position(), buf.limit(), buf.remaining() });
        }
    } else {
        log.debug("Closing and skipping decode for unregistered connection: {}", sessionId);
        session.closeNow();
        log.debug("Session closing: {} reading: {} writing: {}", session.isClosing(), session.isReadSuspended(), session.isWriteSuspended());
    }
}
 
Example 9
Source File: RTMPMinaCodecFactory.java    From red5-client with Apache License 2.0 4 votes vote down vote up
@Override
public void decode(IoSession session, IoBuffer in, ProtocolDecoderOutput out) throws ProtocolCodecException {
    log.trace("decode buffer position: {}", in.position());
    // 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);
    Red5.setConnectionLocal(conn);
    byte[] arr = new byte[in.remaining()];
    in.get(arr);
    // create a buffer and store it on the session
    IoBuffer buf = (IoBuffer) session.getAttribute("buffer");
    if (buf == null) {
        buf = IoBuffer.allocate(arr.length);
        buf.setAutoExpand(true);
        session.setAttribute("buffer", buf);
    }
    // copy incoming into buffer
    buf.put(arr);
    // flip so we can read
    buf.flip();
    final Semaphore lock = conn.getDecoderLock();
    try {
        // acquire the decoder lock
        lock.acquire();
        // construct any objects from the decoded buffer
        List<?> objects = getDecoder().decodeBuffer(conn, buf);
        log.trace("Decoded: {}", objects);
        if (objects != null) {
            for (Object object : objects) {
                log.trace("Writing {} to decoder output: {}", object, out);
                out.write(object);
            }
        }
        log.trace("Input buffer position: {}", in.position());
    } catch (Exception e) {
        log.error("Error during decode", e);
    } finally {
        lock.release();
        Red5.setConnectionLocal(null);
    }
}