Skip to content

refactor: announce the microphone before capture is ready - #2298

Open
lukasIO wants to merge 15 commits into
sxian/CLT-3610/fast-track-publication-session-apifrom
lukas/CLT-3610/optimistic-publish
Open

lukasIO wants to merge 15 commits into
sxian/CLT-3610/fast-track-publication-session-apifrom
lukas/CLT-3610/optimistic-publish

Conversation

@lukasIO

@lukasIO lukasIO commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

#2292 announces the microphone before capture, but only through a versioned symbol bridge, Symbol.for('livekit.internal.sessionPublication.v1'), and only inside the JOIN. Components Session must call prepare(), then a special connect(url, token, opts, publications), then attachTrack(). Both repos must keep that protocol in sync. Apps that do not use Session cannot get the gain, and a setMicrophoneEnabled() call during or after connect still waits for capture. This PR targets the branch of #2292.

Change

  • setMicrophoneEnabled() announces the microphone before capture, in any room state. A call before connect() puts the reservation into the JOIN. A later call registers it right after the JOIN answer while connecting, or at once in a connected room.
  • Each reservation gets a sender without a track. Its CID is the track id in the stream MSID, read from the initial offer or from a probe offer. The AddTrack request carries muted: true, so others see a muted microphone while the permission prompt is open. Capture attaches with replaceTrack. The unmute goes out right before replaceTrack, because the SFU drops media of a track it thinks is muted.
  • Session's existing Promise.all([connect, setMicrophoneEnabled]) gets the gain without code changes. Any app that starts the same way gets it too. setCameraEnabled() still publishes after capture, because the camera's size is unknown before.
  • publishTrack() called before the signal connects reserves a microphone or camera track that already exists, for example from a pre-join screen. The format comes from the track, the stereo decision is the one publishTrack() makes anyway, and the AddTrack request carries the track's own mute state. The reservation is made before the first await in publishTrack(). So Promise.all([connect(), publishTrack()]) puts the track into the JOIN in either order. Like any publication made before the signal connects, it gives up after 15 s.
  • A mono reservation now accepts a stereo capture, as publishing after capture does. Only a stereo reservation needs a stereo capture.
  • Removed: the symbol bridge and the claim handshake between the room and the reservation. Also removed: the prepare hook of the initial offer and the peer connection rebuild before the JOIN.

Failure case

The permission can be denied, or capture can fail. Then the reservation is cancelled, and others see the muted microphone appear and go away. A sender that went into the JOIN is removed only after the JOIN answer is applied. A failed JOIN drops the attempt's peer connection, so a retry does not add the senders twice. A setMicrophoneEnabled() without a later connect() waits until disconnect or dispose. Before, the publish attempt gave up after 15 s.

Verified

  • npx tsc --noEmit passes. npx vitest run --dir src: 66 files, 1186 passed, 1 skipped. New tests cover the muted AddTrack request, a capture that finishes before its reservation is registered, and the CID lookup in reservedSenderCid. Another test checks that publishTrack() creates its reservation in the same turn as the call, so an added await in front of it fails.

  • pnpm build, pnpm check:core and pnpm test:public (45 passed) pass.

  • Comparison with perf: prepare Session publications internally alongside device capture (CLT-3610) #2292 and 2.25.0, same app code, against a local livekit-server --dev 1.13.10. Dummynet adds 100 ms each way to every path to the server: signaling, ICE and media, for both participants. A listener stands in for the agent; "heard" is its first audio samples or first decoded video frame. perf: prepare Session publications internally alongside device capture (CLT-3610) #2292 starts Session through its bridge. Medians of 5 runs, in ms from the start:

    Scenario 2.25.0 perf: prepare Session publications internally alongside device capture (CLT-3610) #2292 This PR
    Session start, no permission wait: mic published / heard 672 / 971 594 / 942 429 / 944
    Session start, permission 800 ms 1078 / 1335 831 / 1112 835 / 1123
    Session start, permission 2 s 2289 / 2564 2045 / 2330 2043 / 2338
    Pre-join mic + camera: published / audio heard / video heard 677 / 940 / 1164 684 / 949 / 1239 439 / 961 / 1189
    Mic after join, permission 800 ms: published / heard 2196 / 2469 2187 / 2457 1942 / 2237

    For Session start, this PR and perf: prepare Session publications internally alongside device capture (CLT-3610) #2292 are the same within about 10 ms. A microphone enabled after joining is heard 220 ms sooner than with either. Pre-join tracks publish about 245 ms sooner, but first media at the listener is not sooner, because media waits for the user's own ICE and DTLS setup, about 590 ms in. The early unmute brings first audio for a Session start without a permission wait from 996 to 944 ms.

  • In traces with delay on signaling only, a call before connect() gets trackPublished with the JOIN answer, and no separate addTrack is sent. The same holds for Promise.all([connect(), publishTrack()]) with a microphone captured first. A call while connecting or connected sends the muted addTrack right after the JOIN answer, or at once. In all cases the microphone is published about 25 ms after capture. Earlier runs in this setup overstated the gain for first media, because media had no delay there.

  • scripts/benchmark-prepared-publication.mjs passes all 12 rows. With single PC, the reserved microphone is published 4 ms after capture, with no addTrack or offer, against 167 ms without a reservation. In dual-PC mode, a connect() that runs together with setMicrophoneEnabled() waits for capture. 2.25.0 does the same, so the script checks the JOIN timing only for single PC.

