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

The following examples show how to use org.red5.server.api.Red5#getConnectionLocal() . 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: ServerClientDetection.java    From red5-server-common with Apache License 2.0 6 votes vote down vote up
private void callBWCheck(Object payload) {
    if (log.isTraceEnabled()) {
        log.trace("callBWCheck: {}", payload);
    } else {
        log.debug("callBWCheck");
    }
    IConnection conn = Red5.getConnectionLocal();
    Map<String, Object> statsValues = new HashMap<String, Object>();
    statsValues.put("count", packetsReceived.get());
    statsValues.put("sent", packetsSent.get());
    statsValues.put("timePassed", timePassed);
    statsValues.put("latency", latency);
    statsValues.put("cumLatency", cumLatency);
    statsValues.put("payload", payload);
    if (conn instanceof IServiceCapableConnection) {
        log.debug("Invoking onBWCheck on the client");
        // increment sent counter
        packetsSent.incrementAndGet();
        // invoke on the client
        ((IServiceCapableConnection) conn).invoke("onBWCheck", new Object[] { statsValues }, this);
    }
}
 
Example 2
Source File: StreamService.java    From red5-server-common with Apache License 2.0 6 votes vote down vote up
/** {@inheritDoc} */
public Number createStream(Number streamId) {
    IConnection conn = Red5.getConnectionLocal();
    log.trace("createStream stream id: {} connection: {}", streamId, conn.getSessionId());
    if (conn instanceof IStreamCapableConnection) {
        try {
            if (streamId.intValue() > 0) {
                streamId = ((IStreamCapableConnection) conn).reserveStreamId(streamId);
            } else {
                streamId = ((IStreamCapableConnection) conn).reserveStreamId();
            }
            if (log.isTraceEnabled()) {
                log.trace("Stream id: {} created for {}", streamId, conn.getSessionId());
            }
            return streamId;
        } catch (IndexOutOfBoundsException e) {
            log.error("Unable to create stream", e);
        }
    }
    return -1;
}
 
Example 3
Source File: StreamService.java    From red5-server-common with Apache License 2.0 6 votes vote down vote up
/** {@inheritDoc} */
public void initStream(Number streamId) {
    IConnection conn = Red5.getConnectionLocal();
    log.info("initStream stream id: {} current stream id: {} connection: {}", streamId, conn.getStreamId(), conn.getSessionId());
    if (conn instanceof IStreamCapableConnection) {
        ((IStreamCapableConnection) conn).reserveStreamId(streamId);
        IClientStream stream = ((IStreamCapableConnection) conn).getStreamById(streamId);
        if (stream != null) {
            if (stream instanceof IClientBroadcastStream) {
                IClientBroadcastStream bs = (IClientBroadcastStream) stream;
                IBroadcastScope bsScope = getBroadcastScope(conn.getScope(), bs.getPublishedName());
                if (bsScope != null && conn instanceof BaseConnection) {
                    ((BaseConnection) conn).unregisterBasicScope(bsScope);
                }
            }
            stream.close();
        }
        ((IStreamCapableConnection) conn).deleteStreamById(streamId);
    } else {
        log.warn("ERROR in initStream, connection is not stream capable");
    }
}
 
Example 4
Source File: MultiThreadedApplicationAdapter.java    From red5-server-common with Apache License 2.0 5 votes vote down vote up
public void streamPlayItemStop(ISubscriberStream stream, IPlayItem item) {
    // since there is a fair amount of processing below we will check log
    // level prior to proceeding
    if (log.isInfoEnabled()) {
        // log w3c connect event
        String remoteAddress = "";
        long readBytes = -1;
        long writtenBytes = -1;
        IConnection conn = Red5.getConnectionLocal();
        if (conn != null) {
            remoteAddress = conn.getRemoteAddress();
            readBytes = conn.getReadBytes();
            writtenBytes = conn.getWrittenBytes();
        }
        long playDuration = -1;
        if (stream instanceof PlaylistSubscriberStream) {
            // converted to seconds
            playDuration = (System.currentTimeMillis() - ((PlaylistSubscriberStream) stream).getCreationTime()) / 1000;
        }
        long playItemSize = -1;
        String playItemName = "";
        if (item != null) {
            playItemName = item.getName();
            //get file size in bytes if available
            IProviderService providerService = (IProviderService) scope.getContext().getBean(IProviderService.BEAN_NAME);
            if (providerService != null) {
                File file = providerService.getVODProviderFile(scope, playItemName);
                if (file != null) {
                    playItemSize = file.length();
                } else {
                    log.debug("File was null, this is ok for live streams");
                }
            } else {
                log.debug("ProviderService was null");
            }
        }
        log.info("W3C x-category:stream x-event:stop c-ip:{} cs-bytes:{} sc-bytes:{} x-sname:{} x-file-length:{} x-file-size:{} x-name:{}", new Object[] { remoteAddress, readBytes, writtenBytes, stream.getName(), playDuration, playItemSize, playItemName });
    }
}
 
