# Optimize video rendering (/en/realtime-media/broadcast-streaming/build/optimize-quality-and-connection/optimize-frame-rendering/windows)

> For AI agents: see the complete documentation index at [llms.txt](/llms.txt).

First frame output time is the duration between when a user joins a channel and when they first see the remote video. A shorter first frame output time reduces perceived wait time by rendering video more quickly.

    This guide describes two best practices to reduce video rendering time in Broadcast Streaming.

    ## Prerequisites [#prerequisites-3]

    Complete the steps in the [SDK Quickstart](/en/realtime-media/broadcast-streaming/quickstart) to build a basic Broadcast Streaming app.

    ## Understand the tech [#understand-the-tech-3]

    To reduce video rendering time, Agora provides the following solutions:

    * **Preload and initialize before joining the channel**
      Complete time-consuming operations ahead of time, such as preloading the channel, configuring the rendering view, and enabling accelerated rendering for audio and video frames.

    * **Join early, subscribe later**
      Join the channel in advance but delay subscribing to the audio and video stream. When the user triggers the join operation, subscribe to the host's stream and begin rendering immediately.

    The following table compares both solutions:

    | Characteristic       | Preload and initialize early                           | Join early, subscribe on demand                                        |
    | -------------------- | ------------------------------------------------------ | ---------------------------------------------------------------------- |
    | Applicable scenarios | Most audio and video use cases                         | Scenarios with very high requirements for first frame rendering speed  |
    | Core implementation  | Initialize and configure video settings before joining | Join the channel early without subscribing; subscribe only when needed |
    | Cost                 | Normal billing                                         | May incur additional channel usage fees                                |

    The following figure shows the time to output the first frame before optimization and with each solution:

    ![Optimize video rendering](https://assets-docs.agora.io/images/video-sdk/optimize-video-rendering-tech.jpg)

    ## Implement fast first-frame rendering [#implement-fast-first-frame-rendering-3]

    This section describes the implementation logic for both solutions.

    <Tabs defaultValue="preload">
      <TabsList>
        <TabsTrigger value="preload">
          Preload and initialize early
        </TabsTrigger>

        <TabsTrigger value="subscribe">
          Join early, subscribe on demand
        </TabsTrigger>
      </TabsList>

      <TabsContent value="preload">
        The following figure illustrates the essential steps:

        ### Sequence diagram for implementation [#sequence-diagram-for-implementation-6]

        ![Sequence diagram for optimized video rendering](https://assets-docs.agora.io/images/video-sdk/optimize-video-rendering-solution-1.svg)

        ### Set up a Video SDK instance [#set-up-a-video-sdk-instance-3]

        Creating and initializing the Video SDK engine takes time. To reduce first-frame display time, Agora recommends initializing the engine when the module is loaded, not when SDK functions are first called.

        <CalloutContainer type="info">
          <CalloutDescription>
            Initialize the engine only once. Avoid creating and destroying it multiple times.
          </CalloutDescription>
        </CalloutContainer>

        ```cpp
        class CAgoraQuickStartDlg {
        private:
            IRtcEngine* m_rtcEngine;

        public:
            // Create and initialize the engine during dialog initialization
            CAgoraQuickStartDlg() {
                m_rtcEngine = createAgoraRtcEngine();
                RtcEngineContext context;
                context.appId = "Your App ID";
                context.channelProfile = CHANNEL_PROFILE_LIVE_BROADCASTING;
                // ... other necessary configurations

                m_rtcEngine->initialize(context);
            }
        };
        ```

        ### Enable accelerated rendering [#enable-accelerated-rendering-3]

        Call [`enableInstantMediaRendering`](https://api-ref.agora.io/en/video-sdk/cpp/4.x/API/class_irtcengine.html#api_irtcengine_enableinstantmediarendering) to reduce the time it takes to render the first video frame and play audio after joining a channel.

        * Call this method **before** joining a channel. Ideally, call it right after engine initialization.
        * Both host and audience must call this method to benefit from faster rendering.
        * To disable this feature, destroy the engine with `release`, then reinitialize it.

        ```cpp
        // Enable accelerated rendering before joining the channel
        m_rtcEngine->enableInstantMediaRendering();
        ```

        ### Set a video scenario [#set-a-video-scenario-3]

        Use [`setVideoScenario`](https://api-ref.agora.io/en/video-sdk/cpp/4.x/API/class_irtcengine.html#api_irtcengine_setvideoscenario) to optimize performance for your specific use case. The SDK applies strategies tailored to the selected scenario.

        For example, for a one-on-one call, use `APPLICATION_SCENARIO_1V1`.

        ```cpp
        // Set the video scenario
        m_rtcEngine->setVideoScenarios(agora::rtc::APPLICATION_SCENARIO_1V1);
        ```

        ### Preload a channel [#preload-a-channel-3]

        Joining a channel involves acquiring server resources and establishing a connection. Call [`preloadChannel`](https://api-ref.agora.io/en/video-sdk/cpp/4.x/API/class_irtcengine.html#api_irtcengine_preloadchannel) to handle resource acquisition early and reduce join time.

        * The `token`, `channelId`, and `uid` must match the values used in `joinChannel`.
        * Call `preloadChannel` as soon as you retrieve the required info.
        * Don’t call `joinChannel` immediately after `preloadChannel`.

        ```cpp
        int CAgoraQuickStartDlg::prepareChannelInfo() {
            m_uid = get_uid();
            m_channelId = get_channel_info();
            m_token = getTokenFromServer(m_channelId, m_uid);

            // Preload the channel
            m_rtcEngine->preloadChannel(m_token, m_channelId, m_uid);
        }
        ```

        ### Set up the rendering view [#set-up-the-rendering-view-6]

        Setting the rendering view early ensures the first frame displays properly. If the view is not ready, the first frame might be skipped.

        If your app knows the remote user ID (For example, from Signaling), set the view immediately. Otherwise, use the `onUserJoined` callback.

        * **Set the remote view early:**

        ```cpp
        void CAgoraQuickStartDlg::onShowChannels(const char* channelId, uid_t remoteUid) {
            VideoCanvas canvas;
            canvas.uid = remoteUid;
            m_rtcEngine->setupRemoteVideo(canvas);
        }

        void CAgoraQuickStartDlg::onEIDUserJoined(uid_t uid, int elapsed) {
            // Already set
        }
        ```

        * **Set the view when the user joins:**

        ```cpp
        void EventHandler::onUserJoined(uid_t uid, int elapsed) {
            // Forward to UI logic
        }

        void CAgoraQuickStartDlg::onEIDUserJoined(uid_t uid, int elapsed) {
            VideoCanvas canvas;
            canvas.uid = uid;
            m_rtcEngine->setupRemoteVideo(canvas);
        }
        ```

        ### Monitor rendering performance [#monitor-rendering-performance-3]

        Use [`startMediaRenderingTracing`](https://api-ref.agora.io/en/video-sdk/cpp/4.x/API/class_irtcengine.html#api_irtcengine_startmediarenderingtracing) to monitor first-frame rendering metrics. Results are reported via [`onVideoRenderingTracingResult`](https://api-ref.agora.io/en/video-sdk/cpp/4.x/API/class_irtcengineeventhandler.html#callback_irtcengineeventhandler_onvideorenderingtracingresult).

        <CalloutContainer type="info">
          <CalloutDescription>
            Call this method when the user initiates joining. For example, on a **Join** button tap. This gives accurate first-frame timing.
          </CalloutDescription>
        </CalloutContainer>

        ```cpp
        void on_join_clicked() {
            m_rtcEngine->startMediaRenderingTracing();
            m_rtcEngine->joinChannel(token, channelId, uid, options);
        }
        ```

        ### Join a channel [#join-a-channel-3]

        Call [`joinChannel`](https://api-ref.agora.io/en/video-sdk/cpp/4.x/API/class_irtcengine.html#api_irtcengine_joinchannel2) to enter the channel. To speed up first-frame playback, avoid delays like fetching a token in this method.

        If you can’t retrieve a token early, consider using a [wildcard token](/en/realtime-media/broadcast-streaming/build/authenticate-users/deploy-token-server#generate-wildcard-tokens).

        ```cpp
        int CAgoraQuickStartDlg::prepareChannelInfo() {
            m_uid = get_uid();
            m_channelId = get_channel_info();
            m_token = getTokenFromServer(m_channelId, m_uid);
        }

        int CAgoraQuickStartDlg::joinChannel() {
            ChannelMediaOptions options;
            return m_rtcEngine->joinChannel(m_token, m_channelId, m_uid, options);
        }
        ```

        ### Optimize callback performance [#optimize-callback-performance-3]

        The SDK runs callbacks like `onJoinChannelSuccess` on the same thread. If one callback is slow, it can delay others—including rendering events.

        <CalloutContainer type="info">
          <CalloutDescription>
            Don’t block the callback thread with network calls, file I/O, or heavy processing.
          </CalloutDescription>
        </CalloutContainer>

        #### Best practices [#best-practices-3]

        * Avoid complex operations in `onJoinChannelSuccess`.
        * Don’t block `onUserJoined` or other rendering-related callbacks.
        * Use background threads for heavy logic.
      </TabsContent>

      <TabsContent value="subscribe">
        The following figure illustrates the essential steps:

        ### Sequence diagram for implementation [#sequence-diagram-for-implementation-7]

        ![Sequence diagram for optimized video rendering](https://assets-docs.agora.io/images/video-sdk/optimize-video-rendering-solution-2.svg)

        ### Set up the rendering view [#set-up-the-rendering-view-7]

        If you know the host’s user ID before joining the channel, call [`setupRemoteVideoEx`](https://api-ref.agora.io/en/video-sdk/cpp/4.x/API/class_irtcengineex.html#api_irtcengineex_setupremotevideoex) as early as possible to set up the rendering view. This ensures the rendering pipeline is initialized in advance, helping avoid delays in displaying the first decoded frame.

        If the host’s user ID is not available beforehand, wait for the `onUserJoined` callback, then call [`setupRemoteVideoEx`](https://api-ref.agora.io/en/video-sdk/cpp/4.x/API/class_irtcengineex.html#api_irtcengineex_setupremotevideoex).

        ```cpp
        // Set the host’s rendering view
        VideoCanvas canvas;
        canvas.uid = far_next_channel.remoteUid;
        canvas.view = getView();  // Replace with your rendering view
        m_rtcEngine->setupRemoteVideoEx(canvas, connection);
        ```

        ### Join a channel without automatically subscribing [#join-a-channel-without-automatically-subscribing-3]

        Joining a channel typically takes the most time before the first video frame appears. For use cases like fast channel switching, delay subscribing to media streams to speed up rendering:

        1. Call [`joinChannelEx`](https://api-ref.agora.io/en/video-sdk/cpp/4.x/API/class_irtcengineex.html#api_irtcengineex_joinchannelex) to join the channel.
        2. In [`ChannelMediaOptions`](https://api-ref.agora.io/en/video-sdk/cpp/4.x/API/class_channelmediaoptions.html), set `autoSubscribeAudio` and `autoSubscribeVideo` to `false`.
        3. Subscribe manually when the user is ready to view content.

           ```cpp
           // Set channel media options
           ChannelMediaOptions options;
           options.channelProfile = CHANNEL_PROFILE_LIVE_BROADCASTING;
           options.clientRoleType = CHANNEL_ROLE_AUDIENCE;
           options.autoSubscribeAudio = false;
           options.autoSubscribeVideo = false;

           RtcConnection connection(far_next_channel.channel_id.c_str(), m_localUid);

           // Join the channel without subscribing
           m_rtcEngine->joinChannelEx(APP_TOKEN, connection, options, m_handler);
           ```

        ### Subscribe to streams and start rendering [#subscribe-to-streams-and-start-rendering-3]

        When the user chooses to view content:

        1. Resume media subscription using [`muteRemoteVideoStreamEx`](https://api-ref.agora.io/en/video-sdk/cpp/4.x/API/class_irtcengineex.html#api_irtcengineex_muteremotevideostreamex) and [`muteRemoteAudioStreamEx`](https://api-ref.agora.io/en/video-sdk/cpp/4.x/API/class_irtcengineex.html#api_irtcengineex_muteremoteaudiostreamex).
        2. Call [`startMediaRenderingTracingEx`](https://api-ref.agora.io/en/video-sdk/cpp/4.x/API/class_irtcengineex.html#api_irtcengineex_startmediarenderingtracingex) to log rendering metrics.
        3. The SDK reports results in the [`onVideoRenderingTracingResult`](https://api-ref.agora.io/en/video-sdk/cpp/4.x/API/class_irtcengineeventhandler.html#callback_irtcengineeventhandler_onvideorenderingtracingresult) callback, which you can use for performance analysis.

           ```cpp
           void CAgoraQuickStartDlg::switchNextChannel() {
               RtcConnection connection(next_channel.channel_id.c_str(), localUid);

               // Start video rendering tracing
               m_rtcEngine->startMediaRenderingTracingEx(connection);

               // Resume remote media subscriptions
               m_rtcEngine->muteRemoteVideoStreamEx(next_channel.remoteUid, false, connection);
               m_rtcEngine->muteRemoteAudioStreamEx(next_channel.remoteUid, false, connection);
           }
           ```
      </TabsContent>
    </Tabs>

    ## Troubleshooting [#troubleshooting-3]

    Refer to [Slow first-frame rendering of remote video when using the Agora Video SDK](/en/api-reference/faq/quality/optimize_video_rendering).

    
  
