Class BroadcastSession

  • All Implemented Interfaces:
    Releasable

    public class BroadcastSession
    extends java.lang.Object
    implements Releasable
    BroadcastSession is the primary interaction point with the IVS Broadcast SDK. You must create a BroadcastSession in order to begin broadcasting.
    • Constructor Detail

      • BroadcastSession

        public BroadcastSession​(@NonNull
                                android.content.Context ctx,
                                @Nullable
                                BroadcastSession.Listener listener,
                                @NonNull
                                BroadcastConfiguration configuration,
                                @Nullable
                                Device.Descriptor[] startDevices)
        Create a BroadcastSession object that can stream to an IVS endpoint via RTMPS. You must interact with the Broadcast Session from the thread you create it on. If initialization fails, Session.isReady() will return false and an error will be emitted to the provided BroadcastSession.Listener.onError(BroadcastException) callback.
        Parameters:
        ctx - the current Application context
        listener - a BroadcastSession.Listener object
        configuration - a Broadcast configuration, either one of the Presets.Configuration or a custom configuration.
        startDevices - an optional list of devices to instantiate immediately. To get a list of devices see Session.listAvailableDevices(android.content.Context)
    • Method Detail

      • getVersion

        @NonNull
        public static java.lang.String getVersion()
        Returns:
        the Broadcast SDK version string
      • start

        public void start​(java.lang.String url,
                          java.lang.String streamKey)
        Start the configured broadcast session
        Parameters:
        url - the RTMPS endpoint provided by IVS.
        streamKey - the broadcaster's stream key that has been provided by IVS.
        Throws:
        BroadcastException - if the session is not ready (see Session.isReady())
        BroadcastException - if the provided url contains an unsupported scheme
      • stop

        public void stop()
        Stop the broadcast session, but do not deallocate resources. This operation is asynchronous. When it completes BroadcastSession.State.DISCONNECTED will be emitted by BroadcastSession.Listener.onStateChanged(State). If Session.release() is called before this operation completes, the call to release will block until this operation completes, or the timeout is reached. This is required to properly terminate the current broadcast, otherwise the broadcast may remain live beyond the expected lifecycle. Because of the synchronous nature of calling release during a stop operation, is it recommended to wait for the disconnected state change.
      • recommendedVideoSettings

        @Nullable
        public BroadcastSessionTest recommendedVideoSettings​(java.lang.String url,
                                                             java.lang.String streamKey,
                                                             double duration,
                                                             TypedLambda<BroadcastSessionTest.Result> onNewResult)
        This will perform a network test and provide recommendations for video configurations. It will not publish live video, it will only test the connection quality. The callback will be called periodically and provide you with a status, progress, and continuously updated recommendations. The longer the test runs the more refined the suggestions will be, however you can cancel the test at any time and make use of previous recommendations. But these recommendations might not be as stable, or as high quality as a fully completed test. This can not be called while an existing broadcast is in progress, and a new broadcast can not be started while a test is in progress.
        Parameters:
        url - the RTMPS endpoint provided by IVS.
        streamKey - the broadcaster's stream key that has been provided by IVS.
        duration - how long to run the test for. It's recommended the test runs for at least 8 seconds, and the minimum is 3 seconds. The test can always be cancelled early.
        onNewResult - a block that will be called periodically providing you with an update on the test's progress and recommendations.
        Returns:
        a handle to the network test, providing you a way to cancel it, or `null` if there is an error starting the test.
      • sendTimedMetadata

        public boolean sendTimedMetadata​(@NonNull
                                         java.lang.String contents)
        Send timed metadata that will be automatically synchronized with the ongoing stream.
        Parameters:
        contents - Text-based metadata that will be interpreted by your receiver
        Returns:
        true on success or false if the session is not connected
      • listAvailableDevices

        public static Device.Descriptor[] listAvailableDevices​(android.content.Context context)
        List available devices for use with the BroadcastSession.
        Parameters:
        context - the current Application context
        Returns:
        an array of Device.Descriptors representing attached devices such as cameras, microphones, and screen recording sessions.
      • isReady

        public boolean isReady()
        This state will be set once the session has been instantiated and will not change. So if, after instantiating the BroadcastSession isReady is TRUE, it will continue to be true. If this method returns FALSE, be sure to assign a listener in the BroadcastSession constructor so that you receive the relevant error.
        Returns:
        whether or not the session is ready for use.
      • listAttachedDevices

        public java.util.List<Device> listAttachedDevices()
        List attached, active devices being used with the BroadcastSession
        Returns:
        a list of Device
      • attachDevice

        public void attachDevice​(@NonNull
                                 Device.Descriptor descriptor,
                                 boolean bindToPreference,
                                 @Nullable
                                 TypedLambda<Device> onComplete)
        Asynchronously attach and open a device for use with the broadcast session
        Parameters:
        descriptor - The device descriptor for the device to be attached
        bindToPreference - Automatically bind to a slot with a preferred input device type that matches this device type. Defining multiple slots with the same preferred device type may result in unexpected behavior.
        onComplete - An optional task that will be run upon completion of attaching and opening the device. This task will be run on the main thread and will have a single parameter that passes the created device. For example, attachDevice(descriptor, device -> { Log.d("Example", "Attached %s", device.friendlyName); }); This task will not be invoked if the session is released while the device is being attached, or if the device failed to be attached.
        Throws:
        BroadcastException - if the Device.Descriptor is not correct or in a valid state
        BroadcastException - if the session is not ready (see Session.isReady())
      • attachDevice

        public void attachDevice​(@NonNull
                                 Device.Descriptor descriptor,
                                 @Nullable
                                 TypedLambda<Device> onComplete)
        Asynchronously attach and open a device for use with the broadcast session. If there is a mixer slot with a device type preference that matches this device type it will be bound automatically. Be aware that defining multiple slots with the same preferred device type may result in unexpected behavior.
        Parameters:
        descriptor - The device descriptor for the device to be attached
        onComplete - An optional task that will be run upon completion of attaching and opening the device. This task will be run on the main thread and will have a single parameter that passes the created device. For example, attachDevice(descriptor, device -> { Log.d("Example", "Attached %s", device.friendlyName); }); This task will not be invoked if the session is released while the device is being attached, or if the device fails to be attached.
        Throws:
        BroadcastException - if the Device.Descriptor is not correct or in a valid state
        BroadcastException - if the session is not ready (see Session.isReady())
      • attachDevice

        public void attachDevice​(@NonNull
                                 Device device)
        Asynchronously attach a device for use with the broadcast session. If there is a mixer slot with a device type preference that matches this device type it will be bound automatically. Be aware that defining multiple slots with the same preferred device type may result in unexpected behavior.
        Parameters:
        device - The device to be attached
        Throws:
        BroadcastException - if the Device is not correct or in a valid state
        BroadcastException - if the session is not ready (see Session.isReady())
      • attachDevice

        public void attachDevice​(@NonNull
                                 Device.Descriptor descriptor)
        Asynchronously attach and open a device for use with the broadcast session. If you wish to be notified of completion, see the other override for attachDevice or Session.awaitDeviceChanges(java.lang.Runnable)
        Parameters:
        descriptor - The device descriptor for the device to be attached
        Throws:
        BroadcastException - if the Device.Descriptor is not correct or in a valid state
        BroadcastException - if the session is not ready (see Session.isReady())
      • detachDevice

        public void detachDevice​(@NonNull
                                 Device.Descriptor toRemove)
        Close and detach a device
        Parameters:
        toRemove - The descriptor for the device to close.
      • detachDevice

        public void detachDevice​(@NonNull
                                 Device device)
      • awaitDeviceChanges

        public void awaitDeviceChanges​(java.lang.Runnable task)
        Run a task upon the completion of pending device attachments or detachments. This can be used as an alternative to including tasks with individual device changes if you wish to perform multiple changes at once.
        Parameters:
        task - The task to be run when device changes have been completed. This task will be run on the main thread. This task will not be invoked if the session is released while the device is being attached.
      • exchangeDevices

        public void exchangeDevices​(Device old,
                                    Device.Descriptor next,
                                    @Nullable
                                    TypedLambda<Device> onComplete)
        Exchange a device with another device of the same type
        Parameters:
        old - The device to replace
        next - The descriptor of the new device to attach and open
        onComplete - an optional lambda to be run on completion
        Throws:
        BroadcastException - if the session is not ready (see Session.isReady())
        BroadcastException - if the device types don't match
        BroadcastException - if the old device is not currently attached
      • createImageInputSource

        public SurfaceSource createImageInputSource()
        Create an image input for a custom source. This should only be used if you intend to generate and feed image data to the SDK manually. Custom sources created using this API are only compatible with this BroadcastSession instance and cannot be attached to a Stage.
        Returns:
        An SurfaceSource that represents as Surface and can receive your samples.
        Throws:
        BroadcastException - if the session is not ready (see Session.isReady())
        BroadcastException - if creating the image input source failed
      • createAudioInputSource

        public AudioDevice createAudioInputSource​(int channels,
                                                  BroadcastConfiguration.AudioSampleRate sampleRate,
                                                  AudioDevice.Format format)
        Create an audio input for a custom source. This should only be used if you intend to generate and feed pcm audio data to the SDK manually. Custom sources created using this API are only compatible with this BroadcastSession instance and cannot be attached to a Stage.
        Parameters:
        channels - The number of audio channels.
        sampleRate - The sampling rate for the PCM audio.
        format - The sample format.
        Returns:
        An AudioDevice that represents as Surface and can receive your samples.
        Throws:
        BroadcastException - if the session is not ready (see Session.isReady())
        BroadcastException - if the parameters are invalid
      • getPreviewView

        public ImagePreviewView getPreviewView()
        Gets a ImagePreviewView that will display a preview of the composited stream being produced by the SDK. This will include all mixer slots, fill colors, etc. Use getPreviewSurfaceView() if you can, it has better performance. Warning: Using many previews at once may result in performance degradation.
        Returns:
        A preview of the composited image stream.
        Throws:
        BroadcastException - If unable to get the preview.
      • getPreviewSurfaceView

        public ImagePreviewSurfaceView getPreviewSurfaceView()
        Gets a ImagePreviewSurfaceView that will display a preview of the composited stream being produced by the SDK. This will include all mixer slots, fill colors, etc. It has better performance than the default ImagePreviewView so please use it if you can. Warning: Using many previews at once may result in performance degradation.
        Returns:
        A preview of the composited image stream.
        Throws:
        BroadcastException - If unable to get the preview.
      • getPreviewSurfaceView

        public ImagePreviewSurfaceView getPreviewSurfaceView​(BroadcastConfiguration.AspectMode aspectMode)
        Gets a ImagePreviewSurfaceView that will display a preview of the composited stream being produced by the SDK. This will include all mixer slots, fill colors, etc. It has better performance than the default ImagePreviewView so please use it if you can. Warning: Using many previews at once may result in performance degradation.
        Parameters:
        aspectMode - The aspect mode the preview view should be in.
        Returns:
        A preview of the composited image stream.
        Throws:
        BroadcastException - If unable to get the preview.
      • getPreviewTextureView

        public ImagePreviewView getPreviewTextureView()
        Gets a ImagePreviewView that will display a preview of the composited stream being produced by the SDK. This will include all mixer slots, fill colors, etc. Use getPreviewSurfaceView() if you can, it has better performance. Warning: Using many previews at once may result in performance degradation.
        Returns:
        A preview of the composited image stream.
        Throws:
        BroadcastException - If unable to get the preview.
      • getMixer

        public Mixer getMixer()
        Returns:
        The session mixer instance. This allows you to control on-screen elements.
      • release

        public void release()
        Release BroadcastSession resources. If a call to stop() is still in progress, this call to release will block until the stop operation completes, or the timeout is reached. This is required to properly terminate the current broadcast, otherwise the broadcast may remain live beyond the expected lifecycle. Because of the synchronous nature of calling release during a stop operation, is it recommended to wait for the disconnected state change after calling stop.
      • createSystemCaptureSources

        public void createSystemCaptureSources​(android.content.Intent permissionGrantedIntent,
                                               java.lang.Class<?> serviceClass,
                                               @Nullable
                                               android.app.Notification notification,
                                               @Nullable
                                               TypedLambda<java.util.List<Device>> onComplete)
        This allows you to create an ImageDevice that can be used to capture the Android device's screen and an AudioDevice that can capture the Android device's audio (API 29 and above only). Calling this will launch a foreground service for your app. Implementers will need to call https://developer.android.com/reference/android/media/projection/MediaProjectionManager#createScreenCaptureIntent() and obtain a permission granted intent from the user in order to capture the screen or audio. That intent must be passed into this function. Implementers must add the following permission to their app manifest: <uses-permission android:name="android.permission.FOREGROUND_SERVICE" /> and you must also add the following service specification, replacing ExampleSystemCaptureService with your service class: <service android:name=".ExampleSystemCaptureService" android:foregroundServiceType="mediaProjection" android:isolatedProcess="false" /> This service must extend SystemCaptureService.
        Parameters:
        permissionGrantedIntent - An intent that gives user permission to capture the screen
        serviceClass - A class that extends SystemCaptureService
        notification - A notification that will be displayed during the lifetime of the foreground service. You can use Session.createServiceNotificationBuilder(java.lang.String, java.lang.String, android.content.Intent) to provide a NotificationBuilder that should be customized. The notification is only required for Android API 26 and newer.
        onComplete - An optional lambda that will receive the created screen capture and audio capture devices.
      • stopSystemCapture

        public void stopSystemCapture()
        Stop the system capture foreground service launched by createSystemCaptureSources(...) by unbinding the service, if it exists.
      • createSystemAudioSource

        @RequiresApi(api=29)
        public void createSystemAudioSource​(android.media.projection.MediaProjection projection,
                                            @Nullable
                                            TypedLambda<java.util.List<Device>> onComplete)
      • createServiceNotificationBuilder

        @RequiresApi(api=26)
        public android.app.Notification.Builder createServiceNotificationBuilder​(java.lang.String channelId,
                                                                                 java.lang.String friendlyName,
                                                                                 android.content.Intent notificationIntent)
        Create a notification builder that can create a persistent notification compatible with the MediaProjection API
        Parameters:
        channelId - The identifier for the notification channel to be created, for example "ivs_notifications".
        friendlyName - The friendly name for the channel to be created, for example "IVS Broadcast Service".
        notificationIntent - The notification content activity.
        Returns:
        A notification.builder that can be completed, for example: createServiceNotificationBuilder("ivs_notifications", "IVS BroadcastService", new Intent(context, activity)) .setContentText("Test text") .setContentTitle("Test title") .build();
      • getSessionId

        @NonNull
        public java.lang.String getSessionId()
        Returns:
        A unique identifier for the session. The session identifier can be shared with support or displayed in a user interface to help troubleshoot or diagnose issues.
      • isReady

        protected boolean isReady​(long handle)