org.red5.server.api.IConnection Java Examples

The following examples show how to use org.red5.server.api.IConnection. 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: ServiceUtils.java    From red5-server-common with Apache License 2.0 6 votes vote down vote up
/**
 * Invoke a method on all connections of a client to a given scope and handle result.
 * 
 * @param client
 *            client to get connections for
 * @param scope
 *            scope to get connections of the client from
 * @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
 * @deprecated Use {@link ServiceUtils#invokeOnAllScopeConnections(IScope, String, Object[], IPendingServiceCallback)} instead
 */
@Deprecated
public static void invokeOnClient(IClient client, IScope scope, String method, Object[] params, IPendingServiceCallback callback) {
    if (client == null) {
        invokeOnAllScopeConnections(scope, method, params, callback);
    } else {
        IConnection conn = scope.lookupConnection(client);
        if (conn != null) {
            if (callback == null) {
                invokeOnConnection(conn, method, params);
            } else {
                invokeOnConnection(conn, method, params, callback);
            }
        }
    }
}
 
Example #2
Source File: Scope.java    From red5-server-common with Apache License 2.0 6 votes vote down vote up
/** {@inheritDoc} */
public Set<IConnection> getClientConnections() {
    Set<IConnection> result = new HashSet<IConnection>(3);
    log.debug("Client count: {}", clients.size());
    for (IClient cli : clients) {
        Set<IConnection> set = cli.getConnections();
        log.debug("Client connection count: {}", set.size());
        if (set.size() > 1) {
            log.warn("Client connections exceeded expected single count; size: {}", set.size());
        }
        for (IConnection conn : set) {
            result.add(conn);
        }
    }
    return result;
}
 
Example #3
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 #4
Source File: ServerClientDetection.java    From red5-server-common with Apache License 2.0 6 votes vote down vote up
private void callBWDone() {
    log.debug("callBWDone");
    IConnection conn = Red5.getConnectionLocal();
    Map<String, Object> statsValues = new HashMap<String, Object>();
    statsValues.put("kbitDown", kbitDown);
    statsValues.put("deltaDown", deltaDown);
    statsValues.put("deltaTime", deltaTime);
    statsValues.put("latency", latency);
    if (conn instanceof IServiceCapableConnection) {
        log.debug("Invoking onBWDone on the client");
        // invoke on the client
        ((IServiceCapableConnection) conn).invoke("onBWDone", new Object[] { statsValues });
        // adjust bandwidth to mbit/s
        int mbits = (int) ((kbitDown / 1000d) * 1000000);
        log.debug("Setting bandwidth to {} mbit/s", mbits);
        // tell the flash player how fast we want data and how fast we shall send it
        conn.setBandwidth(mbits);
    }
}
 
Example #5
Source File: ClientSharedObject.java    From red5-server-common with Apache License 2.0 6 votes vote down vote up
/**
 * Connect the shared object using the passed connection.
 * 
 * @param conn
 *            Attach SO to given connection
 */
public void connect(IConnection conn) {
    if (conn instanceof RTMPConnection) {
        if (!isConnected()) {
            source = conn;
            SharedObjectMessage msg = new SharedObjectMessage(name, 0, isPersistent());
            msg.addEvent(new SharedObjectEvent(Type.SERVER_CONNECT, null, null));
            Channel c = ((RTMPConnection) conn).getChannel(3);
            c.write(msg);
        } else {
            throw new UnsupportedOperationException("Already connected");
        }
    } else {
        throw new UnsupportedOperationException("Only RTMP connections are supported");
    }
}
 
Example #6
Source File: Scope.java    From red5-server-common with Apache License 2.0 6 votes vote down vote up
/** {@inheritDoc} */
@Deprecated
public Set<IConnection> lookupConnections(IClient client) {
    HashSet<IConnection> result = new HashSet<IConnection>(1);
    if (clients.contains(client)) {
        for (IClient cli : clients) {
            if (cli.equals(client)) {
                Set<IConnection> set = cli.getConnections();
                if (set.size() > 1) {
                    log.warn("Client connections exceeded expected single count; size: {}", set.size());
                }
                result.add(set.iterator().next());
                break;
            }
        }
    }
    return result;
}
 
Example #7
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 #8
Source File: Client.java    From red5-server-common with Apache License 2.0 6 votes vote down vote up
/**
 * Associate connection with client
 * 
 * @param conn
 *            Connection object
 */
