org.red5.server.api.service.IPendingServiceCall Java Examples

The following examples show how to use org.red5.server.api.service.IPendingServiceCall. 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: BaseRTMPHandler.java    From red5-server-common with Apache License 2.0 6 votes vote down vote up
/**
 * Handler for pending call result. Dispatches results to all pending call handlers.
 * 
 * @param conn
 *            Connection
 * @param invoke
 *            Pending call result event context
 */
protected void handlePendingCallResult(RTMPConnection conn, Invoke invoke) {
    final IServiceCall call = invoke.getCall();
    final IPendingServiceCall pendingCall = conn.retrievePendingCall(invoke.getTransactionId());
    if (pendingCall != null) {
        // The client sent a response to a previously made call.
        Object[] args = call.getArguments();
        if (args != null && args.length > 0) {
            // TODO: can a client return multiple results?
            pendingCall.setResult(args[0]);
        }
        Set<IPendingServiceCallback> callbacks = pendingCall.getCallbacks();
        if (!callbacks.isEmpty()) {
            HashSet<IPendingServiceCallback> tmp = new HashSet<>();
            tmp.addAll(callbacks);
            for (IPendingServiceCallback callback : tmp) {
                try {
                    callback.resultReceived(pendingCall);
                } catch (Exception e) {
                    log.error("Error while executing callback {}", callback, e);
                }
            }
        }
    }
}
 
Example #2
Source File: BaseRTMPClientHandler.java    From red5-client with Apache License 2.0 6 votes vote down vote up
@Override
public void resultReceived(IPendingServiceCall call) {
    Number streamId = (Number) call.getResult();
    log.debug("CreateStreamCallBack resultReceived - stream id: {} call: {} connection: {}", streamId, call, conn);
    if (conn != null && streamId != null) {
        log.debug("Setting new net stream");
        NetStream stream = new NetStream(streamEventDispatcher);
        stream.setConnection(conn);
        stream.setStreamId(streamId);
        conn.addClientStream(stream);
        NetStreamPrivateData streamData = new NetStreamPrivateData();
        streamData.outputStream = conn.createOutputStream(streamId);
        streamData.connConsumer = new ConnectionConsumer(conn, streamData.outputStream.getVideo(), streamData.outputStream.getAudio(), streamData.outputStream.getData());
        streamDataMap.put(streamId, streamData);
        log.debug("streamDataMap: {}", streamDataMap);
    }
    wrapped.resultReceived(call);
}
 
Example #3
Source File: StreamingProxy.java    From red5-client with Apache License 2.0 6 votes vote down vote up
@Override
public void resultReceived(IPendingServiceCall call) {
    String method = call.getServiceMethodName();
    log.debug("resultReceived: {}", method);
    if ("connect".equals(method)) {
        //rtmpClient.releaseStream(this, new Object[] { publishName });
        timer.schedule(new BandwidthStatusTask(), 2000L);
    } else if ("releaseStream".equals(method)) {
        //rtmpClient.invoke("FCPublish", new Object[] { publishName }, this);
    } else if ("createStream".equals(method)) {
        setState(StreamState.PUBLISHING);
        Object result = call.getResult();
        if (result instanceof Number) {
            streamId = (Number) result;
            log.debug("Publishing: {}", state);
            rtmpClient.publish(streamId, publishName, publishMode, this);
        } else {
            rtmpClient.disconnect();
            setState(StreamState.STOPPED);
        }
    } else if ("FCPublish".equals(method)) {

    }
}
 
Example #4
Source File: ClientServerDetection.java    From red5-server-common with Apache License 2.0 5 votes vote down vote up
/**
 * Handle callback from service call.
 */
public void resultReceived(IPendingServiceCall call) {
    // if we aren't connection, skip any further testing
    if (Call.STATUS_NOT_CONNECTED != call.getStatus()) {

    } else {
        log.debug("Pending call skipped due to being no longer connected");
    }
}
 
