All Products
Search
Document Center

ApsaraVideo Live:Guest spot mode

Last Updated:Aug 17, 2026

Co-streaming lets a viewer join a live streamer as a co-host over Real-Time Communication (RTC) while regular viewers continue watching through CDN. The implementation involves pushing streams to an RTC room, managing server-side mixing tasks, and handling the transition between CDN playback and RTC participation.

How co-streaming works

image

The streamer and co-streamer push streams to an RTC room through the ARTC SDK. The application server monitors stream change events and calls the StartLiveMPUTask API to forward streams from the RTC room to ApsaraVideo Live CDN. Regular viewers pull and watch the CDN stream through the ApsaraVideo Player SDK.

Co-streaming lifecycle

Phase

Streamer

Co-streamer

Application server

Viewers

Before co-streaming

Joins the RTC room and pushes audio/video streams via the ARTC SDK.

Watches the CDN stream via ApsaraVideo Player.

Detects the streamer's stream push, then calls StartLiveMPUTask with MixMode=0 (bypass) to forward the stream to CDN.

Pull and play the CDN stream via ApsaraVideo Player.

During co-streaming

Pulls the co-streamer's RTC stream and renders it.

Stops CDN playback, joins the RTC room, pushes streams, and renders the streamer's RTC stream.

Detects the co-streamer's stream push, then calls UpdateLiveMPUTask to switch to MixMode=1 (stream mixing) with a layout for both participants.

No action needed. The live stream automatically switches to show both participants.

End co-streaming

Stops pulling the co-streamer's stream.

Leaves the RTC room, destroys the RTC instance, and switches back to CDN playback.

Detects the co-streamer's departure, then calls UpdateLiveMPUTask to switch back to MixMode=0 (bypass).

No action needed. The live stream automatically switches back to the streamer only.

Note

To monitor RTC room stream change events, create a subscription with CreateEventSub.

Key APIs

API

Purpose

When to call

StartLiveMPUTask

Forward RTC room streams to CDN

After the streamer pushes a stream

UpdateLiveMPUTask

Switch between bypass and stream mixing

When a co-streamer joins or leaves

CreateEventSub

Subscribe to RTC room stream change events

Before starting the broadcast (recommended)

Step 1: Start the broadcast (streamer)

image

1. Push a stream to the RTC room

The streamer initializes the ARTC SDK, configures encoding parameters, and joins the RTC room.

For the full ARTC SDK integration guide, see:

Initialize the engine

Android

// Import ARTC related classes
import com.alivc.rtc.AliRtcEngine;
import com.alivc.rtc.AliRtcEngineEventListener;
import com.alivc.rtc.AliRtcEngineNotify;

private AliRtcEngine mAliRtcEngine = null;
if(mAliRtcEngine == null) {
    mAliRtcEngine = AliRtcEngine.getInstance(this);
}

// Set channel mode to interactive live streaming
mAliRtcEngine.setChannelProfile(AliRtcEngine.AliRTCSdkChannelProfile.AliRTCSdkInteractiveLive);
mAliRtcEngine.setClientRole(AliRtcEngine.AliRTCSdkClientRole.AliRTCSdkInteractive);

iOS (Swift)

import AliVCSDK_ARTC

private var rtcEngine: AliRtcEngine? = nil

// Create the engine and set the delegate
let engine = AliRtcEngine.sharedInstance(self, extras: nil)
self.rtcEngine = engine

// Set channel mode to interactive live streaming
engine.setChannelProfile(AliRtcChannelProfile.interactivelive)
engine.setClientRole(AliRtcClientRole.roleInteractive)

Configure audio and video encoding

Android

// Audio: high-quality music mode
mAliRtcEngine.setAudioProfile(
    AliRtcEngine.AliRtcAudioProfile.AliRtcEngineHighQualityMode,
    AliRtcEngine.AliRtcAudioScenario.AliRtcSceneMusicMode
);