protected void register(IConnection conn) {
    if (log.isDebugEnabled()) {
        if (conn == null) {
            log.debug("Register null connection, client id: {}", id);
        } else {
            log.debug("Register connection ({}:{}) client id: {}", conn.getRemoteAddress(), conn.getRemotePort(), id);
        }
    }
    if (conn != null) {
        IScope scope = conn.getScope();
        if (scope != null) {
            log.debug("Registering for scope: {}", scope);
            connections.add(conn);
        } else {
            log.warn("Clients scope is null. Id: {}", id);
        }
    } else {
        log.warn("Clients connection is null. Id: {}", id);
    }
}
 
Example #9
Source File: StreamService.java    From red5-server-common with Apache License 2.0 6 votes vote down vote up
/**
 * Pause at given position. Required as "pausePlayback" can be "null" if no flag is passed by the client
 * 
 * @param pausePlayback
 *            Pause playback or not
 * @param position
 *            Pause position
 */
public void pause(Boolean pausePlayback, int position) {
    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;
            // pausePlayback can be "null" if "pause" is called without any parameters from flash
            if (pausePlayback == null) {
                pausePlayback = !subscriberStream.isPaused();
            }
            if (pausePlayback) {
                subscriberStream.pause(position);
            } else {
                subscriberStream.resume(position);
            }
        }
    }
}
 
Example #10
Source File: StreamService.java    From red5-server-common with Apache License 2.0 6 votes vote down vote up
/** {@inheritDoc} */
public void publish(Boolean dontStop) {
    // null is as good as false according to Boolean.valueOf() so if null, interpret as false
    if (dontStop == null || !dontStop) {
        IConnection conn = Red5.getConnectionLocal();
        if (conn instanceof IStreamCapableConnection) {
            IStreamCapableConnection streamConn = (IStreamCapableConnection) conn;
            Number streamId = conn.getStreamId();
            IClientStream stream = streamConn.getStreamById(streamId);
            if (stream instanceof IBroadcastStream) {
                IBroadcastStream bs = (IBroadcastStream) stream;
                if (bs.getPublishedName() != null) {
                    IBroadcastScope bsScope = getBroadcastScope(conn.getScope(), bs.getPublishedName());
                    if (bsScope != null) {
                        bsScope.unsubscribe(bs.getProvider());
                        if (conn instanceof BaseConnection) {
                            ((BaseConnection) conn).unregisterBasicScope(bsScope);
                        }
                    }
                    bs.close();
                    streamConn.deleteStreamById(streamId);
                }
            }
        }
    }
}
 
Example #11
Source File: StreamService.java    From red5-server-common with Apache License 2.0 6 votes vote down vote up
/** {@inheritDoc} */
public void seek(int position) {
    log.trace("seek - position:{}", position);
    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;
            try {
                subscriberStream.seek(position);
            } catch (OperationNotSupportedException err) {
                sendNSFailed(streamConn, StatusCodes.NS_SEEK_FAILED, "The stream doesn't support seeking.", stream.getName(), streamId);
            }
        }
    }
}
 
Example #12
Source File: BasicScope.java    From red5-server-common with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
public boolean isConnectionAllowed(IConnection conn) {
    if (log.isDebugEnabled()) {
        log.debug("isConnectionAllowed: {}", conn);
    }
    if (securityHandlers != null) {
        if (log.isDebugEnabled()) {
            log.debug("securityHandlers: {}", securityHandlers);
        }
        // loop through the handlers
        for (IScopeSecurityHandler handler : securityHandlers) {
            // if allowed continue to the next handler
            if (handler.allowed(conn)) {
                continue;
            } else {
                // if any handlers deny we return false
                return false;
            }
        }
    }
    // default is to allow
    return true;
}
 
Example #13
Source File: BaseConnection.java    From red5-server-common with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a new base connection with the given parameters.
 *
 * @param type
 *            Connection type
 * @param host
 *            Host
 * @param remoteAddress
 *            Remote address
 * @param remotePort
 *            Remote port
 * @param path
 *            Scope path on server
 * @param sessionId
 *            Session id
 * @param params
 *            Params passed from client
 */
@ConstructorProperties({ "type", "host", "remoteAddress", "remotePort", "path", "sessionId" })
public BaseConnection(String type, String host, String remoteAddress, int remotePort, String path, String sessionId, Map<String, Object> params) {
    log.debug("New BaseConnection - type: {} host: {} remoteAddress: {} remotePort: {} path: {} sessionId: {}", new Object[] { type, host, remoteAddress, remotePort, path, sessionId });
    log.debug("Params: {}", params);
    if (type != null) {
        this.type = IConnection.Type.valueOf(type.toUpperCase());
    } else {
        this.type = IConnection.Type.UNKNOWN;
    }
    this.host = host;
    this.remoteAddress = remoteAddress;
    this.remoteAddresses = new ArrayList<String>(1);
    this.remoteAddresses.add(remoteAddress);
    this.remoteAddresses = Collections.unmodifiableList(this.remoteAddresses);
    this.remotePort = remotePort;
    this.path = path;
    this.sessionId = sessionId;
    this.params = params;
    log.debug("Generated session id: {}", sessionId);
}
 
