Package com.amazonaws.ivs.broadcast
Class BroadcastSession
- java.lang.Object
-
- com.amazonaws.ivs.broadcast.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.Note that the first time you use this class (either to create a BroadcastSession object or to access one of its static methods), you must ensure that you are not asynchronously accessing one of the following classes at the same time: Device, DeviceDiscovery or (if using Stages) Stage or StageAudioManager. Otherwise there is a risk of deadlock due to loading the underlying native library.
-
-
Nested Class Summary
Nested Classes Modifier and Type Class Description static class
BroadcastSession.Listener
Provide a listener to receive status updates and errors from the SDK.static class
BroadcastSession.RetryState
A value representing theBroadcastSession
retry state.static class
BroadcastSession.State
-
Constructor Summary
Constructors Constructor Description BroadcastSession(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
All Methods Static Methods Instance Methods Concrete Methods Modifier and Type Method Description void
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(java.lang.Runnable task)
Run a task upon the completion of pending device attachments or detachments.AudioDevice
createAudioInputSource(int channels, BroadcastConfiguration.AudioSampleRate sampleRate, AudioDevice.Format format)
Create an audio input for a custom source.SurfaceSource
createImageInputSource()
Create an image input for a custom source.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 APIvoid
createSystemAudioSource(android.media.projection.MediaProjection projection, TypedLambda<java.util.List<Device>> onComplete)
void
createSystemCaptureSources(android.content.Intent permissionGrantedIntent, java.lang.Class<?> serviceClass, android.app.Notification notification, TypedLambda<java.util.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 typeMixer
getMixer()
ImagePreviewSurfaceView
getPreviewSurfaceView()
Gets aImagePreviewSurfaceView
that will display a preview of the composited stream being produced by the SDK.ImagePreviewSurfaceView
getPreviewSurfaceView(BroadcastConfiguration.AspectMode aspectMode)
Gets aImagePreviewSurfaceView
that will display a preview of the composited stream being produced by the SDK.ImagePreviewView
getPreviewTextureView()
Gets aImagePreviewView
that will display a preview of the composited stream being produced by the SDK.ImagePreviewView
getPreviewTextureView(BroadcastConfiguration.AspectMode aspectMode)
Gets aImagePreviewView
that will display a preview of the composited stream being produced by the SDK.ImagePreviewView
getPreviewView()
Gets aImagePreviewView
that will display a preview of the composited stream being produced by the SDK.ImagePreviewView
getPreviewView(BroadcastConfiguration.AspectMode aspectMode)
Gets aImagePreviewView
that will display a preview of the composited stream being produced by the SDK.java.lang.String
getSessionId()
static java.lang.String
getVersion()
boolean
isReady()
This state will be set once the session has been instantiated and will not change.protected boolean
isReady(long handle)
java.util.List<Device>
listAttachedDevices()
List attached, active devices being used with the BroadcastSessionstatic Device.Descriptor[]
listAvailableDevices(android.content.Context context)
List available devices for use with the BroadcastSession.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.BroadcastSessionTest
recommendedVideoSettings(java.lang.String url, java.lang.String streamKey, TypedLambda<BroadcastSessionTest.Result> onNewResult)
Runs a network test with a default duration of 8 seconds.void
release()
Release BroadcastSession resources.boolean
sendTimedMetadata(java.lang.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(java.lang.String url, java.lang.String streamKey)
Start the configured broadcast sessionvoid
stop()
Stop the broadcast session, but do not deallocate resources.void
stopSystemCapture()
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 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 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 Detail
-
getVersion
@NonNull public static java.lang.String getVersion()
- Returns:
- the Broadcast SDK version string
-
setListener
public void setListener(BroadcastSession.Listener listener)
Set the callback to receive state, error, and analytics data- Parameters:
listener
- aBroadcastSession.Listener
object
-
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 (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(java.lang.String url, java.lang.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(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.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
public void setLogLevel(BroadcastConfiguration.LogLevel logLevel)
Logging level for the broadcast session. Default is `ERROR`.
-
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 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
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 theDevice
is not correct or in a valid stateBroadcastException
- if the session is not ready (seeSession.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 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
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 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
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 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
public ImagePreviewView 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
public ImagePreviewView getPreviewView(BroadcastConfiguration.AspectMode aspectMode)
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
public ImagePreviewSurfaceView 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
public ImagePreviewSurfaceView getPreviewSurfaceView(BroadcastConfiguration.AspectMode aspectMode)
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
public ImagePreviewView 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
public ImagePreviewView getPreviewTextureView(BroadcastConfiguration.AspectMode aspectMode)
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
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 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, java.lang.Class<?> serviceClass, @Nullable android.app.Notification notification, @Nullable TypedLambda<java.util.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<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)
-
-