logo
On this page

Use CDN for Live Streaming

2024-01-02

Overview

ZEGO Express SDK supports publishing streams to CDN (Content Delivery Network), including two functions: relaying to CDN and direct publishing to CDN. Based on this function, developers can connect RTC products and CDN live streaming products, making it convenient for users to directly watch and listen to live content from web pages or third-party players. To ensure security, CDN authentication is enabled by default when publishing streams to CDN.

To prevent attackers from stealing or forging your publishing stream URL address, you can refer to CDN Stream Publishing Authentication to improve the security of your publishing stream usage.

Warning

When initiating relay to CDN or direct publishing to CDN, please note that CDN has requirements for audio and video formats. The publishing end audio supports AAC and MP3, and video supports H.264 and H.265 (requires CDN configuration).

Relay to CDN

Relaying to CDN refers to the process of pushing audio and video streams from ZEGO audio and video cloud to ZEGO's own CDN or third-party CDN.

Relaying to CDN includes the following three methods:

Relay MethodDescription
Default Relay to CDNAll live streams published by users using ZEGO Express SDK to ZEGO audio and video cloud will be relayed to CDN. Currently, only ZEGO's own CDN is supported.
Side-by-side Relay to CDNDevelopers can customize and specify streams on ZEGOCLOUD to be relayed to CDN, supporting ZEGO's own CDN and third-party CDN.
Stream Mixing Relay to CDNIn stream mixing scenarios, output streams can also be relayed to CDN, supporting ZEGO's own CDN and third-party CDN.

Direct Publishing to CDN

Direct publishing to CDN refers to the process of pushing audio and video streams directly from the local client to the CDN. Users can watch directly from web pages or third-party players through the playing stream URL address. However, because the direct publishing to CDN function does not pass through ZEGOCLOUD during network transmission, developers cannot use ZEGO's real-time audio and video services.

Function Comparison

The descriptions and usage scenarios of the two functions are as follows:

FunctionDescriptionUsage Scenarios
Relay to CDN (Recommended)The publishing stream first passes through ZEGOCLOUD, and then is relayed to CDN by ZEGOCLOUD. You can use ZEGO's real-time audio and video services, which can be used in scenarios that require co-hosting interaction.Developers have business cooperation with third-party CDN and want to use the original third-party CDN streaming media network distribution service while also using ZEGO Express SDK for real-time co-hosting interaction. It is applicable to business scenarios with co-hosting interaction requirements, such as show live streaming, audio chat rooms, etc.
Direct Publishing to CDNThe publishing stream does not pass through ZEGOCLOUD and is directly pushed to CDN. ZEGO's real-time audio and video services cannot be used, applicable to single live streaming scenarios (no interaction required).Applicable to situations where developers do not need to use real-time co-hosting interaction and other services, such as e-commerce live streaming, game live streaming, large classes, etc.

Prerequisites

Before using CDN for live streaming, please ensure:

Warning

The CDN live streaming function is not enabled by default. Please enable it yourself in the ZEGO Console before use (for enabling steps, please refer to "CDN" in Project Management - Service Configuration), or contact ZEGOCLOUD Technical Support to enable it.

Relay to CDN

Note

If you choose to use the direct publishing to CDN function, you do not need to perform all steps in this section. Please refer to Direct Publishing to CDN.

Initialize and Login Room

Please refer to "Create engine" and "Login room" in Quick Start - Implementing Video Call.

Start Publishing Stream

Please refer to "Publish stream" in Quick Start - Implementing Video Call.

Start Relay

After the publishing stream is successful, call the addPublishCdnUrl interface to add the URL for dynamic relay to CDN, so that the audio and video stream that has been successfully published to ZEGO real-time cloud can be dynamically relayed to third-party CDN. The supported relay address format is "rtmp".

Note
  • If developers need to relay to multiple third-party CDN vendors, they can use the same stream ID to call the addPublishCdnUrl interface multiple times (URLs need to be different).
  • After developers relay to multiple third-party CDNs, they also need to call multiple times to stop all relayed streams when stopping relay.
  • After developers relay to multiple third-party CDNs, they can obtain status change notifications for each relayed stream from the list parameter of the CDN callback status notification publisherRelayCDNStateUpdate.
// After publishing stream successfully, start relaying to CDN

// Stream ID used when publishing stream
let streamID = "STREAM_ID";
// CDN address to be relayed, please fill in according to the actual URL, streamID is the stream name of publishing stream, can be customized
let URL = "rtmp://publishing domain/ingest point/streamID";
ZegoExpressEngine.instance().addPublishCdnUrl(streamID, URL).then((result) => {
    if(result.errorCode == 0) {
        // Relay successful
    } else {
        // Relay failed, possibly due to network reasons causing relay request sending to fail
    }
});

(Optional) Listen to CDN Relay Status Notification

Add/Remove Relay CDN Address Status Callback

Developers can register publisherRelayCDNStateUpdate to get add/remove relay CDN address status callbacks. After ZEGO RTC server relays the audio and video stream to CDN, if the CDN relay status changes, such as relay stopping or relay retrying, this callback will be received.

Note

Developers can use this callback to determine whether the audio and video stream relayed to CDN is normal:

  • If it is abnormal, further locate the cause of the abnormal audio and video stream relayed to CDN based on the abnormal reason, and take corresponding disaster recovery strategies.
  • If you do not understand the cause of the abnormality, you can contact ZEGOCLOUD Technical Support to analyze the specific cause of the abnormality.