Example 5
Source File: StreamService.java    From red5-server-common with Apache License 2.0 5 votes vote down vote up
/** {@inheritDoc} */
public void receiveAudio(boolean receive) {
    IConnection conn = Red5.getConnectionLocal();
    if (conn instanceof IStreamCapableConnection) {
        IStreamCapableConnection streamConn = (IStreamCapableConnection) conn;
        Number streamId = conn.getStreamId();
        IClientStream stream = streamConn.getStreamById(streamId);
        if (stream != null && stream instanceof ISubscriberStream) {
            ISubscriberStream subscriberStream = (ISubscriberStream) stream;
            subscriberStream.receiveAudio(receive);
        }
    }
}
 
Example 6
Source File: ClientServerDetection.java    From red5-examples with Apache License 2.0 5 votes vote down vote up
private IStreamCapableConnection getStats() {
	IConnection conn = Red5.getConnectionLocal();
	if (conn instanceof IStreamCapableConnection) {
		return (IStreamCapableConnection) conn;
	}
	return null;
}
 
Example 7
Source File: ServerClientDetection.java    From red5-examples with Apache License 2.0 5 votes vote down vote up
private void callBWDone()
{
	IConnection conn = Red5.getConnectionLocal();
	
	Map<String, Object> statsValues = new HashMap<String, Object>();
	statsValues.put("kbitDown", this.kbitDown);
	statsValues.put("deltaDown", this.deltaDown);
	statsValues.put("deltaTime", this.deltaTime);
	statsValues.put("latency", this.latency);
	
	if (conn instanceof IServiceCapableConnection) {
		((IServiceCapableConnection) conn).invoke("onBWDone", new Object[]{statsValues});
	}
}
 
Example 8
Source File: ServiceUtils.java    From red5-server-common with Apache License 2.0 5 votes vote down vote up
/**
 * Notify a method on all connections to the current scope.
 * 
 * @param method
 *            name of the method to notify
 * @param params
 *            parameters to pass to the method
 */
public static void notifyOnAllConnections(String method, Object[] params) {
    IConnection conn = Red5.getConnectionLocal();
    if (conn != null) {
        log.debug("Connection for notify on all: {}", conn);
        IScope scope = conn.getScope();
        log.debug("Scope for notify on all: {}", scope);
        notifyOnAllScopeConnections(scope, method, params);
    } else {
        log.warn("Connection was null (thread local), scope cannot be located and cannot execute notify request");
    }
}
 
Example 9
Source File: MultiThreadedApplicationAdapter.java    From red5-server-common with Apache License 2.0 4 votes vote down vote up
public void streamSubscriberClose(ISubscriberStream stream) {
    // log w3c connect event
    IConnection conn = Red5.getConnectionLocal();
    log.info("W3C x-category:stream x-event:stop c-ip:{} cs-bytes:{} sc-bytes:{} x-sname:{}", new Object[] { conn.getRemoteAddress(), conn.getReadBytes(), conn.getWrittenBytes(), stream.getName() });
}
 
Example 10
Source File: MultiThreadedApplicationAdapter.java    From red5-server-common with Apache License 2.0 4 votes vote down vote up
public void streamRecordStop(IBroadcastStream stream) {
    // log w3c connect event
    IConnection connection = Red5.getConnectionLocal();
    log.info("W3C x-category:stream x-event:record-stop c-ip:{} x-sname:{} x-file-name:{}", new Object[] { connection != null ? connection.getRemoteAddress() : "0.0.0.0", stream.getName(), stream.getSaveFilename() });
}
 
Example 11
Source File: StreamService.java    From red5-server-common with Apache License 2.0 4 votes vote down vote up
/**
 * Close stream
 */
public void closeStream() {
    IConnection conn = Red5.getConnectionLocal();
    closeStream(conn, conn.getStreamId());
}
 
Example 12
Source File: StreamService.java    From red5-server-common with Apache License 2.0 4 votes vote down vote up
/** {@inheritDoc} */
public void play(String name, int start, int length, boolean flushPlaylist) {
    log.debug("Play called - name: {} start: {} length: {} flush playlist: {}", new Object[] { name, start, length, flushPlaylist });
    IConnection conn = Red5.getConnectionLocal();
    if (conn instanceof IStreamCapableConnection) {
        IScope scope = conn.getScope();
        IStreamCapableConnection streamConn = (IStreamCapableConnection) conn;
        Number streamId = conn.getStreamId();
        if (StringUtils.isEmpty(name)) {
            log.warn("The stream name may not be empty");
            sendNSFailed(streamConn, StatusCodes.NS_FAILED, "The stream name may not be empty.", name, streamId);
            return;
        }
        IStreamSecurityService security = (IStreamSecurityService) ScopeUtils.getScopeService(scope, IStreamSecurityService.class);
        if (security != null) {
            Set<IStreamPlaybackSecurity> handlers = security.getStreamPlaybackSecurity();
            for (IStreamPlaybackSecurity handler : handlers) {
                if (!handler.isPlaybackAllowed(scope, name, start, length, flushPlaylist)) {
                    log.warn("You are not allowed to play stream {}", name);
                    sendNSFailed(streamConn, StatusCodes.NS_FAILED, "You are not allowed to play the stream.", name, streamId);
                    return;
                }
            }
        }
        boolean created = false;
        IClientStream stream = streamConn.getStreamById(streamId);
        if (stream == null) {
            if (log.isTraceEnabled()) {
                log.trace("Stream not found for stream id: {} streams: {}", streamId, streamConn.getStreamsMap());
            }
            try {
                // if our current stream id is less than or equal to 0, reserve a new id
                if (streamId.doubleValue() <= 0.0d) {
                    streamId = streamConn.reserveStreamId();
                }
                // instance a new stream for the stream id
                stream = streamConn.newPlaylistSubscriberStream(streamId);
                if (stream != null) {
                    if (log.isTraceEnabled()) {
                        log.trace("Created stream: {} for stream id: {}", stream, streamId);
                    }
                    stream.setBroadcastStreamPublishName(name);
                    stream.start();
                    created = true;
                } else {
                    log.warn("Stream was null for id: {}", streamId);
                    // throw the ex so the ns fail will go out
                    throw new Exception("Stream creation failed for name: " + name + " id: " + streamId);
                }
            } catch (Exception e) {
                log.warn("Unable to start playing stream: {}", name, e);
                sendNSFailed(streamConn, StatusCodes.NS_FAILED, "Unable to start playing stream", name, streamId);
                return;
            }
        }
        if (stream instanceof ISubscriberStream) {
            ISubscriberStream subscriberStream = (ISubscriberStream) stream;
            IPlayItem item = simplePlayback.get() ? SimplePlayItem.build(name, start, length) : DynamicPlayItem.build(name, start, length);
            if (subscriberStream instanceof IPlaylistSubscriberStream) {
                IPlaylistSubscriberStream playlistStream = (IPlaylistSubscriberStream) subscriberStream;
                if (flushPlaylist) {
                    playlistStream.removeAllItems();
                }
                playlistStream.addItem(item);
            } else if (subscriberStream instanceof ISingleItemSubscriberStream) {
                ISingleItemSubscriberStream singleStream = (ISingleItemSubscriberStream) subscriberStream;
                singleStream.setPlayItem(item);
            } else {
                // not supported by this stream service
                log.warn("Stream instance type: {} is not supported", subscriberStream.getClass().getName());
                return;
            }
            try {
                subscriberStream.play();
            } catch (IOException err) {
                if (created) {
                    stream.close();
                    streamConn.deleteStreamById(streamId);
                }
                log.warn("Unable to play stream " + name, err);
                sendNSFailed(streamConn, StatusCodes.NS_FAILED, err.getMessage(), name, streamId);
            }
        }
    } else {
        log.debug("Connection was not stream capable");
    }
}
 
Example 13
Source File: BandwidthDetection.java    From red5-examples with Apache License 2.0 4 votes vote down vote up
public void onServerClientBWCheck(Object[] params) {
	IConnection conn = Red5.getConnectionLocal();
	ServerClientDetection serverClient = new ServerClientDetection();
	serverClient.checkBandwidth(conn);
}
 
Example 14
Source File: Application.java    From red5-rtsp-restreamer with Apache License 2.0 4 votes vote down vote up
public synchronized void checkBW(int seconds, int chunkSize) {
	BandwidthChecker checker = new BandwidthChecker(Red5.getConnectionLocal(), seconds, chunkSize);
	this.addScheduledOnceJob(1000, checker);

}
 
Example 15
Source File: MultiThreadedApplicationAdapter.java    From red5-server-common with Apache License 2.0 4 votes vote down vote up
public void streamPublishStart(IBroadcastStream stream) {
    // log w3c connect event
    IConnection connection = Red5.getConnectionLocal();
    log.info("W3C x-category:stream x-event:publish c-ip:{} x-sname:{} x-name:{}", new Object[] { connection != null ? connection.getRemoteAddress() : "0.0.0.0", stream.getName(), stream.getPublishedName() });
}
 
Example 16
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 17
Source File: ServerClientDetection.java    From red5-examples with Apache License 2.0 4 votes vote down vote up
public void onServerClientBWCheck() {
	IConnection conn = Red5.getConnectionLocal();
	this.calculateClientBw(conn);
}
 
Example 18
Source File: RTMPClientProtocolEncoder.java    From red5-client with Apache License 2.0 4 votes vote down vote up
/**
 * Encode notification event and fill given byte buffer.
 *
 * @param out
 *            Byte buffer to fill
 * @param command
 *            Notification event
 */
@Override
protected void encodeCommand(IoBuffer out, ICommand command) {
    log.debug("encodeCommand - command: {}", command);
    RTMPConnection conn = (RTMPConnection) Red5.getConnectionLocal();
    Output output = new org.red5.io.amf.Output(out);
    final IServiceCall call = command.getCall();
    final boolean isPending = (call.getStatus() == Call.STATUS_PENDING);
    log.debug("Call: {} pending: {}", call, isPending);
    if (!isPending) {
        log.debug("Call has been executed, send result");
        Serializer.serialize(output, call.isSuccess() ? "_result" : "_error");
    } else {
        log.debug("This is a pending call, send request");
        // for request we need to use AMF3 for client mode if the connection is AMF3
        if (conn.getEncoding() == Encoding.AMF3) {
            output = new org.red5.io.amf3.Output(out);
        }
        final String action = (call.getServiceName() == null) ? call.getServiceMethodName() : call.getServiceName() + '.' + call.getServiceMethodName();
        Serializer.serialize(output, action);
    }
    if (command instanceof Invoke) {
        Serializer.serialize(output, Integer.valueOf(command.getTransactionId()));
        Serializer.serialize(output, command.getConnectionParams());
    }
    if (call.getServiceName() == null && "connect".equals(call.getServiceMethodName())) {
        // response to initial connect, always use AMF0
        output = new org.red5.io.amf.Output(out);
    } else {
        if (conn.getEncoding() == Encoding.AMF3) {
            output = new org.red5.io.amf3.Output(out);
        } else {
            output = new org.red5.io.amf.Output(out);
        }
    }
    if (!isPending && (command instanceof Invoke)) {
        IPendingServiceCall pendingCall = (IPendingServiceCall) call;
        if (!call.isSuccess()) {
            log.debug("Call was not successful");
            StatusObject status = generateErrorResult(StatusCodes.NC_CALL_FAILED, call.getException());
            pendingCall.setResult(status);
        }
        Object res = pendingCall.getResult();
        log.debug("Writing result: {}", res);
        Serializer.serialize(output, res);
    } else {
        log.debug("Writing params");
        final Object[] args = call.getArguments();
        if (args != null) {
            for (Object element : args) {
                Serializer.serialize(output, element);
            }
        }
    }
    if (command.getData() != null) {
        out.setAutoExpand(true);
        out.put(command.getData());
    }
}
 
Example 19
Source File: ServiceUtils.java    From red5-server-common with Apache License 2.0 3 votes vote down vote up
/**
 * Invoke a method on the current connection and handle result.
 * 
 * @param method
 *            name of the method to invoke
 * @param params
 *            parameters to pass to the method
 * @param callback
 *            object to notify when result is received
 * @return true if the connection supports method calls, otherwise false
 */
public static boolean invokeOnConnection(String method, Object[] params, IPendingServiceCallback callback) {
    IConnection conn = Red5.getConnectionLocal();
    if (conn != null) {
        log.debug("Connection for invoke: {}", conn);
        return invokeOnConnection(conn, method, params, callback);
    } else {
        log.warn("Connection was null (thread local), cannot execute invoke request");
        return false;
    }
}
 
Example 20
Source File: ServiceUtils.java    From red5-server-common with Apache License 2.0 3 votes vote down vote up
/**
 * Notify a method on the current connection.
 * 
 * @param method
 *            name of the method to notify
 * @param params
 *            parameters to pass to the method
 * @return <pre>
 * true
 * </pre>
 * 
 *         if the connection supports method calls, otherwise
 * 
 *         <pre>
 * false
 * </pre>
 */
public static boolean notifyOnConnection(String method, Object[] params) {
    IConnection conn = Red5.getConnectionLocal();
    if (conn != null) {
        log.debug("Connection for notify: {}", conn);
        return notifyOnConnection(conn, method, params);
    } else {
        log.warn("Connection was null (thread local), cannot execute notify request");
        return false;
    }
}