For reviewers

@xianshijing-lk: the greeting gain in the #2292 benchmark comes from the local dev server. That server batches the join update of a participant without a publication for up to 3 s. The stand-in agent was already in the room, so it saw the user late. With a real dispatched agent, or on LiveKit Cloud, the greeting does not depend on the publication mode.

Not done yet

  • Components Session still calls the bridge. The notes in perf: prepare Session publications internally alongside device capture (CLT-3610) #2292 say that it falls back to ordinary publication without the bridge. I did not test this. Its check-session-publication-contract.mjs needs to go.
  • Not tested: a denied permission in a connected room, a full reconnect while capture is pending, and a JOIN retry with a reservation.
  • The existing mute reconcile in LocalParticipant.updateInfo sends a second unmute about 160 ms after attach.
  • No unit test drives the engine's registration code. Local traces cover it, but the trace script is not part of this PR.
  • Camera reservations are covered by the live check only, not by a unit test.

lukasIO and others added 2 commits November 24, 2026 12:37
With `engine.optimisticPublications` set, prepared senders are not bundled
into the JOIN. Once the JOIN answer is applied, the engine adds the same
trackless transceivers, reads their CIDs from a probe offer, sends the
AddTrack requests and renegotiates. Attaching the captured track reuses the
prepared replaceTrack path, so no signaling waits for capture.

scripts/trace-agent-subscription.mjs traces and benchmarks current,
prepared and optimistic publication against a stand-in or real agent.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…Session bridge

The prepared publication path was reachable only through the versioned
`livekit.internal.sessionPublication.v1` symbol: a prepare/connect/attach
protocol that Components had to implement and keep in sync, and that apps
outside Session could not use.

Remove the bridge. When setMicrophoneEnabled() is called while the room is
disconnected, before or alongside connect(), the room reserves the
microphone sender from the capture and publish options and the next
connect() claims it. Session's existing Promise.all([connect,
setMicrophoneEnabled]) gets the gain unchanged, and so does any app that
starts the same way. Calls while connecting or connected publish as before;
the camera still publishes after capture.

The benchmarks now start through setMicrophoneEnabled/setCameraEnabled and
turn the reservation off for their baseline.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@lukasIO lukasIO self-assigned this Nov 24, 2026
lukasIO and others added 4 commits November 24, 2026 12:55
…nnect

A setMicrophoneEnabled() call made after connect() started fell back to
publishing after capture. While the room is connecting, the room now adds
the reservation to the connect's own list, which the engine shares. If the
JOIN offer is not built yet, the reservation goes into it. Otherwise the
engine registers it right after the JOIN answer: it adds the sender, sends
addTrack and renegotiates without waiting for capture.

The engine now always runs that registration after the JOIN, one call at a
time so a reservation is never registered twice, and gives up when the JOIN
answer does not arrive within the peer connection timeout.

The trace takes MIC_START_MS to start the microphone after connect().

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
setMicrophoneEnabled() now reserves the microphone publication in any room
state. The engine registers every waiting reservation as soon as the
publisher is negotiated: at once when connected, right after the JOIN
answer when connecting, after the next connect when disconnected. It adds a
sender without a track, reads the CID from a probe offer, sends the
AddTrack request with `muted: true` and renegotiates. Capture attaches with
replaceTrack and unmutes, so others see a muted microphone instead of a
silent one while the permission prompt is open.