// Video: 720x1280 at 20 fps, 1200 kbps
AliRtcEngine.AliRtcVideoEncoderConfiguration config =
    new AliRtcEngine.AliRtcVideoEncoderConfiguration();
config.dimensions = new AliRtcEngine.AliRtcVideoDimensions(720, 1280);
config.frameRate = 20;
config.bitrate = 1200;
config.keyFrameInterval = 2000;
config.orientationMode = AliRtcVideoEncoderOrientationModeAdaptive;
mAliRtcEngine.setVideoEncoderConfiguration(config);

iOS (Swift)

// Audio: high-quality music mode
engine.setAudioProfile(
    AliRtcAudioProfile.engineHighQualityMode,
    audio_scene: AliRtcAudioScenario.sceneMusicMode
)

// Video: 720x1280 at 20 fps, 1200 kbps
let config = AliRtcVideoEncoderConfiguration()
config.dimensions = CGSize(width: 720, height: 1280)
config.frameRate = 20
config.bitrate = 1200
config.keyFrameInterval = 2000
config.orientationMode = AliRtcVideoEncoderOrientationMode.adaptive
engine.setVideoEncoderConfiguration(config)
engine.setCapturePipelineScaleMode(.post)

Publish local streams and subscribe to remote streams

Android

// Publish local audio and video
mAliRtcEngine.publishLocalAudioStream(true);
mAliRtcEngine.publishLocalVideoStream(true);

// Subscribe to all remote streams
mAliRtcEngine.setDefaultSubscribeAllRemoteAudioStreams(true);
mAliRtcEngine.subscribeAllRemoteAudioStreams(true);
mAliRtcEngine.setDefaultSubscribeAllRemoteVideoStreams(true);
mAliRtcEngine.subscribeAllRemoteVideoStreams(true);

iOS (Swift)

// Publish local audio and video
engine.publishLocalVideoStream(true)
engine.publishLocalAudioStream(true)

// Subscribe to all remote streams
engine.setDefaultSubscribeAllRemoteAudioStreams(true)
engine.subscribeAllRemoteAudioStreams(true)
engine.setDefaultSubscribeAllRemoteVideoStreams(true)
engine.subscribeAllRemoteVideoStreams(true)

Register callbacks

Handle connection status changes, remote user events, and error conditions.

Android

private AliRtcEngineEventListener mRtcEngineEventListener = new AliRtcEngineEventListener() {
    @Override
    public void onJoinChannelResult(int result, String channel, String userId, int elapsed) {
        super.onJoinChannelResult(result, channel, userId, elapsed);
        handleJoinResult(result, channel, userId);
    }

    @Override
    public void onLeaveChannelResult(int result, AliRtcEngine.AliRtcStats stats){
        super.onLeaveChannelResult(result, stats);
    }

    @Override
    public void onConnectionStatusChange(AliRtcEngine.AliRtcConnectionStatus status,
            AliRtcEngine.AliRtcConnectionStatusChangeReason reason){
        super.onConnectionStatusChange(status, reason);
        handler.post(() -> {
            if(status == AliRtcEngine.AliRtcConnectionStatus.AliRtcConnectionStatusFailed) {
                // Handle unrecoverable connection failure
                ToastHelper.showToast(VideoChatActivity.this,
                    R.string.video_chat_connection_failed, Toast.LENGTH_SHORT);
            }
        });
    }

    @Override
    public void OnLocalDeviceException(AliRtcEngine.AliRtcEngineLocalDeviceType deviceType,
            AliRtcEngine.AliRtcEngineLocalDeviceExceptionType exceptionType, String msg){
        super.OnLocalDeviceException(deviceType, exceptionType, msg);
        // Notify the user when the SDK cannot recover the device
        handler.post(() -> {
            String str = "OnLocalDeviceException deviceType: " + deviceType
                + " exceptionType: " + exceptionType + " msg: " + msg;
            ToastHelper.showToast(VideoChatActivity.this, str, Toast.LENGTH_SHORT);
        });
    }
};