ZegoExpressEngine.instance().on("publisherRelayCDNStateUpdate", (streamID, infoList) => {
    console.log(`publisherRelayCDNStateUpdate:streamID:${streamID}, infoList:${JSON.stringify(infoList)}`);
});

Detailed Explanation of Relay CDN Information

Relay CDN information ZegoStreamRelayCDNInfo contains the URL of CDN publishing stream, relay status, reason for relay status change, and time when the status occurred. All parameters in ZegoStreamRelayCDNInfo are as follows:

Parameter NameDescription
urlURL of CDN publishing stream.
stateRelay status
updateReasonReason for relay status change.
stateTimeTime when the status occurred.

Among them, state values are as follows:

Enumeration ValueDescription
ZegoStreamRelayCDNState.NoRelayNo relay status, in this state before relay. If the relay process encounters continuous abnormalities, such as incorrect relay address, it will enter the no relay status.
ZegoStreamRelayCDNState.RelayRequestingRequesting relay status. After the relay operation is successfully executed, it will enter the requesting relay status. Usually, the application interface is displayed through this status. If an interruption occurs due to poor network quality, the SDK will internally retry and will also return to the requesting relay status.
ZegoStreamRelayCDNState.RelayingRelaying status. Entering this status indicates that relay has been successful.

updateReason values are as follows:

Enumeration ValueDescription
ZegoStreamRelayCDNUpdateReason.NoneNone.
ZegoStreamRelayCDNUpdateReason.ServerErrorServer error.
ZegoStreamRelayCDNUpdateReason.HandshakeFailedHandshake failed.
ZegoStreamRelayCDNUpdateReason.AccessPointErrorAccess point error.
ZegoStreamRelayCDNUpdateReason.CreateStreamFailedCreate stream failed.
ZegoStreamRelayCDNUpdateReason.BadNameStream ID is invalid.
ZegoStreamRelayCDNUpdateReason.CDNServerDisconnectedCDN server actively disconnected.
ZegoStreamRelayCDNUpdateReason.DisconnectedActively disconnected.
ZegoStreamRelayCDNUpdateReason.MixStreamAllInputStreamClosedAll input stream sessions of stream mixing are closed.
ZegoStreamRelayCDNUpdateReason.MixStreamAllInputStreamNoDataAll input streams of stream mixing have no data.
ZegoStreamRelayCDNUpdateReason.MixStreamServerInternalErrorStream mixing server internal error.

Stop Relay

Call the removePublishCdnUrl interface to delete the URL dynamically relayed to CDN. When calling the removePublishCdnUrl interface to stop relay, please ensure that the current stream streamID exists.

Warning

This interface will not stop the audio and video stream published to ZEGOCLOUD.


// Stream ID used when publishing stream
let streamID = "STREAM_ID";
// CDN address to stop relay, please fill in according to the actual URL, streamID is the stream name of publishing stream
let URL = "rtmp://publishing domain/ingest point/streamID";
ZegoExpressEngine.instance().removePublishCdnUrl(streamID, URL).then((result) => {
    if(result.errorCode == 0) {
        // Stop relay successful
    } else {
       // Stop relay failed, possibly due to network reasons causing stop relay request sending to fail
    }
});

Direct Publishing to CDN

Note

If you choose to use the relay to CDN function, you do not need to perform all steps in this section. Please refer to Relay to CDN.

Start Direct Publishing to CDN

Before publishing stream, call the enablePublishDirectToCDN interface to directly publish audio and video streams to CDN.

Warning
  • After calling the enablePublishDirectToCDN interface, calling addPublishCdnUrl and removePublishCdnUrl to dynamically relay to CDN will no longer take effect, because these two interfaces relay or stop relaying audio and video streams from ZEGOCLOUD to CDN. If audio and video streams are directly published to CDN, they cannot be dynamically relayed to CDN through ZEGOCLOUD.
  • If error code 1000038 occurs when calling the enablePublishDirectToCDN interface, possible problems are: domain name configuration error, media network exception or media network link is empty, please contact ZEGOCLOUD Technical Support.
let config = new ZegoCDNConfig();
// URL needs to be filled in by developers according to the actual situation, streamID is the stream name of publishing stream, can be customized
config.url = "rtmp://publishing domain/ingest point/streamID";
ZegoExpressEngine.instance().enablePublishDirectToCDN(true, config);
ZegoExpressEngine.instance().startPublishingStream("STREAM_ID");

Stop Direct Publishing to CDN

To stop direct publishing to CDN, call the stopPublishingStream interface to stop publishing stream.

After stopping publishing stream, if the next publishing stream does not need direct publishing to CDN, you can call the enablePublishDirectToCDN interface and pass the value "false" to turn off the direct publishing to CDN function. Calling this interface during publishing stream will not affect this publishing stream.

ZegoExpressEngine.instance().stopPublishingStream();
let config = new ZegoCDNConfig();
ZegoExpressEngine.instance().enablePublishDirectToCDN(false, config);

Audience Plays Stream

  • When the publishing party directly publishes to CDN, the playing party can directly play stream through streamID. Please refer to "Play stream" in Quick Start - Implementation.

  • After the audio and video stream is successfully relayed to CDN, when developers want users to play stream from CDN, they need to use the custom playing stream method that passes in the URL, and cannot play stream through the stream ID. For the operation steps of URL playing stream, please refer to "Configure Playing Stream Parameters" and "Start Playing Stream" in Play Stream by URL.

Previous

Multi-Stream Mixing

Next

CDN Stream Publishing Authentication