Class Broadcaster


  • public final class Broadcaster
    extends Object
    This is the main class and entry point to the library. The lowest supported API level is LOLLIPOP, Android 5.0.

    An app that uses this class must have at least the following Android permissions:
    CAMERA, RECORD_AUDIO and INTERNET.

    ACCESS_NETWORK_STATE and WAKE_LOCK are recommended. If available, the library will automatically acquire WifiLocks when appropriate, and will check network type when setResolution(width, height) is used.

    If the app wants to support broadcasting using bluetooth headsets, the following permissions should also be declared in the manifest:
    BLUETOOTH, MODIFY_AUDIO_SETTINGS and BROADCAST_STICKY.

    By default, the Broadcaster does not apply any rotation on the cameras. This implies the traditional landscape orientation on most devices, and the easiest way to get started is to lock the parent Activity screenOrientation to landscape. Support for other orientations, and cameras on some modern devices, require that the Activity supplies the proper rotation value through setRotation(displayRotation). Read the method documentation carefully.

    We recommend that the activity handles at least the "keyboard" configChanges, to avoid disconnection when the user expands a physical keyboard.

    • Method Detail

      • setCameraSurface

        public void setCameraSurface​(SurfaceView surface)
        Set the camera surface. This starts the camera. This should not be called earlier than onResume() in your Activity, as the camera may be unavailable before that. If the SurfaceView is an instance of SurfaceViewWithAutoAR, the camera will set the proper aspect ratio to the surface view and will start when the changes have applied. Make sure that a SurfaceViewWithAutoAR can resize itself within the parent layout (use WRAP_CONTENT), otherwise the camera will not start. If you use a generic SurfaceView, you need to manage its aspect ratio manually.
        Parameters:
        surface - A SurfaceViewWithAutoAR or generic SurfaceView that has been added to your UI layout.
      • setUplinkSpeedObserver

        public void setUplinkSpeedObserver​(Broadcaster.UplinkSpeedObserver obs)
        Set an uplink speed test observer. Provided that the Broadcaster has been constructed with an applicationId (see Broadcaster(activity, applicationId, observer)), the observer will receive results from automatic uplink speed tests every time the Broadcaster instance prepares itself for broadcasting. The speed test results can be used to decide whether the end user should be allowed to broadcast or not. Additional speed tests can be triggered manually through startUplinkTest().

        Note: The Broadcaster library component itself will allow broadcasting regardless of the speed test results. The speed test results are only offered as guidance.

        Parameters:
        obs - An instance of Broadcaster.UplinkSpeedObserver, or null to disable automatic uplink speed tests.
      • getUplinkSpeed

        public long getUplinkSpeed()
        Get the latest known uplink bandwidth estimate. This method can be used also while a speed test is running (if you don't have time to wait for the onUplinkTestComplete(bitrate, recommendation) callback), but the accuracy of the result improves until the measurement is complete.
        Returns:
        Measured bandwidth in bits per second (bps). Zero if no test has been started, or if broadcasting is in progress.
      • getUplinkRecommendation

        public boolean getUplinkRecommendation()
        Get whether the Broadcaster recommends broadcasting or not, based on the latest uplink bandwidth estimate. This method can be used also while a speed test is running (if you don't have time to wait for the onUplinkTestComplete(bitrate, recommendation) callback), but the accuracy of the result improves until the measurement is complete.
        Returns:
        True if a bandwidth measurement exists and the bitrate is deemed sufficient for live broadcasting. False otherwise.
      • setTitle

        public void setTitle​(String title)
        Set the title to use for the broadcast. This can be set before startBroadcast(), and can also be updated later during the broadcast.
        Parameters:
        title - Free-text broadcast title
      • setAuthor

        public void setAuthor​(String author)
        Set the author tag to send along with the broadcast. This is any arbitrary string to associate with the broadcast. It should be kept relatively short, as it is stored in database columns of limited size and may be accessed along with other broadcast metadata. This can be set before startBroadcast(), and can also be updated later during the broadcast.
        Parameters:
        author - Broadcast author string
      • setCustomData

        public void setCustomData​(String data)
        Set custom data to send along with the broadcast. This can be any data that can be expressed in UTF-8, such as JSON, XML, BASE64 or plain text. It should be kept below 10KB, as it is stored in database columns of limited size. This can be set before startBroadcast(), and can also be updated later during the broadcast.
        Parameters:
        data - Custom data associated with broadcast.
      • getSupportedResolutions

        public List<Resolution> getSupportedResolutions()
        Retrieve a list of video resolutions that the current camera on this device supports. We recommend that you invoke this method in the onResolutionsScanned() callback and then call setResolution(width, height).
        Returns:
        A list of camera video Resolution objects, sorted ascending. The list of supported resolutions can change when switching cameras. Returns an empty list until the first onResolutionsScanned() callback.
      • getResolution

        public Resolution getResolution()
        Get the current selected camera resolution.
        Returns:
        A Resolution object or null. When a camera is active, the returned value is the actual camera video resolution, no rotation applied. Before a camera is started, this returns the latest value set through setResolution(width, height).
      • setResolution

        public void setResolution​(int maxWidth,
                                  int maxHeight)
        Set the desired camera video resolution. We recommend that you invoke this method in the onResolutionsScanned() callback, which is called every time a camera starts. See getSupportedResolutions() for a list of resolutions supported by the chosen camera.

        Don't swap the width and height values, any rotation is taken care of internally when using the setRotation() methods.

        The live broadcast resolution is always automatically adjusted, up to and including the chosen camera resolution, depending on current network conditions. Any stored local copy (see storeLocalMedia(File, LocalMediaObserver) or storeLocalMedia(ParcelFileDescriptor, LocalMediaObserver)) will use the chosen camera resolution.

        Use maxWidth 0 and maxHeight 0 to use the default video resolution for the current camera. The default is generally 1280x720, but may be lower on older devices. If you set a resolution that isn't supported by the camera on the current device, the nearest supported lower resolution is chosen.

        This may be called also while broadcasting but may result in a new broadcast on the servers. This setting is locked while local recording is in progress.

        If the app has the ACCESS_NETWORK_STATE permission, automatic resolution switching will read the network type to quickly select a high resolution when appropriate.

        Parameters:
        maxWidth - Camera resolution width in pixels
        maxHeight - Camera resolution height in pixels
      • setMaxLiveResolution

        public void setMaxLiveResolution​(int maxWidth,
                                         int maxHeight)
        Set the maximum allowed resolution for the live broadcast video. This can be used to conserve bandwidth while using a higher camera video resolution, for example when a high resolution local copy is desired.

        The live broadcast resolution will not be higher than the set limit, not higher than the actual camera video resolution set through setResolution(int, int) and will still be automatically adjusted depending on current network conditions. This method only sets an upper bound.

        This should preferably be set before starting broadcasting. It may be called also while broadcasting but may result in a new broadcast on the servers.

        Accepted values range from 320x240 to 1280x720. The default is currently 1280x720. Don't swap the width and height values. Any rotation is taken care of internally when using the setRotation() methods.

        Parameters:
        maxWidth - Allowed live video width in pixels
        maxHeight - Allowed live video height in pixels
      • setRotation

        public void setRotation​(int displayRotation)
        Invoke this method to rotate the camera preview, video and pictures according to the UI orientation desired by the app. This is a convenience method for invoking setRotation(previewRotation, captureRotation).
        Parameters:
        displayRotation - The current app UI rotation, see Display.getRotation().
      • setRotation

        public void setRotation​(int previewRotation,
                                int captureRotation)
        Invoke this method to rotate the camera preview, video and pictures according to the app UI orientation.

        By default, the Broadcaster does not apply any rotation on the cameras, because it doesn't know the app orientation. Camera default is usually landscape orientation. Modern devices may have cameras mounted differently, and are only rotated correctly when this method is used.

        Use Display.getRotation() to get the current display rotation constant suitable for preview rotation. You can set up an OrientationEventListener and use setRotation(previewRotation, captureRotation) when the value from Display.getRotation() changes.

        Captured video and pictures can be rotated independently of the preview rotation. This can be useful if the Activity is locked permanently to one orientation and manually detects how the device is held.

        This may be called also while broadcasting but will result in a new broadcast on the servers if the output aspect ratio changes. Switching between opposite rotations (landscape to reverse landscape, or portrait to upside down portrait) will not interrupt the broadcast.

        This setting is locked while local recording is in progress. If your app UI can rotate to any orientation and you use storeLocalMedia(File, LocalMediaObserver) or storeLocalMedia(ParcelFileDescriptor, LocalMediaObserver), you should lock the orientation before starting a broadcast, and can unlock it again after stopping.

        Parameters:
        previewRotation - The current app UI rotation, see Display.getRotation().
        captureRotation - One of the Display.getRotation() constants. Should usually be the same as previewRotation.
      • setRotation

        public void setRotation​(int previewRotation,
                                int captureRotation,
                                int aspectWidth,
                                int aspectHeight)
        Advanced rotation setter with support for cropping captured video to a desired aspect ratio. Only the captured data (live and local copy) is cropped. The preview SurfaceView will contain the un-cropped camera image.

        See setRotation(preview, capture) for documentation of the rotation parameters.

        Note: The preview surface view will normally show the full input camera picture, even if cropping is applied to the broadcast stream. If a custom aspect ratio is requested, make sure the parent layout of the surface view has got an aspect ratio similar to what is requested, and set the cropToParent attribute to true on the SurfaceViewWithAutoAR view (if using that class). An example of how to crop the preview to a square:

         <RelativeLayout
             android:layout_width="250dp"
             android:layout_height="250dp"
             android:layout_centerInParent="true">
             <com.bambuser.broadcaster.SurfaceViewWithAutoAR android:id="@+id/PreviewSurfaceView"
                 android:layout_height="wrap_content"
                 android:layout_width="wrap_content"
                 android:layout_centerInParent="true"
                 app:cropToParent="true" />
         </RelativeLayout>
         

        If not using a hardcoded width/height as in this simplified example, the app needs to take care of the layout of this container to keep the desired aspect ratio - e.g. by subclassing the RelativeLayout class and overriding the View.onMeasure(int, int) method.

        Parameters:
        previewRotation - The current app UI rotation, see Display.getRotation().
        captureRotation - One of the Display.getRotation() constants. Should usually be the same as previewRotation.
        aspectWidth - Crop the rotated captured video to provided aspect ratio. Set to 0 for no cropping.
        aspectHeight - Crop the rotated captured video to provided aspect ratio. Set to 0 for no cropping.
      • getPreviewRotation

        public int getPreviewRotation()
        Get the currently active preview rotation value. This method can be used to check if a call to setRotation(previewRotation, captureRotation) had effect, and helps you decide how you should lock your UI when starting a broadcast.
        Returns:
        The currently applied preview display rotation value, or -1 if no value has been set.
      • getCaptureRotation

        public int getCaptureRotation()
        Get the currently active capture rotation value. This method can be used to check if a call to setRotation(previewRotation, captureRotation) had effect, and determines how a broadcast will turn out.
        Returns:
        The currently applied capture rotation value, or -1 if no value has been set.
      • hasLocalMediaCapability

        public boolean hasLocalMediaCapability()
        Check if the current device is capable of writing a local media file while broadcasting. If this method returns false, storeLocalMedia(File, LocalMediaObserver) or storeLocalMedia(ParcelFileDescriptor, LocalMediaObserver) does nothing.

        Writing a local media file of the broadcast is only supported on modern devices known to have working hardware accelerated video encoding. If you have a new model where you need this feature, contact info@bambuser.com and we'll investigate.

        Returns:
        true if the device can write a local copy, false otherwise.
      • storeLocalMedia

        public boolean storeLocalMedia​(File mp4file,
                                       Broadcaster.LocalMediaObserver observer)
        Enable writing a local copy of a broadcast to the specified file. The calling app must have permission to write to the specified file.

        The File API is generally NOT usable with shared media storage on Android Q (API 29) and up. See storeLocalMedia(ParcelFileDescriptor, LocalMediaObserver) for a suitable method for modern Android versions.

        The recorded video resolution is equal to the chosen camera resolution, see setResolution(width, height) and getSupportedResolutions(), and is full frame rate regardless of the live stream network conditions.

        This method should be invoked before each broadcast that should be recorded.

        Invoke hasLocalMediaCapability() to determine if local media writing is supported on the current device.

        Parameters:
        mp4file - A new file to which the Broadcaster should write data. Any existing data in the file will be overwritten.
        observer - A Broadcaster.LocalMediaObserver which will be invoked while writing a local media file.
        Returns:
        true if media file initialization succeeded, false otherwise.
      • storeLocalMedia

        public boolean storeLocalMedia​(ParcelFileDescriptor fileDescriptor,
                                       Broadcaster.LocalMediaObserver observer)
        Enable writing a local copy of a broadcast to the specified file descriptor. The calling app must have permission to write to the specified location and the ParcelFileDescriptor must be created with full read-write access. The Broadcaster takes responsibility for the file descriptor and will close it when finished.

        This method is usable for all Android versions, unlike storeLocalMedia(File, LocalMediaObserver) which is suitable only for older Android versions.

        The recorded video resolution is equal to the chosen camera resolution, see setResolution(width, height) and getSupportedResolutions(), and is full frame rate regardless of the live stream network conditions.

        This method should be invoked before each broadcast that should be recorded.

        Invoke hasLocalMediaCapability() to determine if local media writing is supported on the current device.

        Parameters:
        fileDescriptor - A new file descriptor to which the Broadcaster should write data.
        observer - A Broadcaster.LocalMediaObserver which will be invoked while writing a local media file.
        Returns:
        true if media file initialization succeeded, false otherwise.
      • hasTalkbackCapability

        public boolean hasTalkbackCapability()
        Check if the current device is capable of receiving talkback streams while broadcasting. If this method returns false, setTalkbackObserver(TalkbackObserver) does nothing.
        Returns:
        true if this device can receive talkback streams, false otherwise.
      • setTalkbackObserver

        public void setTalkbackObserver​(Broadcaster.TalkbackObserver obs)
        Enable talkback functionality in your app by providing a Broadcaster.TalkbackObserver implementation.

        This can not be changed while broadcasting.

        Parameters:
        obs - An observer object enabling talkback functionality, or null to disable talkback functionality.
      • setTalkbackMixin

        public void setTalkbackMixin​(boolean enabled)
        Set whether received talkback audio should be mixed into the broadcast audio signal. The default is to play talkback audio only locally, not mix it into the broadcast.

        This setting can not be changed while broadcasting.

        Parameters:
        enabled - True to enable talkback mix-in. False to only play talkback audio locally.
      • stopTalkback

        public void stopTalkback()
        Optionally call this at any time to stop a pending/ongoing talkback stream. The state will transition to TalkbackState.IDLE Talkback streams are automatically stopped when broadcasting stops.
      • switchCamera

        public void switchCamera()
        Switch to using the next camera. If the other camera doesn't support the same resolution, the resolution will automatically be changed.

        This may be called also while broadcasting, but if the resolution changes, it can result in a new broadcast on the servers. If you want to allow camera switching while broadcasting, as long as it doesn't cause a new broadcast, use canSwitchCameraWithoutResolutionChange().

        If camera change requires a resolution change (or rotation change) and local recording is in progress, it is not possible to switch camera. In that case, this method will do nothing.

      • getCameraCount

        public int getCameraCount()
        Query the number of available cameras on the current device. This can be called at any time.
        Returns:
        the number of cameras
      • getSupportedCameras

        public List<Broadcaster.Camera> getSupportedCameras()
        Returns a list of supported cameras on the current device. This can be used to check for a specific front or rear camera to set using setCameraId(String).
        Returns:
        A list of all supported cameras. Never null.
      • getCameraId

        public String getCameraId()
        Get the ID of the currently selected camera. This doesn't indicate whether a specific camera has started yet, as all camera handling is asynchronous.
        Returns:
        ID of the currently selected camera.
      • setCameraId

        public void setCameraId​(String id)
        Set which camera the Broadcaster should activate. All camera handling is asynchronous.
        Parameters:
        id - Id for the desired camera.
      • canSwitchCameraWithoutResolutionChange

        public boolean canSwitchCameraWithoutResolutionChange()
        Determines whether it is possible to switch camera without causing a resolution change with the currently applied capture rotation. If this method returns true, the app can safely invoke switchCamera() while broadcasting. You can rely on the first Broadcaster.Observer.onCameraPreviewStateChanged() callback to know when it is meaningful to invoke this method.
        Returns:
        true if the next camera supports the resolution currently in use. false if a camera change would require a resolution change or no camera has started yet.
      • canSwitchCameraWithoutResolutionChange

        public boolean canSwitchCameraWithoutResolutionChange​(String nextCameraId)
      • canDisableShutterSound

        public boolean canDisableShutterSound()
        Determines whether the device supports disabling camera shutter sound. The camera shutter sound can normally be disabled, but is enforced by law on devices in some countries.

        Will always return false for a newly constructed Broadcaster, until camera information has been loaded. You can rely on the first Broadcaster.Observer.onCameraPreviewStateChanged() callback to know when it is meaningful to invoke this method.

        Returns:
        True if the device supports disabling shutter sound, false otherwise.
      • setCaptureSounds

        public void setCaptureSounds​(boolean value)
        Enable or disable camera capture sounds, i.e. shutter sound and video recording sounds. Capture sounds are enabled by default.

        Android guidelines strongly recommend playing capture sounds. If you disable the default capture sounds, it is your responsibility to provide alternatives and comply with any laws in countries where capture sounds are required.

        Some devices do not support disabling the shutter sound, this can be determined with canDisableShutterSound().

        Parameters:
        value - True if capture sounds should be enabled, false otherwise.
      • setSendPosition

        public void setSendPosition​(boolean value)
        Enable GPS and network based positioning, provided that the device supports it. The default value is false (positioning disabled). Requires ACCESS_COARSE_LOCATION or ACCESS_FINE_LOCATION.

        This setting can be changed at any time. The setting will not apply retroactively for an ongoing broadcast (if a position is sent to the servers, it will be available there until updated or manually removed).

        Parameters:
        value - True if geo-positioning should be enabled, false otherwise.
      • getRecentPosition

        public Location getRecentPosition()
        Returns:
        The latest known Location, when geotagging has been enabled using setSendPosition(true). May be null if position has not been determined yet or if positioning is disabled/unavailable in the device.
      • setSaveOnServer

        public void setSaveOnServer​(boolean value)
        Sets whether the broadcast is stored on Bambuser's servers or not. The default value is true (broadcasts stored).

        This setting can not be changed while broadcasting.

        Parameters:
        value - True if broadcasts should be stored, false otherwise.
      • hasFocus

        public boolean hasFocus()
        Check whether the current camera supports focusing.
        Returns:
        True if the current camera on this device supports focusing.
      • focus

        public void focus()
        This method toggles focus mode on cameras that support focusing. In practice, on most devices, this alternates between continuous auto-focus and locking the focus with a one-time focus pass. The Broadcaster by default uses continuous auto-focus on devices that support it. If continuous auto-focus is not working well in certain lighting conditions on a device, the end user may want to trigger a one-time focus pass and lock the focus.
      • hasTorch

        public boolean hasTorch()
        Check whether the current camera has a led torch that can be used for continuous lighting.
        Returns:
        True if the current camera on this device has a light that can be enabled.
      • toggleTorch

        public void toggleTorch()
        Toggle the torch on/off
      • hasZoom

        public boolean hasZoom()
        Check whether the current camera supports zooming. See also setZoom(int), getZoom() and getZoomRatios().
        Returns:
        True if the currently started camera supports zooming, false otherwise.
      • getZoom

        public int getZoom()
        Get the currently active zoom. Ex: a zoom of 3.2x is returned as 320, and 1.0x (no zoom) is returned as 100. See also hasZoom() and setZoom(int).
        Returns:
        A value in the range of getZoomRatios().
      • getZoomRatios

        public List<Integer> getZoomRatios()
        Get the zoom ratios supported by the current camera at the current resolution. May change when camera or resolution is changed. See also hasZoom(), getZoom() and setZoom(int).
        Returns:
        A list of zoom ratios expressed as integers from 100 up to the maximum supported value. null if zooming is not supported.
      • setZoom

        public void setZoom​(int zoom)
        Asynchronously sets the desired zoom. See also hasZoom(), getZoom() and getZoomRatios().
        Parameters:
        zoom - A value in the range of getZoomRatios(). If the provided value is not found in the list, it may be rounded down.
      • onActivityPause

        public void onActivityPause()
        This must be called from the onPause() method to stop internal threads and release hardware resources such as the camera and microphone.
      • onActivityResume

        public void onActivityResume()
        This must be called from the onResume() method to start internal threads and restart camera preview.
      • onActivityDestroy

        public void onActivityDestroy()
        This must be called from the onDestroy() method (or earlier if desired) to release all resources properly. After this call, the Broadcaster object can not be used and should be discarded.
      • canStartBroadcasting

        public boolean canStartBroadcasting()
        This method can be called at any time to check whether the Broadcaster is idle and ready to start broadcasting. startBroadcast() will do nothing while this method returns false.
        Returns:
        true if the Broadcaster is idle and ready for broadcasting. false while broadcasting or not attached to a SurfaceView or while the Broadcaster is loading camera information during initialization.
      • stopBroadcast

        public void stopBroadcast()