Example #14
Source File: MultiThreadedApplicationAdapter.java    From red5-server-common with Apache License 2.0 6 votes vote down vote up
/**
 * Returns disconnection result for given scope and parameters. Whether the scope is room or app level scope, this method distinguishes
 * it and acts accordingly.
 * 
 * @param conn
 *            Connection object
 * @param scope
 *            Scope
 */
@Override
public void disconnect(IConnection conn, IScope scope) {
    log.debug("disconnect: {} < {}", conn, scope);
    if (log.isInfoEnabled() && ScopeUtils.isApp(scope)) {
        // log w3c connect event
        IClient client = conn.getClient();
        if (client == null) {
            // log w3c connect event
            log.info("W3C x-category:session x-event:disconnect c-ip:{}", conn.getRemoteAddress());
        } else {
            // log w3c connect event
            log.info("W3C x-category:session x-event:disconnect c-ip:{} c-client-id:{}", conn.getRemoteAddress(), client.getId());
        }
    }
    if (ScopeUtils.isApp(scope)) {
        appDisconnect(conn);
    } else if (ScopeUtils.isRoom(scope)) {
        roomDisconnect(conn);
    }
    super.disconnect(conn, scope);
}
 
Example #15
Source File: Client.java    From red5-server-common with Apache License 2.0 6 votes vote down vote up
/**
 * Disconnects client from Red5 application
 */
public void disconnect() {
    if (disconnected.compareAndSet(false, true)) {
        log.debug("Disconnect - id: {}", id);
        if (connections != null && !connections.isEmpty()) {
            log.debug("Closing {} scope connections", connections.size());
            // close all connections held to Red5 by client
            for (IConnection con : getConnections()) {
                try {
                    con.close();
                } catch (Exception e) {
                    // closing a connection calls into application code, so exception possible
                    log.error("Unexpected exception closing connection {}", e);
                }
            }
        } else {
            log.debug("Connection map is empty or null");
        }
        // unregister client
        removeInstance();
    }
}
 
Example #16
Source File: ClientServerDetection.java    From red5-server-common 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 #17
Source File: Application.java    From red5-examples with Apache License 2.0 5 votes vote down vote up
/** {@inheritDoc} */
@Override
public void appDisconnect(IConnection conn) {
    log.info("oflaDemo appDisconnect");
    if (appScope == conn.getScope() && serverStream != null) {
        serverStream.close();
    }
    super.appDisconnect(conn);
}
 
Example #18
Source File: BaseConnection.java    From red5-server-common with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new base connection with the given type.
 *
 * @param type
 *            Connection type
 */
@ConstructorProperties({ "type" })
public BaseConnection(String type) {
    log.debug("New BaseConnection - type: {}", type);
    if (type != null) {
        this.type = IConnection.Type.valueOf(type.toUpperCase());
    } else {
        this.type = IConnection.Type.UNKNOWN;
    }
    this.sessionId = RandomStringUtils.randomAlphanumeric(13).toUpperCase();
    log.debug("Generated session id: {}", sessionId);
}
 
Example #19
Source File: Application.java    From red5-hls-plugin with Apache License 2.0 5 votes vote down vote up
@Override
public void appDisconnect(IConnection conn) {
	log.debug("appDisconnect");
	// ensure that the recorded stream was completed or reject it here
	if (conn.hasAttribute("streamName")) {
		@SuppressWarnings("unused")
		String streamName = conn.getStringAttribute("streamName");

	}
	super.appDisconnect(conn);
}
 
Example #20
Source File: ServerClientDetection.java    From red5-server-common with Apache License 2.0 5 votes vote down vote up
public void calculateClientBw(IConnection conn) {
    log.debug("calculateClientBw: {} ", conn);
    // set local connection ref
    this.conn = conn;
    // get random generator
    Random rnd = new Random();
    rnd.nextBytes(payload);
    rnd.nextBytes(payload1);
    // get the current bytes written on the connection
    startBytesWritten = conn.getWrittenBytes();
    // start time using nanos
    startTime = System.nanoTime();
    log.debug("Starting bandwidth check at {} ns", startTime);
    callBWCheck("");
}
 
Example #21
Source File: AbortTranscodeCommand.java    From poor-man-transcoder with GNU General Public License v2.0 5 votes vote down vote up
@Override
public boolean execute(Context context) throws Exception {
	// TODO Auto-generated method stub
	TranscoderContext ctx = (TranscoderContext) context;
	TranscodeSessionPool pool =  ctx.getPool();
	IConnection connnection = Red5.getConnectionLocal();
	
	String signature = (String) connnection.getAttribute(Constants.TRANSCODER_SESSION_ATTR);
	ISession session = pool.getSession(signature);
	session.stop();
	
	return true;
}
 
Example #22
Source File: ServerClientDetection.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 #23
Source File: BandwidthChecker.java    From red5-rtsp-restreamer with Apache License 2.0 5 votes vote down vote up
public BandwidthChecker(IConnection conn, long forSeconds, long size) {
	connection = conn;
	connection.setAttribute("bwChecker", this);
	duration = forSeconds * 1000;
	chunk = new ArrayList<Byte>();
	int i = (int) size;
	while (i-- > 0)
		chunk.add(new Byte((byte) (i % 255)));

}
 
Example #24
Source File: MultiThreadedApplicationAdapter.java    From red5-server-common with Apache License 2.0 5 votes vote down vote up
/**
 * Returns connection result for given scope and parameters. Whether the scope is room or app level scope, this method distinguishes it
 * and acts accordingly. You override {@link ApplicationAdapter#appConnect(IConnection, Object[])} or
 * {@link ApplicationAdapter#roomConnect(IConnection, Object[])} in your application to make it act the way you want.
 * 
 * @param conn
 *            Connection object
 * @return <code>true</code> if connect is successful, <code>false</code> otherwise
 */
public boolean connect(IConnection conn) {
    // ensure the log is not null at this point
    if (log == null) {
        log = Red5LoggerFactory.getLogger(this.getClass());
    }
    // get the scope from the connection
    IScope scope = conn.getScope();
    log.debug("connect: {} > {}", conn, scope);
    return connect(conn, scope, null);
}
 
Example #25
Source File: ServerClientDetection.java    From red5-examples with Apache License 2.0 5 votes vote down vote up
public void calculateClientBw(IConnection p_client) {

		for (int i = 0; i < 1200; i++) {
			payload[i] = Math.random();
		}

		p_client.setAttribute("payload", payload);

		for (int i = 0; i < 12000; i++) {
			payload_1[i] = Math.random();
		}

		p_client.setAttribute("payload_1", payload_1);

		for (int i = 0; i < 12000; i++) {
			payload_2[i] = Math.random();
		}

		p_client.setAttribute("payload_2", payload_2);

		final IStreamCapableConnection beginningStats = this.getStats();
		final Long start = new Long(System.nanoTime() / 1000000); 

		this.client = p_client;
		beginningValues = new HashMap<String, Long>();
		beginningValues.put("b_down", beginningStats.getWrittenBytes());
		beginningValues.put("time", start);

		this.pakSent.add(start);
		this.sent++;
		log.info("Starting bandwidth check {} ", new Object[]{start});
        
		this.callBWCheck("");

	}
 
Example #26
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 #27
Source File: ServiceUtils.java    From red5-server-common with Apache License 2.0 5 votes vote down vote up
/**
 * Invoke a method on all connections to the current scope 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
 */
public static void invokeOnAllConnections(String method, Object[] params, IPendingServiceCallback callback) {
    IConnection conn = Red5.getConnectionLocal();
    if (conn != null) {
        log.debug("Connection for invoke on all: {}", conn);
        IScope scope = conn.getScope();
        log.debug("Scope for invoke on all: {}", scope);
        invokeOnAllScopeConnections(scope, method, params, callback);
    } else {
        log.warn("Connection was null (thread local), scope cannot be located and cannot execute invoke request");
    }
}
 
Example #28
Source File: MultiThreadedApplicationAdapter.java    From red5-server-common with Apache License 2.0 5 votes vote down vote up
/**
 * Handler method. Called every time client disconnects from the room.
 * 
 * @param conn
 *            Disconnected connection object
 */
public void roomDisconnect(IConnection conn) {
    log.debug("roomDisconnect: {}", conn);
    for (IApplication listener : listeners) {
        listener.roomDisconnect(conn);
    }
}
 
Example #29
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 #30
Source File: Client.java    From red5-server-common with Apache License 2.0 5 votes vote down vote up
/** {@inheritDoc} */
public void setPermissions(IConnection conn, Collection<String> permissions) {
    if (permissions == null) {
        conn.removeAttribute(PERMISSIONS);
    } else {
        conn.setAttribute(PERMISSIONS, permissions);
    }
}