private AliRtcEngineNotify mRtcEngineNotify = new AliRtcEngineNotify() {
    @Override
    public void onAuthInfoWillExpire() {
        super.onAuthInfoWillExpire();
        // Refresh the token before it expires.
        // Obtain new auth info for the current channel and user,
        // then call refreshAuthInfo.
    }

    @Override
    public void onRemoteUserOnLineNotify(String uid, int elapsed){
        super.onRemoteUserOnLineNotify(uid, elapsed);
    }

    @Override
    public void onRemoteUserOffLineNotify(String uid,
            AliRtcEngine.AliRtcUserOfflineReason reason){
        super.onRemoteUserOffLineNotify(uid, reason);
        // Remove the remote video rendering view
    }

    @Override
    public void onRemoteTrackAvailableNotify(String uid,
            AliRtcEngine.AliRtcAudioTrack audioTrack,
            AliRtcEngine.AliRtcVideoTrack videoTrack){
        // Set or remove remote video rendering.
            // See "Render the streamer's video" in Step 2.
    }

    @Override
    public void onBye(int code){
        // Handle session termination (e.g., another device using the same UserID)
    }
};

mAliRtcEngine.setRtcEngineEventListener(mRtcEngineEventListener);
mAliRtcEngine.setRtcEngineNotify(mRtcEngineNotify);

iOS (Swift)

extension VideoCallMainVC: AliRtcEngineDelegate {

    func onJoinChannelResult(_ result: Int32, channel: String, userId: String, elapsed: Int32) {
        "onJoinChannelResult result: \(result)".printLog()
    }

    func onRemoteUser(onLineNotify uid: String, elapsed: Int32) {
        "onRemoteUserOnlineNotify uid: \(uid)".printLog()
    }

    func onRemoteUserOffLineNotify(_ uid: String, offlineReason reason: AliRtcUserOfflineReason) {
        "onRemoteUserOffLineNotify uid: \(uid) reason: \(reason)".printLog()
    }

    func onRemoteTrackAvailableNotify(_ uid: String, audioTrack: AliRtcAudioTrack,
            videoTrack: AliRtcVideoTrack) {
        // Set or remove remote video rendering.
        // See "Render the streamer's video" in Step 2.
    }

    func onAuthInfoWillExpire() {
        // Refresh the token before it expires.
        // Obtain new auth info for the current channel and user,
        // then call refreshAuthInfo.
    }

    func onAuthInfoExpired() {
        // Token is invalid. Leave the channel and release the engine.
    }

    func onBye(_ code: Int32) {
        // Handle session termination (e.g., another device using the same UserID)
    }

    func onLocalDeviceException(_ deviceType: AliRtcLocalDeviceType,
            exceptionType: AliRtcLocalDeviceExceptionType, message msg: String?) {
        // Notify the user when the SDK cannot recover the device
    }

    func onConnectionStatusChange(_ status: AliRtcConnectionStatus,
            reason: AliRtcConnectionStatusChangeReason) {
        if status == .failed {
            // Handle unrecoverable connection failure
        }
    }
}

Set up local preview and join the room

Android

// Local preview
mLocalVideoCanvas = new AliRtcEngine.AliRtcVideoCanvas();
SurfaceView localSurfaceView = mAliRtcEngine.createRenderSurfaceView(VideoChatActivity.this);
localSurfaceView.setZOrderOnTop(true);
localSurfaceView.setZOrderMediaOverlay(true);

FrameLayout fl_local = findViewById(R.id.fl_local);
fl_local.addView(localSurfaceView, layoutParams);
mLocalVideoCanvas.view = localSurfaceView;
mAliRtcEngine.setLocalViewConfig(mLocalVideoCanvas, AliRtcVideoTrackCamera);
mAliRtcEngine.startPreview();

// Join the RTC room
mAliRtcEngine.joinChannel(token, null, null, null);

iOS (Swift)

// Local preview
let videoView = self.createVideoView(uid: self.userId)
let canvas = AliVideoCanvas()
canvas.view = videoView.canvasView
canvas.renderMode = .auto
canvas.mirrorMode = .onlyFrontCameraPreviewEnabled
canvas.rotationMode = ._0
self.rtcEngine?.setLocalViewConfig(canvas, for: AliRtcVideoTrack.camera)
self.rtcEngine?.startPreview()

// Join the RTC room
let ret = self.rtcEngine?.joinChannel(joinToken, channelId: nil, userId: nil, name: nil) {
    [weak self] errCode, channelId, userId, elapsed in
    if errCode == 0 {
        // Joined successfully
    } else {
        // Handle join failure
    }
}

2. Forward RTC streams to CDN (application server)

After the streamer pushes a stream to the RTC room:

  1. Subscribe to stream change events. Call CreateEventSub to receive notifications when users push or stop streams in the RTC room.

  2. Start a bypass streaming task. After receiving the stream push notification, call StartLiveMPUTask with MixMode=0 (single-stream forwarding without transcoding). Pass the CDN ingest URL, which must use the RTMP protocol. To generate this URL, see Generate ingest and playback URLs.

  3. Distribute the playback URL. Monitor CDN stream pushing callbacks to detect when forwarding succeeds, then distribute the playback URL to viewers. For callback setup details, see Callback settings.

3. Play the CDN stream (viewers)

When viewers receive the playback URL from the application server, create an ApsaraVideo Player instance and start playback. For the full player API reference, see ApsaraVideo Player SDK.

Note

Use HTTP-FLV instead of RTMP for the CDN playback URL. Both deliver the same content, but HTTP-FLV uses standard ports 80/443, offers better network optimization, and provides more stable playback with less stuttering and lower latency. RTMP's default port 1935 may be blocked by firewalls.

Android

AliPlayer aliPlayer = AliPlayerFactory.createAliPlayer(context);
aliPlayer.setAutoPlay(true);

UrlSource urlSource = new UrlSource();
// Use HTTP-FLV for CDN playback
urlSource.setUri("http://test.alivecdn.com/live/streamId.flv?auth_key=XXX");
aliPlayer.setDataSource(urlSource);
aliPlayer.prepare();

iOS (Objective-C)

self.cdnPlayer = [[AliPlayer alloc] init];
self.cdnPlayer.delegate = self;
self.cdnPlayer.autoPlay = YES;

// Use HTTP-FLV for CDN playback
AVPUrlSource *source = [[AVPUrlSource alloc] urlWithString:@"http://test.alivecdn.com/live/streamId.flv?auth_key=XXX"];
[self.cdnPlayer setUrlSource:source];
[self.cdnPlayer prepare];

Step 2: Start co-streaming (viewer joins as co-host)

image

Co-streamer side

1. Stop CDN playback

Destroy the player instance before joining the RTC room.

Android

aliPlayer.stop();
aliPlayer = null;

iOS

[self.cdnPlayer stop];
[self.cdnPlayer clearScreen];
self.cdnPlayer.playerView = nil;
Note

Stopping the CDN player is required, not an optional cleanup step. If the CDN player keeps running, the co-streamer's device plays the CDN audio and the RTC audio at the same time, which produces echo or doubled audio. After the CDN player is stopped, the device plays only the RTC audio and the echo disappears.

2. Join the RTC room

The co-streamer pushes a stream to the RTC room using the same process as the streamer.

3. Render the streamer's video

When the streamer's remote track becomes available, set up the rendering view in the onRemoteTrackAvailableNotify callback.

Android

