Skip to content

Simulcast layers paused by dynacast are re-enabled after every publisher renegotiation (ICE restart, resume, new track) #4906

Closed

Description

@pabloFuente

Bug description

When dynacast has paused the upper simulcast layers of a publisher, any renegotiation of the publisher
PeerConnection makes the browser send those layers again, and livekit-server never pauses them back.
The layers stay on until something changes that track's subscribed quality (a subscriber joining,
leaving or resizing), which in a stable connection could theoretically be for the rest of the Room.

Nothing breaks functionally (subscribers still get the layer they need), but dynacast kind of loses its reason to exist: the publisher uploads layers nobody watches, which ultimately wastes valuable upstream bandwidth.

Root cause

pkg/rtc/transport.go calls se.SetIgnoreRidPauseForRecv(true) (#4129), so the SFU's answer drops the
RFC 8853 pause markers the browser put in its offer:

offer  (browser): a=simulcast:send q;~h;~f
answer (SFU):     a=simulcast:recv q;h;f

Chrome applies the answer's pause state to the sender: h and f go back to active: true. The SFU's
dynacast state has not changed, so it only notifies changes and never sends the pause again.

The comment next to the setting says layer enable/disable is signalled through the signalling channel,
but nothing re-sends it after the renegotiation.

Server

  • Version: v1.13.7
  • Environment: local

Client

  • SDK: client-sdk-js in latest Google Chrome
  • Version: v2.22.3

To Reproduce

  1. A publisher with simulcast (3 layers q/h/f) and dynacast enabled, plus a subscriber that only needs the low layer (small video element, adaptiveStream).
  2. Wait for dynacast to pause the upper layers: the server logs sending max subscribed quality, and sender.getParameters().encodings shows q=true h=false f=false.
  3. Trigger any publisher renegotiation, for example:
    • room.localParticipant.engine.pcManager.triggerIceRestart() (what a resume does), or
    • room.localParticipant.engine.pcManager.createAndSendPublisherOffer(), or
    • publishing another track (e.g. a screen share).
  4. Check the sender encodings and the outbound-rtp stats of the camera again.

Below there is a copy-paste way to reproduce the problem.

Click to expand

Run latest livekit-server...

docker run --rm --network host livekit/livekit-server --dev

... and simply serve this html and connect through http://localhost:XXXX:

<!doctype html>
<html>
<body>
<button id="reneg">Renegotiate the publisher (ICE restart)</button>
<pre id="log"></pre>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/livekit-client.umd.js"></script>
<script>
const LIVEKIT_URL = 'ws://localhost:7880', API_KEY = 'devkey', API_SECRET = 'secret', ROOM = 'repro';
const { Room, RoomEvent, LocalVideoTrack, VideoQuality } = LivekitClient;
const log = (s) => { console.log(s); document.getElementById('log').textContent += s + '\n'; };

// Access token signed in the page (dev keys only)
async function token(identity) {
  const b64 = (s) => btoa(s).replace(/=/g, '').replace(/\+/g, '-').replace(/\//g, '_');
  const now = Math.floor(Date.now() / 1000);
  const data = b64(JSON.stringify({ alg: 'HS256', typ: 'JWT' })) + '.' + b64(JSON.stringify({
    iss: API_KEY, sub: identity, nbf: now, exp: now + 3600,
    video: { room: ROOM, roomJoin: true, canPublish: true, canSubscribe: true },
  }));
  const key = await crypto.subtle.importKey('raw', new TextEncoder().encode(API_SECRET),
    { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']);
  const sig = await crypto.subtle.sign('HMAC', key, new TextEncoder().encode(data));
  return data + '.' + b64(String.fromCharCode(...new Uint8Array(sig)));
}

(async () => {
  // 1280x720 animated canvas as the camera, so that simulcast has 3 layers: q, h and f
  const canvas = Object.assign(document.createElement('canvas'), { width: 1280, height: 720 });
  const ctx = canvas.getContext('2d');
  setInterval(() => {
    for (let i = 0; i < 20; i++) {
      ctx.fillStyle = `hsl(${Math.random() * 360}, 80%, 50%)`;
      ctx.fillRect(Math.random() * 1280, Math.random() * 720, 160, 160);
    }
  }, 33);

  // Publisher with simulcast and dynacast
  const publisher = new Room({ dynacast: true });
  await publisher.connect(LIVEKIT_URL, await token('publisher'));
  await publisher.localParticipant.publishTrack(
    new LocalVideoTrack(canvas.captureStream(30).getVideoTracks()[0]), { simulcast: true });

  // Subscriber that only wants the low layer: dynacast pauses h and f after a few seconds
  const subscriber = new Room();
  subscriber.on(RoomEvent.TrackSubscribed, (_track, publication) => publication.setVideoQuality(VideoQuality.LOW));
  await subscriber.connect(LIVEKIT_URL, await token('subscriber'));

  // Every second: what the publisher is sending, layer by layer
  const pc = publisher.localParticipant.engine.pcManager.publisher._pc;
  const sender = pc.getSenders().find((s) => s.track?.kind === 'video');
  const lastBytes = {};
  setInterval(async () => {
    const kbps = {};
    (await pc.getStats()).forEach((r) => {
      if (r.type === 'outbound-rtp' && r.kind === 'video') {
        kbps[r.rid] = Math.round((r.bytesSent - (lastBytes[r.rid] ?? r.bytesSent)) * 8 / 1000);
        lastBytes[r.rid] = r.bytesSent;
      }
    });
    log(new Date().toISOString().slice(11, 19) + '  ' + sender.getParameters().encodings
      .map((e) => `${e.rid}: ${e.active ? 'on ' : 'off'} ${String(kbps[e.rid] ?? 0).padStart(5)} kbps`).join(' | '));
  }, 1000);

  // Any renegotiation of the publisher PC does it; this is the ICE restart livekit-client does to resume
  document.getElementById('reneg').onclick = async () => {
    log('--- renegotiating the publisher PeerConnection');
    await publisher.localParticipant.engine.pcManager.triggerIceRestart();
    setTimeout(() => log('offer:  ' + pc.localDescription.sdp.match(/a=simulcast:.*/)[0].trim() +
      '\nanswer: ' + pc.remoteDescription.sdp.match(/a=simulcast:.*/)[0].trim()), 500);
  };
})();
</script>
</body>
</html>

You will see this behavior in the browser after restarting the ICE connetion:

Image

As you can see, the ICE restart breaks the dynacast behavior in the publisher.

Expected behavior

h and f stay paused, since the subscribed quality did not change.

Actual behavior

h and f are active: true again and keep sending. For example, with a 1080p camera, that's
about 320 kbps (h) plus 1 Mbps (f) on top of the ~140 kbps of q.


Possible fixes

  1. Re-send the committed subscribed qualities after each publisher answer (server side, covers every SDK). Only the qualities already committed are re-sent: nothing new is committed, so a debounced downgrade stays pending. It has to be delayed, because livekit-client's handleSignalResponse does not await onAnswer. An update right behind the answer is handled before setRemoteDescription has applied it, sees the layers still paused, and does nothing. We use 1 s:

    // participant.go, onPublisherAnswer
    defer p.resendSubscribedQualities() // after 1 s, ResendCommittedQuality() on each published video track's dynacast
    
    // dynacastmanagervideo.go
    func (d *dynacastManagerVideo) ResendCommittedQuality() {
    	d.lock.Lock()
    	defer d.lock.Unlock()
    	if len(d.committedMaxSubscribedQuality) > 0 {
    		d.enqueueSubscribedQualityChange()
    	}
    }

    We run this in our fork. With it, the layers come back briefly when the answer is applied, and are paused again about a second later.

  2. Answer with ~ for the layers dynacast currently has paused, i.e. keep the pause markers in sync with dynacast instead of dropping them. This fixes it at the root, but Do not pause rid in SDP #4129 disabled the markers for reasons that aren't documented.

  3. Client side: re-apply the last subscribed qualities once setRemoteDescription(answer) completes. This is race-free, but has to be done in every single SDK.

What was the motivation for #4129, and which approach would you prefer?

Activity

  1. boks1971 commented on Sep 24, 2026

    @boks1971
    Contributor

    #4129 was due to the clash of signalling protocol and SDP.

    More details in pion/webrtc#3289

    When signalling layer paused, browser put pause in SDP and the SDP answer sent it back. Browser used that and did not react to signalling protocol updates IIRC.

  2. boks1971 commented on Sep 24, 2026

    @boks1971
    Contributor

    Guess it is the reverse problem now. The answer is being interpreted as "enable" this layer.

    Probably have to re-send dynacast message after every answer like you mentioned.

  3. boks1971 commented on Sep 24, 2026

    @boks1971
    Contributor

    #4129 was due to the clash of signalling protocol and SDP.

    More details in pion/webrtc#3289

    When signalling layer paused, browser put pause in SDP and the SDP answer sent it back. Browser used that and did not react to signalling protocol updates IIRC.

    I think this was more of a race and which ones client applied. Signalling asking client to enable layers, but a pending answer applied turned off the layers. The change was to ensure that signalling is the source of truth. But, I guess an answer which inverts the offer state is applied by the browser.

  4. pabloFuente commented on Sep 24, 2026

    @pabloFuente
    ContributorAuthor

    I have just proposed a PR with what is seems the agreed solution: re-send dynacast message after every answer (#4907)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions