Package com.amazonaws.ivs.broadcast
Class BroadcastSession
java.lang.Object
com.amazonaws.ivs.broadcast.BroadcastSession
- All Implemented Interfaces:
Releasable
BroadcastSession is the primary interaction point with the IVS Broadcast SDK. You must create a BroadcastSession
in order to begin broadcasting.
-
Nested Class Summary
Modifier and TypeClassDescriptionstatic class
Provide a listener to receive status updates and errors from the SDK.static enum
A value representing theBroadcastSession
retry state.static enum
-
Constructor Summary
ConstructorDescriptionBroadcastSession
(android.content.Context ctx, BroadcastSession.Listener listener, BroadcastConfiguration configuration, Device.Descriptor[] startDevices) Create a BroadcastSession object that can stream to an IVS endpoint via RTMPS. -
Method Summary
Modifier and TypeMethodDescriptionvoid
attachDevice
(Device device) Asynchronously attach a device for use with the broadcast session.void
attachDevice
(Device.Descriptor descriptor) Asynchronously attach and open a device for use with the broadcast session.void
attachDevice
(Device.Descriptor descriptor, boolean bindToPreference, TypedLambda<Device> onComplete) Asynchronously attach and open a device for use with the broadcast sessionvoid
attachDevice
(Device.Descriptor descriptor, TypedLambda<Device> onComplete) Asynchronously attach and open a device for use with the broadcast session.void
awaitDeviceChanges
(Runnable task) Run a task upon the completion of pending device attachments or detachments.createAudioInputSource
(int channels, BroadcastConfiguration.AudioSampleRate sampleRate, AudioDevice.Format format) Create an audio input for a custom source.Create an image input for a custom source.android.app.Notification.Builder
createServiceNotificationBuilder
(String channelId, String friendlyName, android.content.Intent notificationIntent) Create a notification builder that can create a persistent notification compatible with the MediaProjection APIvoid
createSystemAudioSource
(android.media.projection.MediaProjection projection, TypedLambda<List<Device>> onComplete) Creates an audio capture device for capturing the system audiovoid
createSystemCaptureSources
(android.content.Intent permissionGrantedIntent, Class<?> serviceClass, android.app.Notification notification, TypedLambda<List<Device>> onComplete) This allows you to create anImageDevice
that can be used to capture the Android device's screen and anAudioDevice
that can capture the Android device's audio (API 29 and above only).void
detachDevice
(Device device) void
detachDevice
(Device.Descriptor toRemove) Close and detach a devicevoid
exchangeDevices
(Device.Descriptor old, Device.Descriptor next, TypedLambda<Device> onComplete) void
exchangeDevices
(Device old, Device.Descriptor next, TypedLambda<Device> onComplete) Exchange a device with another device of the same typegetMixer()
Gets aImagePreviewSurfaceView
that will display a preview of the composited stream being produced by the SDK.Gets aImagePreviewSurfaceView
that will display a preview of the composited stream being produced by the SDK.Gets aImagePreviewView
that will display a preview of the composited stream being produced by the SDK.Gets aImagePreviewView
that will display a preview of the composited stream being produced by the SDK.Gets aImagePreviewView
that will display a preview of the composited stream being produced by the SDK.getPreviewView
(BroadcastConfiguration.AspectMode aspectMode) Gets aImagePreviewView
that will display a preview of the composited stream being produced by the SDK.static String
boolean
isReady()
This state will be set once the session has been instantiated and will not change.protected boolean
isReady
(long handle) List attached, active devices being used with the BroadcastSessionstatic Device.Descriptor[]
listAvailableDevices
(android.content.Context context) List available devices for use with the BroadcastSession.recommendedVideoSettings
(String url, String streamKey, double duration, TypedLambda<BroadcastSessionTest.Result> onNewResult) This will perform a network test and provide recommendations for video configurations.recommendedVideoSettings
(String url, String streamKey, TypedLambda<BroadcastSessionTest.Result> onNewResult) Runs a network test with a default duration of 8 seconds.void
release()
Release BroadcastSession resources.boolean
sendTimedMetadata
(String contents) Send timed metadata that will be automatically synchronized with the ongoing stream.void
setListener
(BroadcastSession.Listener listener) Set the callback to receive state, error, and analytics datavoid
setLogLevel
(BroadcastConfiguration.LogLevel logLevel) Logging level for the broadcast session.void
Start the configured broadcast sessionvoid
stop()
Stop the broadcast session, but do not deallocate resources.void
Stop the system capture foreground service launched bycreateSystemCaptureSources(...)
by unbinding the service, if it exists.Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
Methods inherited from interface com.amazonaws.ivs.broadcast.Releasable
release
-
Constructor Details
-
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 providedBroadcastSession.Listener.onError(BroadcastException)
callback.- Parameters:
ctx
- the current Application contextlistener
- aBroadcastSession.Listener
objectconfiguration
- a Broadcast configuration, either one of thePresets.Configuration
or a custom configuration.startDevices
- an optional list of devices to instantiate immediately. To get a list of devices seeSession.listAvailableDevices(android.content.Context)
-
-
Method Details
-
getVersion
- Returns:
- the Broadcast SDK version string
-
setListener
Set the callback to receive state, error, and analytics data- Parameters:
listener
- aBroadcastSession.Listener
object
-
start
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 (seeSession.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 completesBroadcastSession.State.DISCONNECTED
will be emitted byBroadcastSession.Listener.onStateChanged(State)
. IfSession.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(String url, String streamKey, TypedLambda<BroadcastSessionTest.Result> onNewResult) Runs a network test with a default duration of 8 seconds.recommendedVideoSettings(String, String, double, TypedLambda)
-
recommendedVideoSettings
@Nullable public BroadcastSessionTest recommendedVideoSettings(String url, 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
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
List available devices for use with the BroadcastSession.- Parameters:
context
- the current Application context- Returns:
- an array of
Device.Descriptor
s 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.
-
setLogLevel
Logging level for the broadcast session. Default is `ERROR`. -
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 attachedbindToPreference
- 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 theDevice.Descriptor
is not correct or in a valid stateBroadcastException
- if the session is not ready (seeSession.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 attachedonComplete
- 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 theDevice.Descriptor
is not correct or in a valid stateBroadcastException
- if the session is not ready (seeSession.isReady()
)
-
attachDevice
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 theDevice
is not correct or in a valid stateBroadcastException
- if the session is not ready (seeSession.isReady()
)
-
attachDevice
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 orSession.awaitDeviceChanges(java.lang.Runnable)
- Parameters:
descriptor
- The device descriptor for the device to be attached- Throws:
BroadcastException
- if theDevice.Descriptor
is not correct or in a valid stateBroadcastException
- if the session is not ready (seeSession.isReady()
)
-
detachDevice
Close and detach a device- Parameters:
toRemove
- The descriptor for the device to close.
-
detachDevice
-
awaitDeviceChanges
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 replacenext
- The descriptor of the new device to attach and openonComplete
- an optional lambda to be run on completion- Throws:
BroadcastException
- if the session is not ready (seeSession.isReady()
)BroadcastException
- if the device types don't matchBroadcastException
- if the old device is not currently attached
-
exchangeDevices
public void exchangeDevices(Device.Descriptor old, Device.Descriptor next, @Nullable TypedLambda<Device> onComplete) -
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 thisBroadcastSession
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 (seeSession.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 thisBroadcastSession
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 (seeSession.isReady()
)BroadcastException
- if the parameters are invalid
-
getPreviewView
Gets aImagePreviewView
that will display a preview of the composited stream being produced by the SDK. This will include all mixer slots, fill colors, etc. UsegetPreviewSurfaceView()
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.
-
getPreviewView
Gets aImagePreviewView
that will display a preview of the composited stream being produced by the SDK. This will include all mixer slots, fill colors, etc. UsegetPreviewSurfaceView(BroadcastConfiguration.AspectMode)
if you can, it has better performance. 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.
-
getPreviewSurfaceView
Gets aImagePreviewSurfaceView
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
Gets aImagePreviewSurfaceView
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
Gets aImagePreviewView
that will display a preview of the composited stream being produced by the SDK. This will include all mixer slots, fill colors, etc. UsegetPreviewSurfaceView()
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.
-
getPreviewTextureView
Gets aImagePreviewView
that will display a preview of the composited stream being produced by the SDK. This will include all mixer slots, fill colors, etc. UsegetPreviewSurfaceView(BroadcastConfiguration.AspectMode)
if you can, it has better performance. 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.
-
getMixer
- Returns:
- The session mixer instance. This allows you to control on-screen elements.
-
release
public void release()Release BroadcastSession resources. If a call tostop()
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, Class<?> serviceClass, @Nullable android.app.Notification notification, @Nullable TypedLambda<List<Device>> onComplete) This allows you to create anImageDevice
that can be used to capture the Android device's screen and anAudioDevice
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 extendSystemCaptureService
.- Parameters:
permissionGrantedIntent
- An intent that gives user permission to capture the screenserviceClass
- A class that extendsSystemCaptureService
notification
- A notification that will be displayed during the lifetime of the foreground service. You can useSession.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 bycreateSystemCaptureSources(...)
by unbinding the service, if it exists. -
createSystemAudioSource
@RequiresApi(api=29) public void createSystemAudioSource(android.media.projection.MediaProjection projection, @Nullable TypedLambda<List<Device>> onComplete) Creates an audio capture device for capturing the system audio- Parameters:
projection
- The media projectiononComplete
- The listener to call with created device, optional. If starting a system audio capture session fails for whatever reason, the listener will be called with an empty list.
-
createServiceNotificationBuilder
@RequiresApi(api=26) public android.app.Notification.Builder createServiceNotificationBuilder(String channelId, 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
- 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)
-