With one path, the JOIN no longer carries publications. This removes the
AddTrack requests in the JoinRequest, the prepare hook of the initial
offer, the PC rebuild before the JOIN when a reservation fails, the
startup/connecting reservation lists and the claim/connectionReady
handshake in the room, and the optimisticPublications switch. It costs
about one round trip of mic-ready when capture finishes before connect.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
When capture finished before the engine registered the reservation,
attachTrack() marked the publication as attaching, the engine no longer
counted it as waiting, and the attachment waited forever. An attachment now
excludes the publication from registration only after registration settled.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A setMicrophoneEnabled() call made before connect() now puts its
reservation into the JOIN instead of registering it after the JOIN answer,
which saves the renegotiation round trip. The engine adds the sender
before it builds the initial offer, then reads the CID from that offer, so
the initial offer needs no prepare hook. Later reservations still register
right after the JOIN answer or at once when connected, through the same
helpers.

A sender that went into the JOIN is removed only after the JOIN answer is
applied, because it is not in a local description before that. A failed
JOIN drops the attempt's peer connection, so a retry does not add the
senders twice.

reservedSenderCid() maps a reserved stream to its CID and has its own test.
A reservation manager would only forward peer connection calls, so the
engine keeps this code.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@lukasIO lukasIO changed the title refactor: reserve the microphone from setMicrophoneEnabled refactor: announce the microphone before capture is ready Nov 24, 2026
lukasIO and others added 6 commits November 24, 2026 13:23
In dual-PC mode a connect() that runs together with setMicrophoneEnabled()
waits for capture. 2.25.0 behaves the same (connect 1238 ms against capture
at 680 ms), so the benchmark asserts this only for single PC.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
publishTrack() called before the signal connects now reserves a microphone
or camera track. The format comes from the track itself, the stereo
decision is the one publishTrack() makes anyway, and the AddTrack request
carries the track's own mute state, so no unmute follows. A reservation
made before connect() goes into the JOIN, and the track is published as
soon as the room connects. Like any publication made before the signal
connects, it gives up after 15 s and stops the track.

A mono reservation now accepts a stereo capture, as publishing after
capture does; only a stereo reservation needs a stereo capture.
setMicrophoneEnabled() no longer passes the capture channel count, which
made a stereo capture request fall back instead of publishing mono.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
publishTrack() created its reservation only after several awaits, so in
Promise.all([connect(), publishTrack()]) the track reached the JOIN only if
those awaits finished before connect() built the JOIN offer. Otherwise it
registered after the JOIN answer, one round trip later.

publishTrack() now wraps the track, computes the publish options and
reserves before its first await. connect() reads the reservations only
after awaits of its own, so the JOIN carries the track in either order.
The wrapping and option steps move into synchronous helpers that the
ordinary path uses too.

The test checks the reservation in the same turn as the call, so an await
added in front of it fails the test. The trace script gets MIC_API=
publishTrack: with capture first and then Promise.all([connect(),
publishTrack()]), trackPublished arrives with the JOIN answer and the
microphone is published at 208 ms instead of 390 ms (5 runs, 150 ms RTT).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The SFU drops media of a track it thinks is muted. A reservation announced
muted was unmuted only after the publication was built, after replaceTrack,
so the first packets were dropped until the unmute arrived. The unmute now
goes out right before replaceTrack, so it travels with the first packets.

With 100 ms delay on every path to a local server (dummynet), first audio
at a listener for a Session start without a permission wait improves from
996 to 944 ms (5 runs), the same as #2292 (942 ms).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Comments and notes still described states that are gone: reservations
registered only after the JOIN, every AddTrack request sent muted, an
unmute after replaceTrack, a room that must be disconnected to reserve,
media stopped by Session, and the Session bridge. The test helper and one
assertion still used the bridge's names.

The agent trace script leaves the PR; AGENTS.md no longer points to it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@lukasIO
lukasIO marked this pull request as ready for review November 24, 2026 13:25

@devin-ai-integration devin-ai-integration Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Devin Review found 3 potential issues.

3 flags not posted on this PR by your GitHub settings — view them in Devin Review. (Configure)

Devin Review

