Search in sources :

Example 1 with IPendingServiceCall

use of org.red5.server.api.service.IPendingServiceCall in project red5-client by Red5.

the class RTMPSClientTest method test31.

// https://github.com/Red5/red5-client/pull/31
@Test
public void test31() throws InterruptedException {
    final RTMPSClient client = new RTMPSClient();
    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();
        }
    });
    Thread t = new Thread(new Runnable() {

        @Override
        public void run() {
            client.connect(PropertiesReader.getProperty("rtmps.server"), Integer.valueOf(PropertiesReader.getProperty("rtmps.port")), PropertiesReader.getProperty("rtmps.app"), 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());
                        // if its oflaDemo, get the list of flvs
                        if ("oflaDemo".equals(PropertiesReader.getProperty("rtmps.app"))) {
                            client.invoke("demoService.getListOfAvailableFLVs", new Object[] {}, new IPendingServiceCallback() {

                                @Override
                                public void resultReceived(IPendingServiceCall call) {
                                    System.out.println("methodCallCallback");
                                    Map<?, ?> map = (Map<?, ?>) call.getResult();
                                    System.out.printf("Response %s\n", map);
                                }
                            });
                        }
                        client.createStream(new IPendingServiceCallback() {

                            @Override
                            public void resultReceived(IPendingServiceCall call) {
                                Number streamId = (Number) call.getResult();
                                // live buffer 0.5s / vod buffer 4s
                                if (Boolean.valueOf(PropertiesReader.getProperty("rtmps.live"))) {
                                    client.ping(Ping.CLIENT_BUFFER, streamId, 500);
                                    client.play(streamId, PropertiesReader.getProperty("rtmps.name"), -1, -1);
                                } else {
                                    client.ping(Ping.CLIENT_BUFFER, streamId, 4000);
                                    client.play(streamId, PropertiesReader.getProperty("rtmps.name"), 0, -1);
                                }
                            }
                        });
                    }
                }
            });
        }
    });
    t.start();
    t.join();
    System.out.println("Joined");
    Thread.sleep(60000L);
    // disconnect
    client.disconnect();
}
Also used : IPendingServiceCallback(org.red5.server.api.service.IPendingServiceCallback) IPendingServiceCall(org.red5.server.api.service.IPendingServiceCall) ClientExceptionHandler(org.red5.client.net.rtmp.ClientExceptionHandler) ObjectMap(org.red5.io.utils.ObjectMap) ObjectMap(org.red5.io.utils.ObjectMap) Map(java.util.Map) Test(org.junit.Test)

Example 2 with IPendingServiceCall

use of org.red5.server.api.service.IPendingServiceCall in project red5-server-common by Red5.

the class RTMPConnection method invoke.

/**
 * {@inheritDoc}
 */
public void invoke(String method, Object[] params, IPendingServiceCallback callback) {
    IPendingServiceCall call = new PendingCall(method, params);
    if (callback != null) {
        call.registerCallback(callback);
    }
    invoke(call);
}
Also used : IPendingServiceCall(org.red5.server.api.service.IPendingServiceCall) PendingCall(org.red5.server.service.PendingCall)

Example 3 with IPendingServiceCall

use of org.red5.server.api.service.IPendingServiceCall in project red5-server-common by Red5.

the class RTMPConnection method invoke.

/**
 * {@inheritDoc}
 */
public void invoke(IServiceCall call, int channel) {
    // if play or publish update our chunk sizes
    if ("playpublish".contains(call.getServiceMethodName())) {
        // get chunk size we'll write
        final int chunkSize = Red5.getTargetChunkSize();
        // register a callback for chunksize if we're greater than 128 (default)
        if (chunkSize > 128) {
            log.debug("Setting chunk sizes to {}", chunkSize);
            state.setReadChunkSize(chunkSize);
            state.setWriteChunkSize(chunkSize);
            // inform the server we'll be expecting larger chunk sizes
            ChunkSize chunkSizeMessage = new ChunkSize(chunkSize);
            log.debug("Sending chunksize: {}", chunkSizeMessage);
            getChannel(2).write(chunkSizeMessage);
        }
    }
    // We need to use Invoke for all calls to the client
    Invoke invoke = new Invoke();
    invoke.setCall(call);
    invoke.setTransactionId(getTransactionId());
    if (call instanceof IPendingServiceCall) {
        registerPendingCall(invoke.getTransactionId(), (IPendingServiceCall) call);
    }
    getChannel(channel).write(invoke);
}
Also used : ChunkSize(org.red5.server.net.rtmp.event.ChunkSize) IPendingServiceCall(org.red5.server.api.service.IPendingServiceCall) Invoke(org.red5.server.net.rtmp.event.Invoke)

Example 4 with IPendingServiceCall

use of org.red5.server.api.service.IPendingServiceCall in project red5-client by Red5.

the class StreamRelay method main.

/**
 * Creates a stream client to consume a stream from an end point and a proxy to relay the stream to another end point.
 *
 * @param args
 *            application arguments
 */
public static void main(String... args) {
    // handle the args
    if (args == null || args.length < 7) {
        System.out.println("Not enough args supplied. Usage: <source uri> <source app> <source stream name> <destination uri> <destination app> <destination stream name> <publish mode>");
    } else {
        // parse the args
        String sourceHost = args[0], destHost = args[3];
        String sourceApp = args[1], destApp = args[4];
        int sourcePort = 1935, destPort = 1935;
        sourceStreamName = args[2];
        String destStreamName = args[5];
        // live, record, or append
        String publishMode = args[6];
        // look to see if port was included in host string
        int colonIdx = sourceHost.indexOf(':');
        if (colonIdx > 0) {
            sourcePort = Integer.valueOf(sourceHost.substring(colonIdx + 1));
            sourceHost = sourceHost.substring(0, colonIdx);
            System.out.printf("Source host: %s port: %d\n", sourceHost, sourcePort);
        }
        colonIdx = destHost.indexOf(':');
        if (colonIdx > 0) {
            destPort = Integer.valueOf(destHost.substring(colonIdx + 1));
            destHost = destHost.substring(0, colonIdx);
            System.out.printf("Destination host: %s port: %d\n", destHost, destPort);
        }
        // create a timer
        timer = new Timer();
        // create our publisher
        proxy = new StreamingProxy();
        proxy.setHost(destHost);
        proxy.setPort(destPort);
        proxy.setApp(destApp);
        proxy.init();
        proxy.setConnectionClosedHandler(new Runnable() {

            @Override
            public void run() {
                System.out.println("Publish connection has been closed, source will be disconnected");
                client.disconnect();
            }
        });
        proxy.setExceptionHandler(new ClientExceptionHandler() {

            @Override
            public void handleException(Throwable throwable) {
                throwable.printStackTrace();
                System.exit(2);
            }
        });
        proxy.start(destStreamName, publishMode, new Object[] {});
        // wait for the publish state
        do {
            try {
                Thread.sleep(100L);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        } while (!proxy.isPublished());
        System.out.println("Publishing...");
        // create the consumer
        client = new RTMPClient();
        client.setStreamEventDispatcher(new StreamEventDispatcher());
        client.setStreamEventHandler(new INetStreamEventHandler() {

            @Override
            public void onStreamEvent(Notify notify) {
                System.out.printf("onStreamEvent: %s\n", notify);
                ObjectMap<?, ?> map = (ObjectMap<?, ?>) notify.getCall().getArguments()[0];
                String code = (String) map.get("code");
                System.out.printf("<:%s\n", code);
                if (StatusCodes.NS_PLAY_STREAMNOTFOUND.equals(code)) {
                    System.out.println("Requested stream was not found");
                    client.disconnect();
                } else if (StatusCodes.NS_PLAY_UNPUBLISHNOTIFY.equals(code) || StatusCodes.NS_PLAY_COMPLETE.equals(code)) {
                    System.out.println("Source has stopped publishing or play is complete");
                    client.disconnect();
                }
            }
        });
        client.setConnectionClosedHandler(new Runnable() {

            @Override
            public void run() {
                System.out.println("Source connection has been closed, proxy will be stopped");
                proxy.stop();
            }
        });
        client.setExceptionHandler(new ClientExceptionHandler() {

            @Override
            public void handleException(Throwable throwable) {
                throwable.printStackTrace();
                System.exit(1);
            }
        });
        // connect the consumer
        Map<String, Object> defParams = client.makeDefaultConnectionParams(sourceHost, sourcePort, sourceApp);
        // add pageurl and swfurl
        defParams.put("pageUrl", "");
        defParams.put("swfUrl", "app:/Red5-StreamRelay.swf");
        // indicate for the handshake to generate swf verification data
        client.setSwfVerification(true);
        // connect the client
        client.connect(sourceHost, sourcePort, defParams, new IPendingServiceCallback() {

            @Override
            public void resultReceived(IPendingServiceCall call) {
                System.out.println("connectCallback");
                ObjectMap<?, ?> map = (ObjectMap<?, ?>) call.getResult();
                String code = (String) map.get("code");
                if ("NetConnection.Connect.Rejected".equals(code)) {
                    System.out.printf("Rejected: %s\n", map.get("description"));
                    client.disconnect();
                    proxy.stop();
                } else if ("NetConnection.Connect.Success".equals(code)) {
                    // 1. Wait for onBWDone
                    timer.schedule(new BandwidthStatusTask(), 2000L);
                } else {
                    System.out.printf("Unhandled response code: %s\n", code);
                }
            }
        });
        // keep sleeping main thread while the proxy runs
        do {
            try {
                Thread.sleep(100L);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        } while (!proxy.isRunning());
        // kill the timer
        // timer.cancel();
        System.out.println("Stream relay exit");
    }
}
Also used : IPendingServiceCallback(org.red5.server.api.service.IPendingServiceCallback) Notify(org.red5.server.net.rtmp.event.Notify) INetStreamEventHandler(org.red5.client.net.rtmp.INetStreamEventHandler) IPendingServiceCall(org.red5.server.api.service.IPendingServiceCall) RTMPClient(org.red5.client.net.rtmp.RTMPClient) StreamingProxy(org.red5.proxy.StreamingProxy) Timer(java.util.Timer) ClientExceptionHandler(org.red5.client.net.rtmp.ClientExceptionHandler) ObjectMap(org.red5.io.utils.ObjectMap)

Example 5 with IPendingServiceCall

use of org.red5.server.api.service.IPendingServiceCall in project red5-server by Red5.

the class FlexMessagingService method handleRequest.

/**
 * Handle request coming from
 *
 * <pre>
 * mx:RemoteObject
 * </pre>
 *
 * tags.
 *
 * @see <a href="http://livedocs.adobe.com/flex/2/langref/mx/rpc/remoting/mxml/RemoteObject.html">Adobe Livedocs (external)</a>
 *
 * @param msg
 *            message
 * @return aynsc message
 */
public AsyncMessage handleRequest(RemotingMessage msg) {
    log.debug("Handle RemotingMessage request");
    log.trace("{}", msg);
    setClientId(msg);
    if (serviceInvoker == null) {
        log.error("No service invoker configured: {}", msg);
        return returnError(msg, "Server.Invoke.Error", "No service invoker configured.", "No service invoker configured.");
    }
    Object endpoint = endpoints.get(msg.destination);
    log.debug("End point / destination: {}", endpoint);
    if (endpoint == null) {
        String errMsg = String.format("Endpoint %s doesn't exist.", msg.destination);
        log.debug("{} ({})", errMsg, msg);
        return returnError(msg, "Server.Invoke.Error", errMsg, errMsg);
    }
    // prepare an ack message
    AcknowledgeMessage result = new AcknowledgeMessage();
    result.setClientId(msg.getClientId());
    result.setCorrelationId(msg.getMessageId());
    // grab any headers
    Map<String, Object> headers = msg.getHeaders();
    log.debug("Headers: {}", headers);
    // if (headers.containsKey(Message.FLEX_CLIENT_ID_HEADER)) {
    // headers.put(Message.FLEX_CLIENT_ID_HEADER, msg.getClientId());
    // }
    // result.setHeaders(headers);
    // get the operation
    String operation = msg.operation;
    log.debug("Operation: {}", operation);
    if (endpoint instanceof ServiceAdapter) {
        log.debug("Endpoint is a ServiceAdapter so message will be invoked");
        ServiceAdapter adapter = (ServiceAdapter) endpoint;
        // the result of the invocation will make up the message body
        result.body = adapter.invoke(msg);
    } else {
        // get arguments
        Object[] args = null;
        try {
            log.debug("Body: {} type: {}", msg.body, msg.body.getClass().getName());
            args = (Object[]) ConversionUtils.convert(msg.body, Object[].class);
        } catch (ConversionException cex) {
            // if the conversion fails and the endpoint is not a ServiceAdapter
            // just drop the object directly into an array
            args = new Object[] { msg.body };
        }
        IPendingServiceCall call = new PendingCall(operation, args);
        try {
            if (!serviceInvoker.invoke(call, endpoint)) {
                if (call.getException() != null) {
                    // Use regular exception handling
                    Throwable err = call.getException();
                    return returnError(msg, "Server.Invoke.Error", err.getMessage(), err);
                }
                return returnError(msg, "Server.Invoke.Error", "Can't invoke method.", "");
            }
        } catch (Throwable err) {
            log.error("Error while invoking method.", err);
            return returnError(msg, "Server.Invoke.Error", err.getMessage(), err);
        }
        // we got a valid result from the method call.
        result.body = call.getResult();
    }
    return result;
}
Also used : ConversionException(org.apache.commons.beanutils.ConversionException) AcknowledgeMessage(org.red5.compatibility.flex.messaging.messages.AcknowledgeMessage) IPendingServiceCall(org.red5.server.api.service.IPendingServiceCall) ServiceAdapter(org.red5.server.messaging.ServiceAdapter) PendingCall(org.red5.server.service.PendingCall)

Aggregations

IPendingServiceCall (org.red5.server.api.service.IPendingServiceCall)15 ObjectMap (org.red5.io.utils.ObjectMap)7 IPendingServiceCallback (org.red5.server.api.service.IPendingServiceCallback)6 Invoke (org.red5.server.net.rtmp.event.Invoke)6 IServiceCall (org.red5.server.api.service.IServiceCall)5 Notify (org.red5.server.net.rtmp.event.Notify)5 Test (org.junit.Test)3 IEventDispatcher (org.red5.server.api.event.IEventDispatcher)3 RTMPConnection (org.red5.server.net.rtmp.RTMPConnection)3 StatusObject (org.red5.server.net.rtmp.status.StatusObject)3 Map (java.util.Map)2 ClientExceptionHandler (org.red5.client.net.rtmp.ClientExceptionHandler)2 Output (org.red5.io.object.Output)2 IEvent (org.red5.server.api.event.IEvent)2 IClientSharedObject (org.red5.server.api.so.IClientSharedObject)2 PendingCall (org.red5.server.service.PendingCall)2 InvocationTargetException (java.lang.reflect.InvocationTargetException)1 Method (java.lang.reflect.Method)1 ByteBuffer (java.nio.ByteBuffer)1 HashMap (java.util.HashMap)1