Example #5
Source File: RTMPTClientTest.java    From red5-client with Apache License 2.0 5 votes vote down vote up
@Override
public void resultReceived(IPendingServiceCall call) {
    int streamId = (Integer) call.getResult();
    // live buffer 0.5s / vod buffer 4s
    if (Boolean.valueOf(PropertiesReader.getProperty("rtmpt.live"))) {
        conn.ping(new Ping(Ping.CLIENT_BUFFER, streamId, 500));
        play(streamId, PropertiesReader.getProperty("rtmpt.name"), -1, -1);
    } else {
        conn.ping(new Ping(Ping.CLIENT_BUFFER, streamId, 4000));
        play(streamId, PropertiesReader.getProperty("rtmpt.name"), 0, -1);
    }
}
 
Example #6
Source File: RTMPTClientTest.java    From red5-client with Apache License 2.0 5 votes vote down vote up
@Override
public void resultReceived(IPendingServiceCall call) {
    System.out.println("connectCallback");
    ObjectMap<?, ?> map = (ObjectMap<?, ?>) call.getResult();
    String code = (String) map.get("code");
    System.out.printf("Response code: %s\n", code);
    if ("NetConnection.Connect.Rejected".equals(code)) {
        System.out.printf("Rejected: %s\n", map.get("description"));
        disconnect();
        synchronized (RTMPTClientTest.class) {
            finished = true;
            RTMPTClientTest.class.notifyAll();
        }
    } else if ("NetConnection.Connect.Failed".equals(code)) {
        System.out.printf("Failed: %s\n", map.get("description"));
        disconnect();
        synchronized (RTMPTClientTest.class) {
            finished = true;
            RTMPTClientTest.class.notifyAll();
        }
    } else if ("NetConnection.Connect.Success".equals(code)) {
        test();
        createStream(createStreamCallback);
    } else {
        System.out.printf("Unhandled response code: %s\n", code);
    }
}
 
Example #7
Source File: RTMPTSClientTest.java    From red5-client with Apache License 2.0 5 votes vote down vote up
@Override
public void resultReceived(IPendingServiceCall call) {
    int streamId = (Integer) call.getResult();
    // live buffer 0.5s / vod buffer 4s
    if (Boolean.valueOf(PropertiesReader.getProperty("rtmpts.live"))) {
        conn.ping(new Ping(Ping.CLIENT_BUFFER, streamId, 500));
        play(streamId, PropertiesReader.getProperty("rtmpts.name"), -1, -1);
    } else {
        conn.ping(new Ping(Ping.CLIENT_BUFFER, streamId, 4000));
        play(streamId, PropertiesReader.getProperty("rtmpts.name"), 0, -1);
    }
}
 
Example #8
Source File: RTMPTSClientTest.java    From red5-client with Apache License 2.0 5 votes vote down vote up
@Override
public void resultReceived(IPendingServiceCall call) {
    System.out.println("connectCallback");
    ObjectMap<?, ?> map = (ObjectMap<?, ?>) call.getResult();
    String code = (String) map.get("code");
    System.out.printf("Response code: %s\n", code);
    if ("NetConnection.Connect.Rejected".equals(code)) {
        System.out.printf("Rejected: %s\n", map.get("description"));
        disconnect();
        synchronized (RTMPTSClientTest.class) {
            finished = true;
            RTMPTSClientTest.class.notifyAll();
        }
    } else if ("NetConnection.Connect.Failed".equals(code)) {
        System.out.printf("Failed: %s\n", map.get("description"));
        disconnect();
        synchronized (RTMPTSClientTest.class) {
            finished = true;
            RTMPTSClientTest.class.notifyAll();
        }
    } else if ("NetConnection.Connect.Success".equals(code)) {
        test();
        createStream(createStreamCallback);
    } else {
        System.out.printf("Unhandled response code: %s\n", code);
    }
}
 
Example #9
Source File: RTMPClientTest.java    From red5-client with Apache License 2.0 5 votes vote down vote up
@Override
public void resultReceived(IPendingServiceCall call) {
    System.out.println("resultReceived: " + call);
    Double streamId = (Double) call.getResult();
    System.out.println("stream id: " + streamId);
    // send our buffer size request
    client.play(streamId, sourceStreamName, 0, -1);
}
 
Example #10
Source File: SharedObjectClient.java    From red5-client with Apache License 2.0 5 votes vote down vote up
@Override
public void resultReceived(IPendingServiceCall call) {
    log.debug("Received pending call: {}", call);
    Object result = call.getResult();
    if (result instanceof ObjectMap) {
        obj = getSharedObject(soName, false);
        obj.connect(Red5.getConnectionLocal());
        obj.addSharedObjectListener(this);
    }
}
 
Example #11
Source File: ClientTest.java    From red5-client with Apache License 2.0 5 votes vote down vote up
@Override
public void resultReceived(IPendingServiceCall call) {
    Number streamId = (Number) call.getResult();
    // live buffer 0.5s / vod buffer 4s
    if (Boolean.valueOf(PropertiesReader.getProperty("live"))) {
        conn.ping(new Ping(Ping.CLIENT_BUFFER, streamId, 500));
        play(streamId, PropertiesReader.getProperty("name"), -1, -1);
    } else {
        conn.ping(new Ping(Ping.CLIENT_BUFFER, streamId, 4000));
        play(streamId, PropertiesReader.getProperty("name"), 0, -1);
    }
}
 
Example #12
Source File: ClientTest.java    From red5-client with Apache License 2.0 5 votes vote down vote up
@Override
public void resultReceived(IPendingServiceCall call) {
    System.out.println("connectCallback");
    ObjectMap<?, ?> map = (ObjectMap<?, ?>) call.getResult();
    String code = (String) map.get("code");
    System.out.printf("Response code: %s\n", code);
    if ("NetConnection.Connect.Rejected".equals(code)) {
        System.out.printf("Rejected: %s\n", map.get("description"));
        disconnect();
        finished = true;
    } else if ("NetConnection.Connect.Success".equals(code)) {
        invoke("demoService.getListOfAvailableFLVs", new Object[] {}, methodCallCallback);
        createStream(createStreamCallback);
    }
}
 
Example #13
Source File: StreamRelay.java    From red5-client with Apache License 2.0 5 votes vote down vote up
@Override
public void resultReceived(IPendingServiceCall call) {
    System.out.println("resultReceived: " + call);
    Double streamId = (Double) call.getResult();
    System.out.println("stream id: " + streamId);
    // send our buffer size request
    if (sourceStreamName.endsWith(".flv") || sourceStreamName.endsWith(".f4v") || sourceStreamName.endsWith(".mp4")) {
        client.play(streamId, sourceStreamName, 0, -1);
    } else {
        client.play(streamId, sourceStreamName, -1, 0);
    }
}
 
Example #14
Source File: BaseRTMPClientHandler.java    From red5-client with Apache License 2.0 5 votes vote down vote up
@Override
public void resultReceived(IPendingServiceCall call) {
    log.debug("resultReceived", call);
    if (call.getResult() instanceof ObjectMap<?, ?>) {
        ObjectMap<?, ?> map = (ObjectMap<?, ?>) call.getResult();
        if (map.containsKey("code")) {
            String code = (String) map.get("code");
            log.debug("Code: {}", code);
            if (StatusCodes.NS_PLAY_START.equals(code)) {
                subscribed = true;
            }
        }
    }
    wrapped.resultReceived(call);
}
 
Example #15
Source File: BaseRTMPClientHandler.java    From red5-client with Apache License 2.0 5 votes vote down vote up
@Override
public void resultReceived(IPendingServiceCall call) {
    Number streamId = (Number) call.getResult();
    log.debug("Stream id: {} connection: {}", streamId, conn);
    log.debug("DeleteStreamCallBack resultReceived - stream id: {}", streamId);
    if (conn != null && streamId != null) {
        log.debug("Deleting net stream");
        conn.removeClientStream(streamId);
        // send a delete notify?
        //NetStreamPrivateData streamData = streamDataMap.get(streamId);
        //streamData.handler.onStreamEvent(notify)
        streamDataMap.remove(streamId);
    }
    wrapped.resultReceived(call);
}
 
Example #16
Source File: RTMPConnection.java    From red5-server-common with Apache License 2.0 5 votes vote down vote up
/**
 * When the connection has been closed, notify any remaining pending service calls that they have failed because the connection is
 * broken. Implementors of IPendingServiceCallback may only deduce from this notification that it was not possible to read a result for
 * this service call. It is possible that (1) the service call was never written to the service, or (2) the service call was written to
 * the service and although the remote method was invoked, the connection failed before the result could be read, or (3) although the
 * remote method was invoked on the service, the service implementor detected the failure of the connection and performed only partial
 * processing. The caller only knows that it cannot be confirmed that the callee has invoked the service call and returned a result.
 */
public void sendPendingServiceCallsCloseError() {
    if (pendingCalls != null && !pendingCalls.isEmpty()) {
        if (log.isDebugEnabled()) {
            log.debug("Connection calls pending: {}", pendingCalls.size());
        }
        for (IPendingServiceCall call : pendingCalls.values()) {
            call.setStatus(Call.STATUS_NOT_CONNECTED);
            for (IPendingServiceCallback callback : call.getCallbacks()) {
                callback.resultReceived(call);
            }
        }
    }
}
 
Example #17
Source File: RTMPConnection.java    From red5-server-common with Apache License 2.0 5 votes vote down vote up
/** {@inheritDoc} */
public void invoke(String method, Object[] params, IPendingServiceCallback callback) {
    IPendingServiceCall call = new PendingCall(method, params);
    if (callback != null) {
        call.registerCallback(callback);
    }
    invoke(call);
}
 
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: ServerClientDetection.java    From red5-server-common with Apache License 2.0 4 votes vote down vote up
/**
 * Handle callback from service call.
 */
public void resultReceived(IPendingServiceCall call) {
    // if we aren't connection, skip any further testing
    if (Call.STATUS_NOT_CONNECTED != call.getStatus()) {
        // receive time using nanos
        long now = System.nanoTime();
        // increment received
        int received = packetsReceived.incrementAndGet();
        log.debug("Call time stamps - write: {} read: {}", call.getWriteTime(), call.getReadTime());
        // time passed is in milliseconds
        timePassed = (now - startTime) / 1000000;
        log.debug("Received count: {} sent: {} timePassed: {} ms", new Object[] { received, packetsSent.get(), timePassed });
        switch (received) {
            case 1:
                // first packet is used to test latency
                latency = Math.max(Math.min(timePassed, LATENCY_MAX), LATENCY_MIN);
                log.debug("Receive latency: {}", latency);
                // We now have a latency figure so can start sending test data.
                // Second call. 1st packet sent
                log.debug("Sending first payload at {} ns", now);
                callBWCheck(payload); // 1k	
                break;
            case 2:
                log.debug("Sending second payload at {} ns", now);
                // increment cumulative latency
                cumLatency++;
                callBWCheck(payload1); // 32k
                break;
            default:
                log.debug("Doing calculations at {} ns", now);
                // increment cumulative latency
                cumLatency++;
                // bytes to kbits
                deltaDown = ((conn.getWrittenBytes() - startBytesWritten) * 8) / 1000d;
                log.debug("Delta kbits: {}", deltaDown);
                // total dl time - latency for each packet sent in secs
                deltaTime = (timePassed - (latency * cumLatency));
                if (deltaTime <= 0) {
                    deltaTime = (timePassed + latency);
                }
                log.debug("Delta time: {} ms", deltaTime);
                // calculate kbit/s
                kbitDown = Math.round(deltaDown / (deltaTime / 1000d));
                log.debug("onBWDone: kbitDown: {} deltaDown: {} deltaTime: {} latency: {} ", new Object[] { kbitDown, deltaDown, deltaTime, latency });
                callBWDone();
        }
    } else {
        log.debug("Pending call skipped due to being no longer connected");
    }
}
 
Example #20
Source File: RTMPTClientTest.java    From red5-client with Apache License 2.0 4 votes vote down vote up
@Override
public void resultReceived(IPendingServiceCall call) {
    System.out.println("methodCallCallback");
    Map<?, ?> map = (Map<?, ?>) call.getResult();
    System.out.printf("Response %s\n", map);
}
 
Example #21
Source File: RTMPTSClientTest.java    From red5-client with Apache License 2.0 4 votes vote down vote up
@Override
public void resultReceived(IPendingServiceCall call) {
    System.out.println("methodCallCallback");
    Map<?, ?> map = (Map<?, ?>) call.getResult();
    System.out.printf("Response %s\n", map);
}
 
Example #22
Source File: RTMPClientTest.java    From red5-client with Apache License 2.0 4 votes vote down vote up
@Override
public void resultReceived(IPendingServiceCall call) {
    System.out.println("resultReceived: " + call);
}
 
Example #23
Source File: RTMPClientTest.java    From red5-client with Apache License 2.0 4 votes vote down vote up
@Test
public void test26() throws InterruptedException {
    client.setStreamEventHandler(new INetStreamEventHandler() {
        @Override
        public void onStreamEvent(Notify notify) {
            log.info("ClientStream.dispachEvent: {}", notify);
        }
    });
    client.setServiceProvider(new ClientMethodHander());
    client.setConnectionClosedHandler(new Runnable() {
        @Override
        public void run() {
            System.out.println("Connection closed");
        }
    });
    client.setExceptionHandler(new ClientExceptionHandler() {
        @Override
        public void handleException(Throwable throwable) {
            throwable.printStackTrace();
        }
    });

    IPendingServiceCallback connectCallback = new IPendingServiceCallback() {
        @Override
        public void resultReceived(IPendingServiceCall call) {
            log.info("connectCallback");
            ObjectMap<?, ?> map = (ObjectMap<?, ?>) call.getResult();
            String code = (String) map.get("code");
            log.info("Response code: {}", code);
            if ("NetConnection.Connect.Rejected".equals(code)) {
                System.out.printf("Rejected: %s\n", map.get("description"));
                client.disconnect();
            } else if ("NetConnection.Connect.Success".equals(code)) {
                // 1. Wait for onBWDone
                timer.schedule(new BandwidthStatusTask(), 2000L);
            }
        }
    };

    /*
     * client.connect("localhost", 1935, "live/remote/0586e318-6277-11e3-adc2-22000a1d91fe", new IPendingServiceCallback() {
     * @Override public void resultReceived(IPendingServiceCall result) { System.out.println("resultReceived: " + result); ObjectMap<?, ?> map = (ObjectMap<?, ?>) result.getResult();
     * String code = (String) map.get("code"); System.out.printf("Response code: %s\n", code); if ("NetConnection.Connect.Rejected".equals(code)) { System.out.printf("Rejected: %s\n",
     * map.get("description")); client.disconnect(); } else if ("NetConnection.Connect.Success".equals(code)) { System.out.println("success: " + result.isSuccess()); ArrayList<Object>
     * list = new ArrayList<>(); list.add(new Object[] { "fujifilm-x100s-video-test-1080p-full-hd-hdmp4_720.mp4" }); list.add(new Object[] {
     * "canon-500d-test-video-720-hd-30-fr-hdmp4_720.mp4" }); Object[] params = { "64", "cc-video-processed/", list }; //Object[] params = { "64", "cc-video-processed/" };
     * client.invoke("loadPlaylist", params, new IPendingServiceCallback() {
     * @Override public void resultReceived(IPendingServiceCall result) { System.out.println(result); } }); } } });
     */
    client.connect("localhost", 1935, "vod", connectCallback);

    do {
        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
        }
    } while (!client.conn.isClosed());
    log.debug("Client not connected");
    timer.cancel();
    log.info("Exit");
}
 
Example #24
Source File: Invoke.java    From red5-server-common with Apache License 2.0 4 votes vote down vote up
/** {@inheritDoc} */
@Override
public IPendingServiceCall getCall() {
    return (IPendingServiceCall) call;
}
 
Example #25
Source File: ClientTest.java    From red5-client with Apache License 2.0 4 votes vote down vote up
@Override
public void resultReceived(IPendingServiceCall call) {
    System.out.println("methodCallCallback");
    Map<?, ?> map = (Map<?, ?>) call.getResult();
    System.out.printf("Response %s\n", map);
}
 
Example #26
Source File: RTMPProtocolEncoder.java    From red5-server-common with Apache License 2.0 4 votes vote down vote up
/**
 * Encode command event and fill given byte buffer.
 *
 * @param out
 *            Buffer to fill
 * @param command
 *            Command event
 */
protected void encodeCommand(IoBuffer out, ICommand command) {
    // TODO: tidy up here
    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");
        final String action = (call.getServiceName() == null) ? call.getServiceMethodName() : call.getServiceName() + '.' + call.getServiceMethodName();
        Serializer.serialize(output, action); // seems right
    }
    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 (Red5.getConnectionLocal().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() && (call.getException() != null || pendingCall.getResult() == null)) {
            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) {
                if (element instanceof ByteBuffer) {
                    // a byte buffer indicates that serialization is already complete, send raw
                    final ByteBuffer buf = (ByteBuffer) element;
                    buf.mark();
                    try {
                        out.put(buf);
                    } finally {
                        buf.reset();
                    }
                } else {
                    // standard serialize
                    Serializer.serialize(output, element);
                }
            }
        }
    }
    if (command.getData() != null) {
        out.setAutoExpand(true);
        out.put(command.getData());
    }
}
 
Example #27
Source File: StreamRelay.java    From red5-client with Apache License 2.0 4 votes vote down vote up
@Override
public void resultReceived(IPendingServiceCall call) {
    System.out.println("resultReceived: " + call);
}
 
Example #28
Source File: BaseRTMPHandler.java    From red5-server-common with Apache License 2.0 4 votes vote down vote up
/** {@inheritDoc} */
public void messageReceived(RTMPConnection conn, Packet packet) throws Exception {
    log.trace("messageReceived connection: {}", conn.getSessionId());
    if (conn != null) {
        IRTMPEvent message = null;
        try {
            message = packet.getMessage();
            final Header header = packet.getHeader();
            final Number streamId = header.getStreamId();
            final Channel channel = conn.getChannel(header.getChannelId());
            final IClientStream stream = conn.getStreamById(streamId);
            if (log.isTraceEnabled()) {
                log.trace("Message received - header: {}", header);
            }
            // set stream id on the connection
            conn.setStreamId(streamId);
            // increase number of received messages
            conn.messageReceived();
            // set the source of the message
            message.setSource(conn);
            // process based on data type
            final byte headerDataType = header.getDataType();
            if (log.isTraceEnabled()) {
                log.trace("Header / message data type: {}", headerDataType);
            }
            switch (headerDataType) {
                case TYPE_AGGREGATE:
                    log.debug("Aggregate type data - header timer: {} size: {}", header.getTimer(), header.getSize());
                case TYPE_AUDIO_DATA:
                case TYPE_VIDEO_DATA:
                    // mark the event as from a live source
                    // log.trace("Marking message as originating from a Live source");
                    message.setSourceType(Constants.SOURCE_TYPE_LIVE);
                    // NOTE: If we respond to "publish" with "NetStream.Publish.BadName",
                    // the client sends a few stream packets before stopping. We need to ignore them
                    if (stream != null) {
                        ((IEventDispatcher) stream).dispatchEvent(message);
                    }
                    break;
                case TYPE_FLEX_SHARED_OBJECT:
                case TYPE_SHARED_OBJECT:
                    onSharedObject(conn, channel, header, (SharedObjectMessage) message);
                    break;
                case TYPE_INVOKE:
                case TYPE_FLEX_MESSAGE:
                    onCommand(conn, channel, header, (Invoke) message);
                    IPendingServiceCall call = ((Invoke) message).getCall();
                    if (message.getHeader().getStreamId().intValue() != 0 && call.getServiceName() == null && StreamAction.PUBLISH.equals(call.getServiceMethodName())) {
                        if (stream != null) {
                            // Only dispatch if stream really was created
                            ((IEventDispatcher) stream).dispatchEvent(message);
                        }
                    }
                    break;
                case TYPE_NOTIFY:
                    // like an invoke, but does not return anything and has a invoke / transaction id of 0
                case TYPE_FLEX_STREAM_SEND:
                    if (((Notify) message).getData() != null && stream != null) {
                        // Stream metadata
                        ((IEventDispatcher) stream).dispatchEvent(message);
                    } else {
                        onCommand(conn, channel, header, (Notify) message);
                    }
                    break;
                case TYPE_PING:
                    onPing(conn, channel, header, (Ping) message);
                    break;
                case TYPE_BYTES_READ:
                    onStreamBytesRead(conn, channel, header, (BytesRead) message);
                    break;
                case TYPE_CHUNK_SIZE:
                    onChunkSize(conn, channel, header, (ChunkSize) message);
                    break;
                case Constants.TYPE_CLIENT_BANDWIDTH: // onBWDone / peer bw
                    log.debug("Client bandwidth: {}", message);
                    onClientBandwidth(conn, channel, (ClientBW) message);
                    break;
                case Constants.TYPE_SERVER_BANDWIDTH: // window ack size
                    log.debug("Server bandwidth: {}", message);
                    onServerBandwidth(conn, channel, (ServerBW) message);
                    break;
                default:
                    log.debug("Unknown type: {}", header.getDataType());
            }
            if (message instanceof Unknown) {
                log.info("Message type unknown: {}", message);
            }
        } catch (Throwable t) {
            log.error("Exception", t);
        }
        // XXX this may be causing 'missing' data if previous methods are not making copies before buffering etc..
        if (message != null) {
            message.release();
        }
    }
}
 
Example #29
Source File: BaseRTMPClientHandler.java    From red5-client with Apache License 2.0 4 votes vote down vote up
@Override
public void resultReceived(IPendingServiceCall call) {
    wrapped.resultReceived(call);
}
 
Example #30
Source File: ServerClientDetection.java    From red5-examples with Apache License 2.0 4 votes vote down vote up
/**
 * Handle callback from service call.
 */


public void resultReceived(IPendingServiceCall call) { 
	Long now = new Long(System.nanoTime()/1000000); //new Long(System.currentTimeMillis());
	this.pakRecv.add(now);
	timePassed = (now - this.beginningValues.get("time"));

	count++;

       log.info("count: {} sent: {} timePassed: {} latency: {}", new Object[]{count, sent, timePassed, latency});

	if (count == 1) {
		latency = Math.min(timePassed, 800);
		latency = Math.max(latency, 10);

		// We now have a latency figure so can start sending test data.
		// Second call. 1st packet sent
		pakSent.add(now);
		sent++;

		log.info("Sending First Payload at {} count: {} sent: {} ", new Object[]{now, count, sent});
		this.callBWCheck(this.client.getAttribute("payload"));

	}

       
       //To run a very quick test, uncomment the following if statement and comment out the next 3 if statements.

	/*
	 * else if (count == 2 && (timePassed < 2000)) { pakSent.add(now);
	 * sent++; cumLatency++;
	 * this.callBWCheck(this.client.getAttribute("payload")); }
	 */

      
       //The following will progressivly increase the size of the packets been sent until 1 second has elapsed.
	else if ((count > 1 && count < 3) && (timePassed < 1000)) {
		pakSent.add(now);
		sent++;
		cumLatency++;
		log.info("Sending Second Payload at {} count: {} sent: {} ", new Object[]{now, count, sent});
		this.callBWCheck(this.client.getAttribute("payload_1"));
       }
       else if ((count >=3 && count < 6) && (timePassed < 1000)) {
		pakSent.add(now);
		sent++;
		cumLatency++;
		log.info("Sending Third Payload at {} count: {} sent: {} ", new Object[]{now, count, sent});
		this.callBWCheck(this.client.getAttribute("payload_1"));
	}

	else if (count >= 6 && (timePassed < 1000)) {
		pakSent.add(now);
		sent++;
		cumLatency++;
		log.info("Sending Fourth Payload at {} count: {} sent: {}", new Object[]{now, count, sent});
		this.callBWCheck(this.client.getAttribute("payload_2"));
	}

	// Time elapsed now do the calcs
	else if (sent == count) {
		// see if we need to normalize latency
		if (latency >= 100) {
			// make sure satelite and modem is detected properly
			if (pakRecv.get(1) - pakRecv.get(0) > 1000) {
				latency = 100;
			}
		}

		this.client.removeAttribute("payload");
		this.client.removeAttribute("payload_1");
		this.client.removeAttribute("payload_2");

		final IStreamCapableConnection endStats = this.getStats();
		
		this.deltaDown = (endStats.getWrittenBytes() - beginningValues.get("b_down")) * 8 / 1000; // bytes to kbits
           this.deltaTime = ((now - beginningValues.get("time")) - (latency * cumLatency)) / 1000; // total dl time - latency for each packet sent in secs
           
           if (Math.round(deltaTime) <= 0) {
			this.deltaTime = (now - beginningValues.get("time") + latency) / 1000;
		}
		this.kbitDown = Math.round(deltaDown / deltaTime); // kbits / sec
		
           if (kbitDown < 100) this.kbitDown = 100;
           
           log.info("onBWDone: kbitDown: {} deltaDown: {} deltaTime: {} latency: {} ", new Object[]{kbitDown, deltaDown, deltaTime, this.latency});
           
           this.callBWDone();                                 
	}

}