Comment on lines +973 to +979
const publishing =
this.pendingPublishPromises.has(track) ||
[...this.trackPublications.values()].some((pub) => pub.track === track);
if (!publishing) {
const { opts, isStereo } = this.publishOptionsFor(track, options);
const reserved = this.reserveTrack(track, opts, isStereo);
if (reserved) return reserved;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔴 Unpublish misses pending pre-join tracks

Before connecting, publishTrack leaves its reservation out of pendingPublishPromises. unpublishTrack returns without removing it, so the track still publishes on join. A second publish call can also reserve another sender for the same track.

Learn more

Ordinary publication records its in-flight promise in pendingPublishPromises. unpublishTrack uses that map to wait for a LocalTrack's publication before removing it. A reserved publication returns before that map entry is created, and the room still holds the reservation for the JOIN. The early duplicate check also reads the same map, so it cannot see the first reservation either.

Example: Start publishing a LocalVideoTrack before connecting, then request its removal while the room is still disconnected. The removal resolves with undefined. Connecting afterward still publishes the camera.

Recommended fix: Track each pending reservation by LocalTrack alongside ordinary pending publications. Make unpublish cancel or await that reservation, and reuse its promise on repeated publishes. Avoid making the reservation's internal publish continuation wait on its own promise.

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.

Comment thread src/room/RTCEngine.ts Resolved
lukasIO and others added 3 commits November 24, 2026 14:32
A reservation error in the JOIN path (a browser that cannot create a sender
without a track, or reject its codec preferences) made join() throw, so
connect() failed. #2292 rebuilt the peer connection in that case. Now each
reservation fails on its own: its sender is removed and the publication
waits for capture, while the JOIN goes ahead. The same applies to a missing
CID, a failed probe offer and a failed registration after the JOIN, which
used to leave the publication waiting with no registration coming.

setMicrophoneEnabled() before connect() now gives up after 15 s, like
publishTrack() and like any publication made before the signal connects.
Before, it waited until disconnect. Its reservation path calls
attachTrack() directly, so it never went through publishTrack()'s limit.
Both paths now share limitRegistration(), and a cancelled reservation
settles its registration so the timer does not outlive it.

New tests drive the engine with a stubbed publisher: the JOIN claim, a
sender that cannot be created, a missing CID, a single registration for
two concurrent calls, nothing before the JOIN, a connection that cannot
reserve, a failed probe offer, and a new registration after a full
reconnect. Two more check the 15 s limit for publishTrack() and
setMicrophoneEnabled().

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- unpublishTrack() now finds a track published before the signal connected
  and cancels its reservation, so the track no longer publishes on join. A
  second publishTrack() of the same track reuses the pending reservation.
  Reservations are tracked in their own map, because the publish
  continuation inside attachTrack() waits on pendingPublishPromises.
- Only a track that already is a microphone or camera is reserved. A track
  without a source, such as a custom feed, publishes as usual and stays
  untagged, so setMicrophoneEnabled() and setCameraEnabled() never take it
  over.
- Reservations get their CIDs from a probe offer before the JOIN offer is
  built, so a reserved camera's start bitrate is in the munged initial
  offer. Before, the CID came from the initial offer itself, after munging.
  The JOIN and the registration after it now share reserveSenders().

Restores the PCTransport test for a reserved camera's start bitrate in the
initial offer, and adds tests for the unpublish, the repeated publish, the
untagged track and the bitrate registration.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
reserve() lets the attachment start as soon as the AddTrack request exists,
and senderFor() then waits for its acceptance. A full reconnect calls
fallback(), which rejects that request. The waiting attachment took the
rejection as a failure and cancelled the whole publication, so
setMicrophoneEnabled(true) could fail only because the room reconnected at
the wrong moment. The publication was also not registered again, because an
attaching reservation no longer counted as waiting.

fallback() now starts a new registration for an uncommitted publication,
so the next connection registers it again. senderFor() reports a
reservation that fallback() replaced, and the attachment then waits for the
new registration and publishes again. The retry goes through
publishOrRepublishTrack(), which waits for the reconnect to finish.

The new test attaches capture while the acceptance is pending, drops the
reservation as cleanupPeerConnections() does, and checks that the
publication completes on the new registration. It fails without the fix.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@lukasIO
lukasIO added this pull request to stack #2300 November 26, 2026 08:13
@github-actions

Copy link
Copy Markdown
Contributor

size-limit report 📦

Path Size
dist/livekit-client.esm.mjs 122.24 KB (+0.44% 🔺)
dist/livekit-client.umd.js 131.74 KB (+0.44% 🔺)
dist/core/core.mjs 83.54 KB (+0.82% 🔺)

This branch has not been deployed

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant