Custom video source
Updated
Integrate a custom video or audio capture into your client
Custom video capture refers to the collection of a video stream from a custom source. Unlike the default video capture method, custom video capture enables you to control the capture source, and precisely adjust video attributes. You can dynamically adjust parameters such as video quality, resolution, and frame rate to adapt to various application use cases. For example, you can capture video from high-definition cameras, and drone cameras.
Agora recommends default video capture for its stability, reliability, and ease of integration. Custom video capture offers flexibility and customization for specific video capture use cases where default video capture does not fulfill your requirements.
Understand the tech
RTC SDK uses custom video tracks to publish video that you capture yourself. You can create and publish custom video tracks to one or more channels. Your capture module drives the capture device and sends the captured video frames to the SDK through a video track.
The following figure illustrates the video data transmission process when custom video capture is implemented:
Choose an integration approach
For new Android integrations, Agora recommends using io.agora.base.VideoFrame with pushExternalVideoFrameById(VideoFrame frame, int videoTrackId).
- To publish one custom video stream to a channel, enable the external video source with
setExternalVideoSourcebefore joining. SetpublishCustomVideoTracktotrueandcustomVideoTrackIdto0inChannelMediaOptions. The SDK creates the default custom video track automatically. You do not need to callcreateCustomVideoTrack. - To publish multiple custom video streams, or different custom streams to different channels, call
createCustomVideoTrackto create a separate track for each stream. - If an existing capture module uses
AgoraVideoFrame, you can continue usingpushExternalVideoFrameById(AgoraVideoFrame frame, int videoTrackId). This overload does not support Texture data and offers fewer extension capabilities than theVideoFrameoverload.
VideoFrame supports buffer types including I420, NV21, NV12, and Texture. VideoFrame.TextureBuffer provides access to the texture type, EGL context, transform matrix, and fence object. AgoraVideoFrame uses individual fields to describe a frame. Its buf field can hold raw data such as NV21 for simple byte-array capture integrations.
Prerequisites
Ensure that you have implemented the SDK quickstart in your project.
Implement the logic
This section shows you how to implement custom video capture and custom video rendering in your app.
Custom video capture
The following figure shows the workflow you implement to capture and stream a custom video source in your app.
Custom video capture
Use the default track for a single custom video stream, or explicitly created tracks for multiple streams. For details, see Choose an integration approach. Take the following steps to implement this workflow:
-
Create custom video tracks, if required
For a single stream that uses the default custom video track, skip this step and use track ID
0in step 2. For multiple streams, callcreateCustomVideoTrackafter initializing an instance ofRtcEngineto obtain a separate track ID for each stream.int videoTrackId = engine.createCustomVideoTrack();val videoTrackId = engine.createCustomVideoTrack() -
Join a channel and publish the custom video track
Default track for a single stream
Enable the external video source before joining the channel, and publish track ID
0. Set the second argument ofsetExternalVideoSourcetotrueif you push Texture data, orfalseotherwise.// Enable external capture before joining the channel. engine.setExternalVideoSource( true, false, Constants.ExternalVideoSourceType.VIDEO_FRAME); int videoTrackId = 0; ChannelMediaOptions option = new ChannelMediaOptions(); option.clientRoleType = Constants.CLIENT_ROLE_BROADCASTER; option.autoSubscribeAudio = true; option.autoSubscribeVideo = true; option.publishCustomVideoTrack = true; option.customVideoTrackId = videoTrackId; int res = engine.joinChannel(accessToken, channelId, 0, option);// Enable external capture before joining the channel. engine.setExternalVideoSource( true, false, Constants.ExternalVideoSourceType.VIDEO_FRAME) val videoTrackId = 0 val option = ChannelMediaOptions().apply { clientRoleType = Constants.CLIENT_ROLE_BROADCASTER autoSubscribeAudio = true autoSubscribeVideo = true publishCustomVideoTrack = true customVideoTrackId = videoTrackId } val res = engine.joinChannel(accessToken, channelId, 0, option)Explicit tracks for multiple streams
Use the track ID returned in step 1. To publish different streams to different channels, set the corresponding track ID in each channel's
ChannelMediaOptions.// Create a ChannelMediaOptions instance ChannelMediaOptions option = new ChannelMediaOptions(); // Set the client role to BROADCASTER option.clientRoleType = Constants.CLIENT_ROLE_BROADCASTER; // Enable auto subscription of audio and video option.autoSubscribeAudio = true; option.autoSubscribeVideo = true; // Publish the custom video stream option.publishCustomVideoTrack = true; // Set custom video track ID option.customVideoTrackId = videoTrackId; // Join a channel with the specified options int res = engine.joinChannel(accessToken, channelId, 0, option);// Create a ChannelMediaOptions instance val option = ChannelMediaOptions().apply { // Set the client role to BROADCASTER clientRoleType = Constants.CLIENT_ROLE_BROADCASTER // Enable auto subscription of audio and video autoSubscribeAudio = true autoSubscribeVideo = true // Publish the custom video stream publishCustomVideoTrack = true // Set custom video track ID customVideoTrackId = videoTrackId } // Join a channel with the specified options val res = engine.joinChannel(accessToken, channelId, 0, option) -
Implement your capture module
Agora provides the VideoFileReader demo project that shows you how to read
YUVformat video data from a local file. In a production environment, create a custom video module for your device using RTC SDK based on your business requirements. -
Push video data to the SDK
Before sending captured video frames to RTC SDK, integrate your video module with the
VideoFrame.To ensure audio-video synchronization, set the timestamp of each
VideoFrameto the current monotonic time. CallgetCurrentMonotonicTimeInMsto obtain it. This method returns milliseconds, but theVideoFrameconstructor'stimestampNsargument expects nanoseconds. Multiply the value by 1,000,000 before you construct the frame, as the samples do.Call
pushExternalVideoFrameByIdto push the captured video frames through the video track to RTC SDK. Use0for the default track, or the track ID returned bycreateCustomVideoTrackfor an explicitly created track. The ID must match thecustomVideoTrackIdspecified when joining the channel.The following samples use the recommended
io.agora.base.VideoFrameoverload to pushI420,NV21,NV12, andTextureformat video data:-
I420
private void pushVideoFrameByI420(int trackId, byte[] yuv, int width, int height) { // Create an i420Buffer object and store the original YUV data in the buffer JavaI420Buffer i420Buffer = JavaI420Buffer.allocate(width, height); i420Buffer.getDataY().put(yuv, 0, i420Buffer.getDataY().limit()); i420Buffer.getDataU().put(yuv, i420Buffer.getDataY().limit(), i420Buffer.getDataU().limit()); i420Buffer.getDataV().put(yuv, i420Buffer.getDataY().limit() + i420Buffer.getDataU().limit(), i420Buffer.getDataV().limit()); // Get the current monotonic time from the SDK long currentMonotonicTimeInMs = engine.getCurrentMonotonicTimeInMs(); // Create a VideoFrame object, passing the I420 video frame to be pushed and the monotonic time of the video frame (in nanoseconds) VideoFrame videoFrame = new VideoFrame(i420Buffer, 0, currentMonotonicTimeInMs * 1000000); // Push the video frame to the SDK through the video track int ret = engine.pushExternalVideoFrameById(videoFrame, trackId); // Release the memory resources occupied by the i420Buffer object i420Buffer.release(); if (ret != Constants.ERR_OK) { Log.w(TAG, "pushExternalVideoFrame error"); } }private fun pushVideoFrameByI420(trackId: Int, yuv: ByteArray, width: Int, height: Int) { // Create an i420Buffer object and store the original YUV data in the buffer val i420Buffer = JavaI420Buffer.allocate(width, height) i420Buffer.getDataY().put(yuv, 0, i420Buffer.getDataY().limit()) i420Buffer.getDataU().put(yuv, i420Buffer.getDataY().limit(), i420Buffer.getDataU().limit()) i420Buffer.getDataV().put(yuv, i420Buffer.getDataY().limit() + i420Buffer.getDataU().limit(), i420Buffer.getDataV().limit()) // Get the current monotonic time from the SDK val currentMonotonicTimeInMs = engine.getCurrentMonotonicTimeInMs() // Create a VideoFrame object, passing the I420 video frame to be pushed and the monotonic time of the video frame (in nanoseconds) val videoFrame = VideoFrame(i420Buffer, 0, currentMonotonicTimeInMs * 1_000_000) // Push the video frame to the SDK through the video track val ret = engine.pushExternalVideoFrameById(videoFrame, trackId) // Release the memory resources occupied by the i420Buffer object i420Buffer.release() if (ret != Constants.ERR_OK) { Log.w(TAG, "pushExternalVideoFrame error") } } -
NV21
private void pushVideoFrameByNV21(int trackId, byte[] nv21, int width, height) { // Create a frameBuffer object and store the original YUV data in the NV21 format buffer VideoFrame.Buffer frameBuffer = new NV21Buffer(nv21, width, height, null); // Get the current monotonic time from the SDK long currentMonotonicTimeInMs = engine.getCurrentMonotonicTimeInMs(); // Create a VideoFrame object, pass the NV21 video frame to be pushed and the monotonic time of the video frame (in nanoseconds) VideoFrame videoFrame = new VideoFrame(frameBuffer, 0, currentMonotonicTimeInMs * 1000000); // Push the video frame to the SDK through the video track int ret = engine.pushExternalVideoFrameById(videoFrame, trackId); if (ret != Constants.ERR_OK) { Log.w(TAG, "pushExternalVideoFrame error"); } }private fun pushVideoFrameByNV21(trackId: Int, nv21: ByteArray, width: Int, height: Int) { // Create a frameBuffer object and store the original YUV data in the NV21 format buffer val frameBuffer: VideoFrame.Buffer = NV21Buffer(nv21, width, height, null) // Get the current monotonic time from the SDK val currentMonotonicTimeInMs = engine.getCurrentMonotonicTimeInMs() // Create a VideoFrame object, pass the NV21 video frame to be pushed and the monotonic time of the video frame (in nanoseconds) val videoFrame = VideoFrame(frameBuffer, 0, currentMonotonicTimeInMs * 1_000_000) // Push the video frame to the SDK through the video track val ret = engine.pushExternalVideoFrameById(videoFrame, trackId) if (ret != Constants.ERR_OK) { Log.w(TAG, "pushExternalVideoFrame error") } } -
NV12
private void pushVideoFrameByNV12(int trackId, ByteBuffer nv12, int width, int height) { // Create a frameBuffer object and store the original YUV data in the NV12 format buffer VideoFrame.Buffer frameBuffer = new NV12Buffer(width, height, width, height, nv12, null); // Get the current monotonic time from the SDK long currentMonotonicTimeInMs = engine.getCurrentMonotonicTimeInMs(); // Create a VideoFrame object, pass the NV12 video frame to be pushed and the monotonic time of the video frame (in nanoseconds) VideoFrame videoFrame = new VideoFrame(frameBuffer, 0, currentMonotonicTimeInMs * 1000000); // Push the video frame to the SDK through the video track int ret = engine.pushExternalVideoFrameById(videoFrame, trackId); if (ret != Constants.ERR_OK) { Log.w(TAG, "pushExternalVideoFrame error"); } }private fun pushVideoFrameByNV12(trackId: Int, nv12: ByteBuffer, width: Int, height: Int) { // Create a frameBuffer object and store the original YUV data in the NV12 format buffer val frameBuffer: VideoFrame.Buffer = NV12Buffer(width, height, width, height, nv12, null) // Get the current monotonic time from the SDK val currentMonotonicTimeInMs = engine.getCurrentMonotonicTimeInMs() // Create a VideoFrame object, pass the NV12 video frame to be pushed and the monotonic time of the video frame (in nanoseconds) val videoFrame = VideoFrame(frameBuffer, 0, currentMonotonicTimeInMs * 1_000_000) // Push the video frame to the SDK through the video track val ret = engine.pushExternalVideoFrameById(videoFrame, trackId) if (ret != Constants.ERR_OK) { Log.w(TAG, "pushExternalVideoFrame error") } } -
Texture
private void pushVideoFrameByTexture(int trackId, int textureId, VideoFrame.TextureBuffer.Type textureType, int width, int height) { // Create a frameBuffer object to store the texture format video frame VideoFrame.Buffer frameBuffer = new TextureBuffer( EglBaseProvider.getCurrentEglContext(), width, height, textureType, textureId, new Matrix(), null, null, null ); // Get the current monotonic time from the SDK long currentMonotonicTimeInMs = engine.getCurrentMonotonicTimeInMs(); // Create a VideoFrame object, passing the texture video frame to be pushed and the monotonic time of the video frame (in nanoseconds) VideoFrame videoFrame = new VideoFrame(frameBuffer, 0, currentMonotonicTimeInMs * 1000000); // Push the video frame to the SDK through the video track int ret = engine.pushExternalVideoFrameById(videoFrame, trackId); if (ret != Constants.ERR_OK) { Log.w(TAG, "pushExternalVideoFrame error"); } }private fun pushVideoFrameByTexture( trackId: Int, textureId: Int, textureType: VideoFrame.TextureBuffer.Type, width: Int, height: Int ) { // Create a frameBuffer object to store the texture format video frame val frameBuffer: VideoFrame.Buffer = TextureBuffer( EglBaseProvider.getCurrentEglContext(), width, height, textureType, textureId, Matrix(), null, null, null ) // Get the current monotonic time from the SDK val currentMonotonicTimeInMs = engine.getCurrentMonotonicTimeInMs() // Create a VideoFrame object, passing the texture video frame to be pushed and the monotonic time of the video frame (in nanoseconds) val videoFrame = VideoFrame(frameBuffer, 0, currentMonotonicTimeInMs * 1_000_000) // Push the video frame to the SDK through the video track val ret = engine.pushExternalVideoFrameById(videoFrame, trackId) if (ret != Constants.ERR_OK) { Log.w(TAG, "pushExternalVideoFrame error") } }
If you capture Texture video and remote users see flickering or distortion, duplicate the video data and send both the original and the duplicate to RTC SDK. This helps eliminate anomalies during internal encoding.
-
-
Destroy custom video tracks
If you created a track with
createCustomVideoTrack, stop publishing it and calldestroyCustomVideoTrackwith the returned track ID. Repeat for each explicitly created track.// Stop publishing the custom video track. ChannelMediaOptions stopOptions = new ChannelMediaOptions(); stopOptions.customVideoTrackId = videoTrackId; stopOptions.publishCustomVideoTrack = false; engine.updateChannelMediaOptions(stopOptions); // Destroy the custom video track. engine.destroyCustomVideoTrack(videoTrackId); // Leave the channel. engine.leaveChannel();// Stop publishing the custom video track. val stopOptions = ChannelMediaOptions().apply { customVideoTrackId = videoTrackId publishCustomVideoTrack = false } engine.updateChannelMediaOptions(stopOptions) // Destroy the custom video track. engine.destroyCustomVideoTrack(videoTrackId) // Leave the channel. engine.leaveChannel()If you use the default track for a single stream, stop your capture module before leaving the channel. This path does not require
createCustomVideoTrackordestroyCustomVideoTrack. After leaving the channel, disable the external video source if it is no longer needed:// Stop your capture module before leaving the channel. engine.leaveChannel(); engine.setExternalVideoSource( false, false, Constants.ExternalVideoSourceType.VIDEO_FRAME);// Stop your capture module before leaving the channel. engine.leaveChannel() engine.setExternalVideoSource( false, false, Constants.ExternalVideoSourceType.VIDEO_FRAME)
Custom video rendering
To implement custom video rendering in your app, take the following steps:
- Set up the
onCaptureVideoFrameoronRenderVideoFramecallback to obtain the video data to be played. - Implement video rendering and playback yourself.
Reference
This section lists use cases, advantages, sample projects, and API references for custom video capture on Android.
Applicable use cases
Use custom video capture in the following industries and use cases:
Specialized video processing and enhancement
In some gaming or virtual reality use cases, real-time effects, filters, or other enhancements need direct access to the original video stream. Custom video capture provides this access, which enables real-time processing and a more realistic gaming or virtual reality experience.
High-precision video capture
In video surveillance applications, detailed observation and analysis of scene details is necessary. Custom video capture enables higher image quality and finer control over capture to meet the requirements of video monitoring.
Capture from specific video sources
Industries such as IoT and live streaming often require the use of specific cameras, monitoring devices, or non-camera video sources, such as video capture cards or screen recording data. In such situations, default RTC SDK capture may not meet your requirements, and you need custom video capture.
Seamless integration with specific devices or third-party applications
In smart home or IoT applications, transmitting video from devices to users' smartphones or computers for monitoring and control may require the use of specific devices or applications for video capture. Custom video capture lets you integrate these devices or applications with RTC SDK.
Specific video encoding formats
In some live streaming use cases, your business requirements may call for specific video encoding formats. In such cases, RTC SDK default capture might not suffice, and you need custom video capture to capture and encode video in those formats.
Advantages
Using custom video capture offers the following advantages:
More types of video streams
Custom video capture lets you use higher quality and a greater variety of capture devices and cameras, resulting in clearer and smoother video streams. This enhances the user viewing experience and makes the product more competitive.
More flexible video effects
Custom video capture enables you to implement richer and more personalized video effects and filters, enhancing the user experience. You can implement effects such as beautification filters and dynamic stickers.
Adaptation to diverse use-case requirements
Custom video capture helps applications better adapt to the requirements of various use cases, such as live streaming, video conferencing, and online education. You can customize different video capture solutions based on the use-case requirements to provide a more robust application.
Sample projects
Agora provides the following open-source sample projects for your reference. Download the project or view the source code for a more detailed example.
- MultiVideoSourceTracks: Custom video capture
- CustomRemoteVideoRender: Custom remote video rendering