@Override
public void onRemoteTrackAvailableNotify(String uid,
        AliRtcEngine.AliRtcAudioTrack audioTrack,
        AliRtcEngine.AliRtcVideoTrack videoTrack){
    handler.post(() -> {
        if(videoTrack == AliRtcVideoTrackCamera) {
            // Create and attach the remote rendering view
            SurfaceView surfaceView =
                mAliRtcEngine.createRenderSurfaceView(VideoChatActivity.this);
            surfaceView.setZOrderMediaOverlay(true);

            FrameLayout fl_remote = findViewById(R.id.fl_remote);
            if (fl_remote == null) return;

            fl_remote.addView(surfaceView,
                new FrameLayout.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.MATCH_PARENT));

            AliRtcEngine.AliRtcVideoCanvas remoteVideoCanvas =
                new AliRtcEngine.AliRtcVideoCanvas();
            remoteVideoCanvas.view = surfaceView;
            mAliRtcEngine.setRemoteViewConfig(remoteVideoCanvas, uid, AliRtcVideoTrackCamera);

        } else if(videoTrack == AliRtcVideoTrackNo) {
            // Remove the remote rendering view
            FrameLayout fl_remote = findViewById(R.id.fl_remote);
            fl_remote.removeAllViews();
            mAliRtcEngine.setRemoteViewConfig(null, uid, AliRtcVideoTrackCamera);
        }
    });
}

iOS (Swift)

func onRemoteTrackAvailableNotify(_ uid: String, audioTrack: AliRtcAudioTrack,
        videoTrack: AliRtcVideoTrack) {
    if audioTrack != .no {
        let videoView = self.videoViewList.first { $0.uidLabel.text == uid }
        if videoView == nil {
            _ = self.createVideoView(uid: uid)
        }
    }

    if videoTrack != .no {
        // Create or reuse the video view, then configure rendering
        var videoView = self.videoViewList.first { $0.uidLabel.text == uid }
        if videoView == nil {
            videoView = self.createVideoView(uid: uid)
        }

        let canvas = AliVideoCanvas()
        canvas.view = videoView!.canvasView
        canvas.renderMode = .auto
        canvas.mirrorMode = .onlyFrontCameraPreviewEnabled
        canvas.rotationMode = ._0
        self.rtcEngine?.setRemoteViewConfig(canvas, uid: uid, for: AliRtcVideoTrack.camera)
    } else {
        self.rtcEngine?.setRemoteViewConfig(nil, uid: uid, for: AliRtcVideoTrack.camera)
    }

    if audioTrack == .no && videoTrack == .no {
        // Remote user stopped all tracks -- clean up
        self.removeVideoView(uid: uid)
        self.rtcEngine?.setRemoteViewConfig(nil, uid: uid, for: AliRtcVideoTrack.camera)
    }
}

Streamer side

The streamer renders the co-streamer's video using the same onRemoteTrackAvailableNotify callback shown above.

Application server

After the co-streamer pushes a stream, call UpdateLiveMPUTask to update the existing bypass streaming task:

  • Set MixMode to 1 (stream mixing).

  • Configure the stream mixing layout for both the streamer and co-streamer.

Step 3: End co-streaming

image

Co-streamer side

1. Leave the RTC room

Android

mAliRtcEngine.stopPreview();
mAliRtcEngine.setLocalViewConfig(null, AliRtcVideoTrackCamera);
mAliRtcEngine.leaveChannel();
mAliRtcEngine.destroy();
mAliRtcEngine = null;

iOS (Swift)

self.rtcEngine?.stopPreview()
self.rtcEngine?.leaveChannel()
AliRtcEngine.destroy()
self.rtcEngine = nil

2. Resume CDN playback

Create a new ApsaraVideo Player instance and play the CDN stream.

Streamer side

The streamer stops pulling the co-streamer's audio and video stream. The rendering view is automatically cleaned up in the onRemoteTrackAvailableNotify callback when videoTrack changes to AliRtcVideoTrackNo.

Application server

After the co-streamer leaves the RTC room, call UpdateLiveMPUTask to update the stream mixing task:

  • Set MixMode back to 0 (bypass, single-stream forwarding).

The CDN live stream view automatically switches from showing both participants to the streamer only.

References