{"version":3,"file":"PCTransport.mjs","sources":["../../../src/room/PCTransport.ts"],"sourcesContent":["import { Mutex } from '@livekit/mutex';\nimport { EventEmitter } from 'events';\nimport { parse, write } from 'sdp-transform';\nimport type { MediaAttributes, MediaDescription, SessionDescription } from 'sdp-transform';\nimport type TypedEmitter from 'typed-emitter';\nimport log, { LoggerNames, getLogger } from '../logger';\nimport { debounce } from './debounce';\nimport { NegotiationError, UnexpectedConnectionState } from './errors';\nimport type { LoggerOptions } from './types';\nimport { ddExtensionURI, isSVCCodec, isSafari } from './utils';\n\ninterface TrackBitrateInfo {\n  cid?: string;\n  transceiver?: RTCRtpTransceiver;\n  codec: string;\n  maxbr: number;\n  isScreenShare?: boolean;\n}\n\n/*\n * Video codecs use a very low bitrate at the beginning and increase slowly by\n * the bandwidth estimator until they reach the target bitrate. The process commonly\n * costs more than 10 seconds causing subscribers to get blurry video at the first\n * few seconds. We use x-google-start-bitrate to hint the BWE to start higher.\n *\n * Why 90%: Gives ~10% headroom for bandwidth estimation while starting close to target.\n * Why same for all codecs: Target bitrate already accounts for codec efficiency\n * (e.g., users set lower targets for VP9/AV1 knowing they're more efficient).\n * Why cap at 1 Mbps: Prevents BWE from starting too aggressively on high bitrate tracks.\n * The cap is lowered further for connections that were slow to set up, see\n * `computeStartBitrateCap`, or that the browser reports as slow, see\n * `connectionEffectiveTypeStartBitrateCap`.\n */\nconst startBitrateMultiplier = 0.9;\n\n/** Maximum x-google-start-bitrate in kbps. 1 Mbps prevents BWE from starting too aggressively. */\nconst maxStartBitrateKbps = 1000;\n\n/**\n * Minimum x-google-start-bitrate in kbps: libwebrtc's own default starting estimate. A target\n * below this gets no hint, since seeding above the real capacity costs more than the ramp it\n * saves, and a slow connection is seeded no higher than this.\n */\nconst minTargetBitrateKbps = 300;\n\n/**\n * Connection setup times (ms) bounding the ramp in `computeStartBitrateCap`: at or below the\n * first the hint is capped at `maxStartBitrateKbps`, at or above the second at\n * `minTargetBitrateKbps`. Measured on shaped links (CLT-3380): healthy links set up in under\n * 860 ms, a 1 Mbps link with 150 ms RTT took 1.1–1.7 s, a 500 kbps link ~2.3 s at the median,\n * and a 300 kbps link never under 3 s. The first sits above the 1 Mbps link, which a lower seed\n * only slows down, and the second above the 500 kbps link's median, so only links that cannot\n * carry more land at the floor.\n */\nconst setupTimeForMaxStartBitrateMs = 1500;\nconst setupTimeForMinStartBitrateMs = 3500;\n\n/** Cap on the start bitrate hint, in kbps, when the browser reports a `3g` connection. */\nconst effectiveType3gStartBitrateKbps = 500;\n\n/**\n * The part of the Network Information API (`navigator.connection`) read here. It is Chromium\n * only, so TypeScript's DOM typings do not declare it.\n */\ninterface NetworkInformation {\n  readonly effectiveType?: 'slow-2g' | '2g' | '3g' | '4g';\n}\n\nconst debounceInterval = 20;\n\n/**\n * Codec payload for `codec` in this media section, when the section carries `cid`.\n *\n * Returns `undefined` when the section does not belong to the track, `0` when it does but\n * does not offer the requested codec, and the codec payload otherwise.\n *\n * @internal\n */\nexport function findTrackCodecPayload(\n  media: MediaDescription,\n  cid: string,\n  codec: string,\n): number | undefined {\n  if (!media.msid?.includes(cid)) {\n    return undefined;\n  }\n  return media.rtp.find((rtp) => rtp.codec.toUpperCase() === codec.toUpperCase())?.payload ?? 0;\n}\n\n/**\n * Start bitrate hinted for a single track, or `undefined` when its target is too low to\n * be worth seeding.\n *\n * 90% of the target leaves ~10% headroom for the estimator to settle. The same multiplier\n * is used for every codec because the target already reflects the codec's efficiency.\n * Camera is capped at 1 Mbps so the estimator does not open too aggressively on a\n * high-bitrate track; screen share is exempt, because its content needs the bitrate\n * immediately to stay legible.\n *\n * The cap is lowered for a connection that was slow to set up (`computeStartBitrateCap`), and\n * for one the browser reports as slow (`connectionEffectiveTypeStartBitrateCap`), whichever is\n * lower. Screen share is exempt from both, however slow the connection.\n *\n * @internal\n */\nexport function computeTrackStartBitrate(\n  trackbr: TrackBitrateInfo,\n  connectionSetupTimeMs?: number,\n): number | undefined {\n  if (trackbr.maxbr < minTargetBitrateKbps) {\n    return undefined;\n  }\n  const calculated = Math.min(Math.round(trackbr.maxbr * startBitrateMultiplier), trackbr.maxbr);\n  if (trackbr.isScreenShare) {\n    return calculated;\n  }\n  const cap = Math.min(\n    computeStartBitrateCap(connectionSetupTimeMs),\n    connectionEffectiveTypeStartBitrateCap(),\n  );\n  return Math.min(calculated, cap);\n}\n\n/**\n * Cap on the start bitrate hint, in kbps, from the browser's effective connection type\n * (`navigator.connection.effectiveType`, Chromium only): `slow-2g` and `2g` cap at\n * `minTargetBitrateKbps`, `3g` at `effectiveType3gStartBitrateKbps`.\n *\n * It catches links that have low bandwidth but low latency, which set up quickly and so slip\n * past the setup time ramp. `4g`, and browsers without the API, give no guidance and stay at the\n * `maxStartBitrateKbps` ceiling, as `computeStartBitrateCap` does without a setup time. The\n * connection RTT the API also reports is not used: it lags behind network changes, and the setup\n * time already reflects latency.\n */\nfunction connectionEffectiveTypeStartBitrateCap(): number {\n  // A `typeof` guard, since `globalThis` is missing from some supported browsers (Chrome < 71,\n  // Firefox < 65, Safari < 12.1) and the build does not polyfill it.\n  const connection =\n    typeof navigator !== 'undefined'\n      ? (navigator as Navigator & { connection?: NetworkInformation }).connection\n      : undefined;\n  switch (connection?.effectiveType) {\n    case 'slow-2g':\n    case '2g':\n      return minTargetBitrateKbps;\n    case '3g':\n      return effectiveType3gStartBitrateKbps;\n    default:\n      return maxStartBitrateKbps;\n  }\n}\n\n/**\n * Cap on the start bitrate hint, in kbps, from how long the connection took to set up.\n *\n * Connection setup time (signaling join plus ICE/DTLS) is the network signal every platform has\n * before the first video offer, since libwebrtc cannot probe the path until a video sender\n * exists. It grows with round-trip time and loss, which also mark the links where a 1 Mbps\n * seed overshoots, so the cap ramps linearly from `maxStartBitrateKbps` at\n * `setupTimeForMaxStartBitrateMs` down to `minTargetBitrateKbps` at\n * `setupTimeForMinStartBitrateMs`. A video offer built while the connection is still being set\n * up (publishing during connect) passes the time elapsed so far, a lower bound on the setup time.\n * Without any timing the cap stays at the 1 Mbps ceiling.\n */\nfunction computeStartBitrateCap(connectionSetupTimeMs?: number): number {\n  if (connectionSetupTimeMs === undefined) {\n    return maxStartBitrateKbps;\n  }\n  const ramp = Math.min(\n    Math.max(\n      (connectionSetupTimeMs - setupTimeForMaxStartBitrateMs) /\n        (setupTimeForMinStartBitrateMs - setupTimeForMaxStartBitrateMs),\n      0,\n    ),\n    1,\n  );\n  return Math.round(maxStartBitrateKbps - ramp * (maxStartBitrateKbps - minTargetBitrateKbps));\n}\n\n/**\n * The single start bitrate for this peer connection: the largest hint among the video\n * m-sections of `media` that map to a published track.\n *\n * libwebrtc reads `x-google-start-bitrate` per m-section but applies it to the shared\n * `Call` (`WebRtcVideoSendChannel::ApplyChangedParams` -> `SetSdpBitrateParameters`), where\n * `RtpBitrateConfigurator` holds one config for the whole connection. Differing per-section\n * values are therefore last-writer-wins, decided by m-section order, so every video section\n * gets the same number instead.\n *\n * Only sections that can send local media are considered. `trackBitrates` is append-only and an\n * unpublished section keeps its `a=msid`, so matching on msid alone would still pair a stale\n * entry with its old section — letting an uncapped screen-share target seed a connection that\n * now carries only a camera, or consuming the one-shot hint on a section that sends nothing.\n *\n * The direction is the discriminator, as an exclusion rather than a match: `recvonly` and\n * `inactive` are the only directions that cannot carry local media, and they are exactly the\n * two a dead section lands on — unpublish sets `inactive` (explicitly in\n * `LocalParticipant.unpublishTrack`, and via `removeTrack`'s sendonly -> inactive transition for\n * the simulcast senders), `removeTrack` on a `sendrecv` transceiver leaves `recvonly`, and the\n * pre-populated placeholders are `recvonly`. Everything else sends: `sendonly` from the\n * `addTransceiver` path, `sendrecv` from the legacy `addTrack` fallback (which reuses a\n * transceiver rather than creating a sendonly one), and a section with no direction attribute,\n * which SDP defaults to `sendrecv`.\n *\n * @internal\n */\nexport function computeConnectionStartBitrate(\n  media: MediaDescription[],\n  trackBitrates: TrackBitrateInfo[],\n  connectionSetupTimeMs?: number,\n): number | undefined {\n  let connectionStartBitrate: number | undefined;\n  for (const m of media) {\n    if (m.type !== 'video' || m.direction === 'recvonly' || m.direction === 'inactive') {\n      continue;\n    }\n    for (const trackbr of trackBitrates) {\n      if (!trackbr.cid) {\n        continue;\n      }\n      const codecPayload = findTrackCodecPayload(m, trackbr.cid, trackbr.codec);\n      if (codecPayload === undefined) {\n        continue;\n      }\n      const startBitrate =\n        codecPayload > 0 ? computeTrackStartBitrate(trackbr, connectionSetupTimeMs) : undefined;\n      if (\n        startBitrate !== undefined &&\n        (connectionStartBitrate === undefined || startBitrate > connectionStartBitrate)\n      ) {\n        connectionStartBitrate = startBitrate;\n      }\n      break;\n    }\n  }\n  return connectionStartBitrate;\n}\n\n/**\n * Declares `x-google-start-bitrate` on `codecPayload`'s fmtp. This SDP munging is used for\n * a bitrate setting that cannot be applied through `RTCRtpEncodingParameters`.\n *\n * Returns whether the section now carries the hint.\n *\n * @internal\n */\nexport function applyVideoStartBitrate(\n  media: MediaDescription,\n  codecPayload: number,\n  startBitrate: number,\n): boolean {\n  const fmtp = media.fmtp.find((entry) => entry.payload === codecPayload);\n  if (fmtp) {\n    // A payload type is shared across the bundle, so a value written for one section is\n    // already the connection-level one; leave it rather than rewrite it.\n    if (!fmtp.config.includes('x-google-start-bitrate')) {\n      fmtp.config += `;x-google-start-bitrate=${startBitrate}`;\n    }\n  } else {\n    // VP8 and some codecs may not have an existing fmtp line.\n    media.fmtp.push({\n      payload: codecPayload,\n      config: `x-google-start-bitrate=${startBitrate}`,\n    });\n  }\n\n  return true;\n}\n\nexport const PCEvents = {\n  NegotiationStarted: 'negotiationStarted',\n  NegotiationComplete: 'negotiationComplete',\n  // Fired with the offerId for every successful publisher answer application,\n  // including answers that immediately recurse into another offer via\n  // `renegotiate`. Use this rather than NegotiationComplete to know that a\n  // specific offer has been negotiated end-to-end.\n  OfferAnswered: 'offerAnswered',\n  RTPVideoPayloadTypes: 'rtpVideoPayloadTypes',\n} as const;\n\nexport interface PCTransportOptions {\n  singlePeerConnection?: boolean;\n}\n\nexport default class PCTransport extends (EventEmitter as new () => TypedEmitter<PCTransportEventCallbacks>) {\n  private _pc: RTCPeerConnection | null;\n\n  private get pc() {\n    if (!this._pc) {\n      this._pc = this.createPC();\n    }\n    return this._pc;\n  }\n\n  private config?: RTCConfiguration;\n\n  private log = log;\n\n  private iceLog = log;\n\n  private loggerOptions: LoggerOptions;\n\n  private ddExtID = 0;\n\n  latestOfferId: number = 0;\n\n  private answeredOfferId: number = 0;\n\n  /** offerId (0 if unnumbered) of the answer being applied right now */\n  private answerInFlight: number | undefined;\n\n  latestAcknowledgedOfferId: number = 0;\n\n  private offerLock: Mutex;\n\n  private pendingInitialOffer?: { original: RTCSessionDescriptionInit; munged: string };\n\n  private readonly offeredAudioNackMids: string[];\n\n  pendingCandidates: RTCIceCandidateInit[] = [];\n\n  restartingIce: boolean = false;\n\n  renegotiate: boolean = false;\n\n  trackBitrates: TrackBitrateInfo[] = [];\n\n  /**\n   * Whether an offer carrying the connection-level `x-google-start-bitrate` has been\n   * accepted locally. The hint is written once per peer connection: libwebrtc retains\n   * `start_bitrate_bps` in `RtpBitrateConfigurator` and re-applies it on network route\n   * changes, so a later rewrite is at best a no-op and at worst restarts a converged\n   * bandwidth estimator. A new peer connection (full reconnect) seeds a new estimator.\n   */\n  private hasAppliedVideoStartBitrate = false;\n\n  /**\n   * How long this peer connection took to set up, in ms, recorded once the initial connect\n   * succeeds. Lowers the start bitrate hint for a slow connection; see `computeStartBitrateCap`.\n   */\n  private connectionSetupTimeMs?: number;\n\n  /**\n   * When the connection attempt that built this peer connection began (`performance.now()`).\n   * Until `connectionSetupTimeMs` is known, the time elapsed since then is used as a lower bound\n   * on the setup time, so a video published during connect is still seeded from it rather than\n   * waiting for the connection, which would delay the offer.\n   */\n  private connectionStartedAt?: number;\n\n  remoteStereoMids: string[] = [];\n\n  remoteNackMids: string[] = [];\n\n  onOffer?: (offer: RTCSessionDescriptionInit, offerId: number) => void;\n\n  onIceCandidate?: (candidate: RTCIceCandidate) => void;\n\n  onIceCandidateError?: (ev: Event) => void;\n\n  onConnectionStateChange?: (state: RTCPeerConnectionState) => void;\n\n  onIceConnectionStateChange?: (state: RTCIceConnectionState) => void;\n\n  onSignalingStatechange?: (state: RTCSignalingState) => void;\n\n  onDataChannel?: (ev: RTCDataChannelEvent) => void;\n\n  onTrack?: (ev: RTCTrackEvent) => void;\n\n  constructor(\n    config?: RTCConfiguration,\n    loggerOptions: LoggerOptions = {},\n    options: PCTransportOptions = {},\n  ) {\n    super();\n    this.offeredAudioNackMids = options.singlePeerConnection ? ['all'] : [];\n    this.loggerOptions = loggerOptions;\n    this.log = getLogger(\n      loggerOptions.loggerName ?? LoggerNames.PCTransport,\n      () => this.logContext,\n    );\n    this.iceLog = getLogger(LoggerNames.ICE, () => this.logContext);\n    this.config = config;\n    this._pc = this.createPC();\n    this.offerLock = new Mutex();\n  }\n\n  private createPC() {\n    const pc = new RTCPeerConnection(this.config);\n\n    pc.onicecandidate = (ev) => {\n      if (!ev.candidate) return;\n      this.iceLog.debug('local ICE candidate gathered', { candidate: ev.candidate.candidate });\n      this.onIceCandidate?.(ev.candidate);\n    };\n    pc.onicecandidateerror = (ev) => {\n      this.iceLog.debug('ICE candidate error', { event: ev });\n      this.onIceCandidateError?.(ev);\n    };\n\n    pc.oniceconnectionstatechange = () => {\n      this.iceLog.debug(`ICE connection state: ${pc.iceConnectionState}`);\n      this.onIceConnectionStateChange?.(pc.iceConnectionState);\n    };\n\n    pc.onsignalingstatechange = () => {\n      this.log.debug(`signaling state: ${pc.signalingState}`);\n      this.onSignalingStatechange?.(pc.signalingState);\n    };\n\n    pc.onconnectionstatechange = () => {\n      this.log.debug(`connection state: ${pc.connectionState}`);\n      this.onConnectionStateChange?.(pc.connectionState);\n    };\n    pc.ondatachannel = (ev) => {\n      this.log.debug('data channel opened by peer', {\n        label: ev.channel.label,\n        id: ev.channel.id,\n      });\n      this.onDataChannel?.(ev);\n    };\n    pc.ontrack = (ev) => {\n      this.onTrack?.(ev);\n    };\n    return pc;\n  }\n\n  private get logContext() {\n    return {\n      ...this.loggerOptions.loggerContextCb?.(),\n    };\n  }\n\n  get isICEConnected(): boolean {\n    return (\n      this._pc !== null &&\n      (this.pc.iceConnectionState === 'connected' || this.pc.iceConnectionState === 'completed')\n    );\n  }\n\n  async addIceCandidate(candidate: RTCIceCandidateInit): Promise<void> {\n    if (this.pc.remoteDescription && !this.restartingIce) {\n      return this.pc.addIceCandidate(candidate);\n    }\n    this.iceLog.debug('queuing remote ICE candidate until remote description applied', {\n      pendingCount: this.pendingCandidates.length + 1,\n    });\n    this.pendingCandidates.push(candidate);\n  }\n\n  /** Whether an answer for `offerId` answers an offer older than the latest one sent. */\n  isStaleAnswer(offerId: number): boolean {\n    return this.latestOfferId > 0 && offerId > 0 && offerId !== this.latestOfferId;\n  }\n\n  async setRemoteDescription(sd: RTCSessionDescriptionInit, offerId: number): Promise<boolean> {\n    if (sd.type === 'answer' && this.isStaleAnswer(offerId)) {\n      this.log.warn('ignoring answer for old offer', {\n        offerId,\n        latestOfferId: this.latestOfferId,\n      });\n      return false;\n    }\n    if (sd.type === 'answer') {\n      if (\n        isDuplicateAnswer(\n          offerId,\n          this.answerInFlight,\n          this.answeredOfferId,\n          this._pc?.signalingState,\n          this.pendingInitialOffer !== undefined,\n        )\n      ) {\n        // a repeat of an answer already applied or being applied (e.g.\n        // duplicated by a proxy): there is no local offer left to answer\n        this.log.warn('ignoring duplicate answer', { offerId });\n        return false;\n      }\n      // claimed before any await, so a copy arriving mid-apply is caught too;\n      // released however the apply ends, so a genuine retry is still possible\n      this.answerInFlight = offerId;\n    }\n    try {\n      return await this.applyRemoteDescription(sd, offerId);\n    } finally {\n      if (sd.type === 'answer') this.answerInFlight = undefined;\n    }\n  }\n\n  private async applyRemoteDescription(\n    sd: RTCSessionDescriptionInit,\n    offerId: number,\n  ): Promise<boolean> {\n    let mungedSDP: string | undefined = undefined;\n    if (sd.type === 'offer') {\n      let { stereoMids, nackMids } = extractStereoAndNackAudioFromOffer(sd);\n      this.remoteStereoMids = stereoMids;\n      this.remoteNackMids = nackMids;\n    } else if (sd.type === 'answer') {\n      if (this.pendingInitialOffer && this._pc) {\n        const { original, munged } = this.pendingInitialOffer;\n        this.pendingInitialOffer = undefined;\n        this.log.debug('setting pending initial offer before processing answer');\n        await this.setMungedSDP(original, munged);\n      }\n      const sdpParsed = parse(sd.sdp ?? '');\n      sdpParsed.media.forEach((media) => {\n        const mid = getMidString(media.mid!);\n        if (media.type === 'audio') {\n          // munge sdp for opus bitrate settings\n          this.trackBitrates.some((trackbr): boolean => {\n            if (!trackbr.transceiver || mid != trackbr.transceiver.mid) {\n              return false;\n            }\n\n            let codecPayload = 0;\n            media.rtp.some((rtp): boolean => {\n              if (rtp.codec.toUpperCase() === trackbr.codec.toUpperCase()) {\n                codecPayload = rtp.payload;\n                return true;\n              }\n              return false;\n            });\n\n            if (codecPayload === 0) {\n              return true;\n            }\n\n            let fmtpFound = false;\n            for (const fmtp of media.fmtp) {\n              if (fmtp.payload === codecPayload) {\n                fmtp.config = fmtp.config\n                  .split(';')\n                  .filter((attr) => !attr.includes('maxaveragebitrate'))\n                  .join(';');\n                if (trackbr.maxbr > 0) {\n                  fmtp.config += `;maxaveragebitrate=${trackbr.maxbr * 1000}`;\n                }\n                fmtpFound = true;\n                break;\n              }\n            }\n\n            if (!fmtpFound) {\n              if (trackbr.maxbr > 0) {\n                media.fmtp.push({\n                  payload: codecPayload,\n                  config: `maxaveragebitrate=${trackbr.maxbr * 1000}`,\n                });\n              }\n            }\n\n            return true;\n          });\n        }\n      });\n      // The server's answer sets per-track codec params (e.g. opus `usedtx`) on\n      // the sections mapped to a published track, but leaves the pre-populated\n      // recvonly placeholder sections with defaults. Conform the placeholders so\n      // each shared payload type is consistent across the bundle, otherwise\n      // libwebrtc flags a \"bundled payload type collision\".\n      const placeholderMids = this.getPlaceholderMids();\n      if (placeholderMids.size > 0) {\n        conformBundledCodecFmtp(sdpParsed.media, (media) =>\n          placeholderMids.has(getMidString(media.mid!)),\n        );\n      }\n      mungedSDP = write(sdpParsed);\n    }\n    await this.setMungedSDP(sd, mungedSDP, true);\n    // only a successfully applied answer makes later copies duplicates\n    if (sd.type === 'answer' && offerId > 0) this.answeredOfferId = offerId;\n\n    if (this.pendingCandidates.length > 0) {\n      this.iceLog.debug('flushing queued ICE candidates', {\n        count: this.pendingCandidates.length,\n      });\n    }\n    this.pendingCandidates.forEach((candidate) => {\n      this.pc.addIceCandidate(candidate);\n    });\n    this.pendingCandidates = [];\n    this.restartingIce = false;\n\n    // Fire OfferAnswered for every successfully applied answer, including the\n    // ones that recurse into another offer via `renegotiate`. Callers waiting\n    // on a specific offerId can resolve as soon as their offer's answer is in.\n    if (sd.type === 'answer') {\n      this.latestAcknowledgedOfferId = offerId;\n      this.emit(PCEvents.OfferAnswered, offerId);\n    }\n\n    if (this.renegotiate) {\n      this.renegotiate = false;\n      await this.createAndSendOffer();\n    } else if (sd.type === 'answer') {\n      this.emit(PCEvents.NegotiationComplete);\n      if (sd.sdp) {\n        const sdpParsed = parse(sd.sdp);\n        sdpParsed.media.forEach((media) => {\n          if (media.type === 'video') {\n            this.emit(PCEvents.RTPVideoPayloadTypes, media.rtp);\n          }\n        });\n      }\n    }\n    return true;\n  }\n\n  // debounced negotiate interface\n  negotiate = debounce(async (onError?: (e: Error) => void) => {\n    this.emit(PCEvents.NegotiationStarted);\n    try {\n      await this.createAndSendOffer();\n    } catch (e) {\n      if (onError) {\n        onError(e as Error);\n      } else {\n        throw e;\n      }\n    }\n  }, debounceInterval);\n\n  async createInitialOffer() {\n    const unlock = await this.offerLock.lock();\n    try {\n      if (this.pc.signalingState !== 'stable') {\n        this.log.warn('signaling state is not stable, cannot create initial offer');\n        return;\n      }\n      const offerId = this.latestOfferId + 1;\n      this.latestOfferId = offerId;\n      const offer = await this.pc.createOffer();\n      const original = { sdp: offer.sdp, type: offer.type };\n      const sdpParsed = parse(offer.sdp ?? '');\n      sdpParsed.media.forEach((media) => {\n        ensureIPAddrMatchVersion(media);\n        if (media.type === 'audio') {\n          ensureAudioNackAndStereo(media, [], this.offeredAudioNackMids);\n        }\n      });\n      offer.sdp = write(sdpParsed);\n      this.pendingInitialOffer = { original, munged: offer.sdp };\n      return { offer, offerId };\n    } finally {\n      unlock();\n    }\n  }\n\n  async createAndSendOffer(options?: RTCOfferOptions) {\n    const unlock = await this.offerLock.lock();\n\n    try {\n      if (this.onOffer === undefined) {\n        return;\n      }\n\n      if (options?.iceRestart) {\n        this.iceLog.debug('restarting ICE');\n        this.restartingIce = true;\n      }\n\n      if (\n        this._pc &&\n        (this._pc.signalingState === 'have-local-offer' || this.pendingInitialOffer)\n      ) {\n        // we're waiting for the peer to accept our offer, so we'll just wait\n        // the only exception to this is when ICE restart is needed\n        const currentSD = this._pc.remoteDescription;\n        if (options?.iceRestart && currentSD) {\n          // roll the remote description back in so createOffer produces a valid\n          // ICE-restart offer on top of the already-negotiated state\n          await this._pc.setRemoteDescription(currentSD);\n        } else if (options?.iceRestart) {\n          // ICE restart with no remote description to restart on: `renegotiate` would stall\n          // (the pending offer is never answered), so throw for the caller to recreate the PC.\n          throw new NegotiationError(\n            'ICE restart requested without a remote description, peer connection must be recreated',\n          );\n        } else {\n          this.renegotiate = true;\n          this.log.debug('requesting renegotiation');\n          return;\n        }\n      } else if (!this._pc || this._pc.signalingState === 'closed') {\n        this.log.warn('could not createOffer with closed peer connection');\n        return;\n      }\n\n      // actually negotiate\n      this.log.debug('starting to negotiate');\n      // increase the offer id at the start to ensure the offer is always > 0 so that we can use 0 as a default value for legacy behavior\n      const offerId = this.latestOfferId + 1;\n      this.latestOfferId = offerId;\n      const offer = await this.pc.createOffer(options);\n      this.log.debug('original offer', { sdp: offer.sdp });\n\n      const sdpParsed = parse(offer.sdp ?? '');\n      // One value for every video m-section, written only on the first offer that carries\n      // local video: the hint is connection-level in libwebrtc, so differing per-section\n      // values would be last-writer-wins on m-section order. Offers before any video is\n      // published (data channel or audio only) find no target and leave the latch unset.\n      const connectionStartBitrate = this.hasAppliedVideoStartBitrate\n        ? undefined\n        : computeConnectionStartBitrate(\n            sdpParsed.media,\n            this.trackBitrates,\n            this.connectionSetupTimeEstimateMs(),\n          );\n      let appliedVideoStartBitrate = false;\n      sdpParsed.media.forEach((media) => {\n        ensureIPAddrMatchVersion(media);\n        if (media.type === 'audio') {\n          ensureAudioNackAndStereo(media, ['all'], this.offeredAudioNackMids);\n        } else if (media.type === 'video') {\n          this.trackBitrates.some((trackbr): boolean => {\n            if (!trackbr.cid) {\n              return false;\n            }\n\n            const codecPayload = findTrackCodecPayload(media, trackbr.cid, trackbr.codec);\n            if (codecPayload === undefined) {\n              return false;\n            }\n\n            if (codecPayload > 0) {\n              if (connectionStartBitrate !== undefined) {\n                appliedVideoStartBitrate =\n                  applyVideoStartBitrate(media, codecPayload, connectionStartBitrate) ||\n                  appliedVideoStartBitrate;\n              }\n\n              if (isSVCCodec(trackbr.codec) && !isSafari()) {\n                this.ddExtID = ensureVideoDDExtension(media, sdpParsed, this.ddExtID);\n              }\n            }\n\n            return true;\n          });\n        }\n      });\n      // Conform the placeholder sections (pre-populated, or reverted after an\n      // unpublish on a server below protocol 19, which keeps the transceiver; from\n      // protocol 19 unpublish stops it) so every shared payload type carries\n      // identical fmtp across the bundle, otherwise libwebrtc flags a \"bundled\n      // payload type collision\".\n      // Detection is by transceiver (mids are stable across renegotiations) since\n      // an unpublished section keeps its `a=msid`.\n      const placeholderMids = this.getPlaceholderMids();\n      if (placeholderMids.size > 0) {\n        conformBundledCodecFmtp(sdpParsed.media, (media) =>\n          placeholderMids.has(getMidString(media.mid!)),\n        );\n      }\n      if (this.latestOfferId > offerId) {\n        this.log.warn('latestOfferId mismatch', {\n          latestOfferId: this.latestOfferId,\n          offerId,\n        });\n        return;\n      }\n      const mungedSdp = write(sdpParsed);\n      await this.setMungedSDP(offer, mungedSdp);\n      // setMungedSDP falls back to the unmunged SDP on rejection. Only consume the\n      // one-shot hint once the SDP carrying it has been accepted locally.\n      if (appliedVideoStartBitrate && offer.sdp === mungedSdp) {\n        this.hasAppliedVideoStartBitrate = true;\n        this.log.info('applied x-google-start-bitrate', {\n          startBitrateKbps: connectionStartBitrate,\n          connectionSetupTimeMs: this.connectionSetupTimeEstimateMs(),\n        });\n      }\n      this.onOffer(offer, this.latestOfferId);\n    } finally {\n      unlock();\n    }\n  }\n\n  async createAndSetAnswer(): Promise<RTCSessionDescriptionInit> {\n    const answer = await this.pc.createAnswer();\n    const sdpParsed = parse(answer.sdp ?? '');\n    sdpParsed.media.forEach((media) => {\n      ensureIPAddrMatchVersion(media);\n      if (media.type === 'audio') {\n        ensureAudioNackAndStereo(media, this.remoteStereoMids, this.remoteNackMids);\n      }\n    });\n    await this.setMungedSDP(answer, write(sdpParsed));\n    return answer;\n  }\n\n  /**\n   * Returns the mids of transceivers that carry no outgoing track on this\n   * (publisher) connection: the pre-populated placeholders added by\n   * `RTCEngine.applyInitialPublisherLayout`, plus any transceiver that was used\n   * for a track and reverted on unpublish (below server protocol 19; from protocol\n   * 19 unpublish stops it). Their codec fmtp is conformed to the published tracks\n   * so a shared payload type stays consistent across the bundle.\n   */\n  private getPlaceholderMids(): Set<string> {\n    return placeholderMidsFromTransceivers(this._pc?.getTransceivers() ?? []);\n  }\n\n  createDataChannel(label: string, dataChannelDict: RTCDataChannelInit) {\n    return this.pc.createDataChannel(label, dataChannelDict);\n  }\n\n  addTransceiver(mediaStreamTrack: MediaStreamTrack, transceiverInit: RTCRtpTransceiverInit) {\n    return this.pc.addTransceiver(mediaStreamTrack, transceiverInit);\n  }\n\n  addTransceiverOfKind(kind: 'audio' | 'video', transceiverInit: RTCRtpTransceiverInit) {\n    return this.pc.addTransceiver(kind, transceiverInit);\n  }\n\n  addTrack(track: MediaStreamTrack) {\n    if (!this._pc) {\n      throw new UnexpectedConnectionState('PC closed, cannot add track');\n    }\n    return this._pc.addTrack(track);\n  }\n\n  setTrackCodecBitrate(info: TrackBitrateInfo) {\n    this.trackBitrates.push(info);\n  }\n\n  /**\n   * Record how long this peer connection took to set up. Called once, when the initial connect\n   * succeeds; resumes and ICE restarts keep the estimator they have and never call this.\n   */\n  setConnectionSetupTime(ms: number) {\n    this.connectionSetupTimeMs = ms;\n  }\n\n  /** Record when the connection attempt that built this peer connection began. */\n  setConnectionStartedAt(startedAt: number) {\n    this.connectionStartedAt = startedAt;\n  }\n\n  /** The measured setup time, or while still connecting, the time elapsed so far. */\n  private connectionSetupTimeEstimateMs(): number | undefined {\n    if (this.connectionSetupTimeMs !== undefined) {\n      return this.connectionSetupTimeMs;\n    }\n    if (this.connectionStartedAt === undefined) {\n      return undefined;\n    }\n    return Math.round(performance.now() - this.connectionStartedAt);\n  }\n\n  setConfiguration(rtcConfig: RTCConfiguration) {\n    if (!this._pc) {\n      throw new UnexpectedConnectionState('PC closed, cannot configure');\n    }\n    return this._pc?.setConfiguration(rtcConfig);\n  }\n\n  canRemoveTrack(): boolean {\n    return !!this._pc?.removeTrack;\n  }\n\n  /**\n   * Removes `sender` from the connection. With `stop`, it then stops the transceiver of `sender`.\n   */\n  removeTrack(sender: RTCRtpSender, stop = false) {\n    this._pc?.removeTrack(sender);\n    if (stop) {\n      this.stopTransceivers([sender]);\n    }\n  }\n\n  /**\n   * Stops the transceivers of `senders`. `removeTrack` keeps the transceiver and its encoder,\n   * and each publish adds a new transceiver. A transceiver that is not stopped stays until the\n   * connection closes. Call this after `removeTrack`, as `removeTrack(sender, true)` does.\n   * Returns true if a transceiver stopped.\n   *\n   * The last live transceiver of each kind stays. The server cannot follow two changes that some\n   * browsers make after all transceivers of a kind stop. The browser drops the ICE and DTLS\n   * transport when all m-sections are rejected. Some browsers also give the next transceiver new\n   * header extension ids.\n   */\n  stopTransceivers(senders: RTCRtpSender[]): boolean {\n    let stopped = false;\n    const transceivers = this.getTransceivers();\n    const isLive = (t: RTCRtpTransceiver) =>\n      t.direction !== 'stopped' && t.currentDirection !== 'stopped';\n    for (const transceiver of transceivers) {\n      // RTCRtpTransceiver.stop() is not available before Chrome 88\n      if (!senders.includes(transceiver.sender) || typeof transceiver.stop !== 'function') {\n        continue;\n      }\n      // the sender has no track after removeTrack, the receiver always has one\n      const { kind } = transceiver.receiver.track;\n      if (\n        !transceivers.some((t) => t !== transceiver && isLive(t) && t.receiver.track.kind === kind)\n      ) {\n        continue;\n      }\n      try {\n        transceiver.stop();\n        stopped = true;\n      } catch (e) {\n        this.log.warn('could not stop transceiver', { error: e });\n      }\n    }\n    return stopped;\n  }\n\n  getConnectionState() {\n    return this._pc?.connectionState ?? 'closed';\n  }\n\n  getICEConnectionState() {\n    return this._pc?.iceConnectionState ?? 'closed';\n  }\n\n  getSignallingState() {\n    return this._pc?.signalingState ?? 'closed';\n  }\n\n  getTransceivers() {\n    return this._pc?.getTransceivers() ?? [];\n  }\n\n  getSenders() {\n    return this._pc?.getSenders() ?? [];\n  }\n\n  getLocalDescription() {\n    return this._pc?.localDescription;\n  }\n\n  getRemoteDescription() {\n    return this.pc?.remoteDescription;\n  }\n\n  /** stats of the underlying connection, `undefined` when there is none */\n  getStats() {\n    return this._pc?.getStats();\n  }\n\n  getMaxMessageSize() {\n    return this._pc?.sctp?.maxMessageSize;\n  }\n\n  async getConnectedAddress(): Promise<string | undefined> {\n    if (!this._pc) {\n      return;\n    }\n    let selectedCandidatePairId = '';\n    const candidatePairs = new Map<string, RTCIceCandidatePairStats>();\n    // id -> candidate ip\n    const candidates = new Map<string, string>();\n    const stats: RTCStatsReport = await this._pc.getStats();\n    stats.forEach((v) => {\n      switch (v.type) {\n        case 'transport':\n          selectedCandidatePairId = v.selectedCandidatePairId;\n          break;\n        case 'candidate-pair':\n          if (selectedCandidatePairId === '' && v.selected) {\n            selectedCandidatePairId = v.id;\n          }\n          candidatePairs.set(v.id, v);\n          break;\n        case 'remote-candidate':\n          candidates.set(v.id, `${v.address}:${v.port}`);\n          break;\n        default:\n      }\n    });\n\n    if (selectedCandidatePairId === '') {\n      return undefined;\n    }\n    const selectedID = candidatePairs.get(selectedCandidatePairId)?.remoteCandidateId;\n    if (selectedID === undefined) {\n      return undefined;\n    }\n    return candidates.get(selectedID);\n  }\n\n  close = () => {\n    if (!this._pc) {\n      return;\n    }\n    this.log.debug('closing peer connection');\n    this.pendingInitialOffer = undefined;\n    this._pc.close();\n    this._pc.onconnectionstatechange = null;\n    this._pc.oniceconnectionstatechange = null;\n    this._pc.onicegatheringstatechange = null;\n    this._pc.ondatachannel = null;\n    this._pc.onnegotiationneeded = null;\n    this._pc.onsignalingstatechange = null;\n    this._pc.onicecandidate = null;\n    this._pc.ondatachannel = null;\n    this._pc.ontrack = null;\n    this._pc.onconnectionstatechange = null;\n    this._pc.oniceconnectionstatechange = null;\n    this._pc = null;\n  };\n\n  private async setMungedSDP(sd: RTCSessionDescriptionInit, munged?: string, remote?: boolean) {\n    const originalSdp = sd.sdp;\n    if (munged) {\n      sd.sdp = munged;\n      try {\n        this.log.debug(`setting munged ${remote ? 'remote' : 'local'} description`);\n        if (remote) {\n          await this.pc.setRemoteDescription(sd);\n        } else {\n          await this.pc.setLocalDescription(sd);\n        }\n        return;\n      } catch (e) {\n        this.log.warn(`not able to set ${sd.type}, falling back to unmodified sdp`, {\n          error: e,\n          mungedSdp: munged,\n          originalSdp,\n        });\n        sd.sdp = originalSdp;\n      }\n    }\n\n    try {\n      if (remote) {\n        await this._pc?.setRemoteDescription(sd);\n      } else {\n        await this._pc?.setLocalDescription(sd);\n      }\n    } catch (e) {\n      let msg = 'unknown error';\n      if (e instanceof Error) {\n        msg = e.message;\n      } else if (typeof e === 'string') {\n        msg = e;\n      }\n\n      const fields: any = {\n        error: msg,\n        sdp: sd.sdp,\n      };\n      if (munged && munged !== originalSdp) {\n        fields.mungedSdp = munged;\n      }\n      if (!remote && this.pc.remoteDescription) {\n        fields.remoteSdp = this.pc.remoteDescription;\n      }\n      this.log.error(`unable to set ${sd.type}`, { fields });\n      throw new NegotiationError(msg);\n    }\n  }\n}\n\n/**\n * Adds the AV1 dependency descriptor extension to `media` unless it is already there, and\n * returns the id it is mapped to so callers can pass it back in as `ddExtID` (0 when no id has\n * been chosen yet).\n *\n * A bundle has to map one URI to one id, so an id already in use for the extension anywhere in\n * `sdp` wins over both the cached one and a fresh one: Chrome advertises the extension itself on\n * sections it can send on, and an earlier offer may have munged it into others.\n * @internal\n */\nexport function ensureVideoDDExtension(\n  media: {\n    type: string;\n    port: number;\n    protocol: string;\n    payloads?: string | undefined;\n  } & MediaDescription,\n  sdp: SessionDescription,\n  ddExtID: number,\n): number {\n  const id = ddExtensionIDFor(sdp, ddExtID);\n  if (id === undefined) {\n    return ddExtID;\n  }\n\n  if (!media.ext?.some((ext) => ext.uri === ddExtensionURI)) {\n    media.ext ??= [];\n    media.ext.push({\n      value: id,\n      uri: ddExtensionURI,\n    });\n  }\n  return id;\n}\n\n/**\n * The id to map the dependency descriptor to throughout `sdp`, or undefined when no id would be\n * consistent for the whole bundle and the extension therefore has to be left out.\n */\nfunction ddExtensionIDFor(sdp: SessionDescription, cachedID: number): number | undefined {\n  const mapped = mappedExtensionID(sdp, ddExtensionURI);\n  if (mapped !== undefined) {\n    // Adopting an id that also stands for another URI is what the browser rejects the bundle\n    // over, and its own half of the map is not ours to renumber, so give up on this offer.\n    return usedForOtherURI(sdp, mapped, ddExtensionURI) ? undefined : mapped;\n  }\n  // Reusing the id from the last offer keeps the mapping stable across renegotiations, but only\n  // while nothing else has taken it: the browser assigns ids to its own extensions without\n  // knowing about ours, so an id that was free when we picked it can since have been claimed —\n  // typically by the fuller extension set that arrives with the first section we send on.\n  if (cachedID !== 0 && !usedForOtherURI(sdp, cachedID, ddExtensionURI)) {\n    return cachedID;\n  }\n  return unusedExtensionID(sdp);\n}\n\n/** The id `uri` is mapped to in `sdp`, if any section maps it. */\nfunction mappedExtensionID(sdp: SessionDescription, uri: string): number | undefined {\n  for (const media of sdp.media) {\n    const ext = media.ext?.find((candidate) => candidate.uri === uri);\n    if (ext) {\n      return ext.value;\n    }\n  }\n  return undefined;\n}\n\n/** Whether `id` stands for anything in `sdp` other than `uri`. */\nfunction usedForOtherURI(sdp: SessionDescription, id: number, uri: string): boolean {\n  return sdp.media.some((media) => media.ext?.some((ext) => ext.value === id && ext.uri !== uri));\n}\n\n/**\n * An id no extension in `sdp` uses. Stays above every id in use rather than filling gaps, so it\n * is less likely to be an id the browser goes on to allocate to another extension, and steps\n * over 15, which RFC 8285 reserves.\n */\nfunction unusedExtensionID(sdp: SessionDescription): number {\n  let maxID = 0;\n  sdp.media.forEach((media) => {\n    media.ext?.forEach((ext) => {\n      if (ext.value > maxID) {\n        maxID = ext.value;\n      }\n    });\n  });\n  return maxID + 1 === 15 ? 16 : maxID + 1;\n}\n\n/**\n * Checks whether an fmtp config declares `param` as an exact, `;`-delimited\n * token. A plain substring check conflates distinct opus parameters — e.g.\n * `stereo=1` is a substring of `sprop-stereo=1` — so `param` must match a whole\n * parameter, not appear anywhere within the config string.\n * @internal\n */\nexport function fmtpConfigHasParam(config: string, param: string): boolean {\n  return config.split(';').some((entry) => entry.trim() === param);\n}\n\n/** @internal */\nexport function ensureAudioNackAndStereo(\n  media: {\n    type: string;\n    port: number;\n    protocol: string;\n    payloads?: string | undefined;\n  } & MediaDescription,\n  stereoMids: string[],\n  nackMids: string[],\n) {\n  // sdp-transform types don't include number however the parser outputs mids as numbers in some cases\n  const mid = getMidString(media.mid!);\n  const includesThisSection = (mids: string[]) =>\n    mids.includes(mid) || (mids.length === 1 && mids[0] === 'all');\n\n  // found opus codec to add nack fb\n  let opusPayload = 0;\n  media.rtp.some((rtp): boolean => {\n    // rtpmap encoding names are case-insensitive (RFC 4855)\n    if (rtp.codec.toLowerCase() === 'opus') {\n      opusPayload = rtp.payload;\n      return true;\n    }\n    return false;\n  });\n\n  // add nack rtcpfb if not exist\n  if (opusPayload > 0) {\n    if (!media.rtcpFb) {\n      media.rtcpFb = [];\n    }\n\n    if (\n      includesThisSection(nackMids) &&\n      !media.rtcpFb.some((fb) => fb.payload === opusPayload && fb.type === 'nack')\n    ) {\n      media.rtcpFb.push({\n        payload: opusPayload,\n        type: 'nack',\n      });\n    }\n\n    if (includesThisSection(stereoMids)) {\n      media.fmtp.some((fmtp): boolean => {\n        if (fmtp.payload === opusPayload) {\n          if (!fmtpConfigHasParam(fmtp.config, 'stereo=1')) {\n            fmtp.config += ';stereo=1';\n          }\n          return true;\n        }\n        return false;\n      });\n    }\n  }\n}\n\n/**\n * Returns the mids of transceivers that carry no outgoing track: the\n * pre-populated placeholders added by `RTCEngine.applyInitialPublisherLayout`,\n * plus any transceiver that was used for a track and reverted on unpublish (below\n * server protocol 19; from protocol 19 unpublish stops it). The `sender.track`\n * check is the reliable signal — an unpublished section keeps its `a=msid` (and\n * its stale send-derived fmtp), so it can't be told apart from a real send by SDP\n * alone. Transceiver mids are stable across renegotiations, so\n * this works for every offer/answer after the first.\n * @internal\n */\nexport function placeholderMidsFromTransceivers(\n  transceivers: readonly RTCRtpTransceiver[],\n): Set<string> {\n  const mids = new Set<string>();\n  for (const transceiver of transceivers) {\n    if (transceiver.mid && !transceiver.sender.track) {\n      mids.add(transceiver.mid);\n    }\n  }\n  return mids;\n}\n\n/**\n * Within a BUNDLE group a payload type must map to identical codec parameters\n * across every m-line. When the same payload type carries different fmtp between\n * sections — e.g. opus `usedtx=1` on the published microphone but not on the\n * pre-populated recvonly placeholders, or H.265 with different `level-id` between\n * a published video track and a placeholder — libwebrtc flags a \"bundled payload\n * type collision\".\n *\n * Rewrite the placeholder sections so every shared payload type carries the\n * same fmtp. Real (non-placeholder) sections always win the canonical value, so\n * a published track's encoder parameters are never altered. When no real\n * section declares a payload type — e.g. a placeholder that was reused for a\n * track and then reverted to recvonly keeps its send-derived `level-id` while\n * fresh placeholders use the default — the placeholders still converge on the\n * first value seen, so two placeholders can't disagree either. Only placeholder\n * sections are ever rewritten, and it is codec-agnostic (opus, H.265, ...).\n * A codec without an `a=fmtp` line has empty parameters. Real sections that\n * disagree on a payload type are not reconciled: the placeholders follow the\n * last real section, and the real sections still differ.\n * `isPlaceholder` identifies the sections to conform.\n * @internal\n */\nexport function conformBundledCodecFmtp(\n  media: MediaDescription[],\n  isPlaceholder: (media: MediaDescription) => boolean,\n) {\n  // Canonical fmtp per payload type. Payload types are unique within a BUNDLE\n  // group, so keying by payload alone (across audio and video) is safe. A real\n  // section's value always takes precedence; otherwise the first placeholder\n  // value seen is used so divergent placeholders still converge.\n  const canonicalByPayload = new Map<number, string>();\n  for (const m of media) {\n    const placeholder = isPlaceholder(m);\n    for (const { payload } of m.rtp ?? []) {\n      const config = m.fmtp?.find((fmtp) => fmtp.payload === payload)?.config ?? '';\n      if (!placeholder || !canonicalByPayload.has(payload)) {\n        canonicalByPayload.set(payload, config);\n      }\n    }\n  }\n  // Conform placeholder sections to the canonical fmtp for each shared payload.\n  for (const m of media) {\n    if (!isPlaceholder(m)) {\n      continue;\n    }\n    for (const { payload } of m.rtp ?? []) {\n      // The first loop added every payload type a placeholder lists.\n      const config = canonicalByPayload.get(payload)!;\n      const fmtp = m.fmtp?.find((entry) => entry.payload === payload);\n      if (config === '') {\n        m.fmtp = (m.fmtp ?? []).filter((entry) => entry.payload !== payload);\n      } else if (fmtp) {\n        fmtp.config = config;\n      } else {\n        m.fmtp = [...(m.fmtp ?? []), { payload, config }];\n      }\n    }\n  }\n}\n\n/** @internal */\n/**\n * Whether an incoming answer repeats one already applied or being applied.\n * Any answer for the offer whose answer is in flight is a duplicate, numbered\n * or not. With an offerId (current servers) an answer is also a duplicate if\n * that offer's answer was already applied. Without one, fall back to the\n * signaling state: in `stable` no local offer is pending, unless the initial\n * offer is still deferred (it is set locally only once its answer arrives).\n */\nexport function isDuplicateAnswer(\n  offerId: number,\n  answerInFlight: number | undefined,\n  answeredOfferId: number,\n  signalingState: RTCSignalingState | undefined,\n  hasPendingInitialOffer: boolean,\n): boolean {\n  if (answerInFlight === offerId) return true;\n  if (offerId > 0) return offerId === answeredOfferId;\n  return signalingState === 'stable' && !hasPendingInitialOffer;\n}\n\nexport function extractStereoAndNackAudioFromOffer(offer: RTCSessionDescriptionInit): {\n  stereoMids: string[];\n  nackMids: string[];\n} {\n  const stereoMids: string[] = [];\n  const nackMids: string[] = [];\n  const sdpParsed = parse(offer.sdp ?? '');\n  let opusPayload = 0;\n  sdpParsed.media.forEach((media) => {\n    const mid = getMidString(media.mid!);\n    if (media.type === 'audio') {\n      media.rtp.some((rtp): boolean => {\n        // rtpmap encoding names are case-insensitive (RFC 4855)\n        if (rtp.codec.toLowerCase() === 'opus') {\n          opusPayload = rtp.payload;\n          return true;\n        }\n        return false;\n      });\n\n      if (media.rtcpFb?.some((fb) => fb.payload === opusPayload && fb.type === 'nack')) {\n        nackMids.push(mid);\n      }\n\n      media.fmtp.some((fmtp): boolean => {\n        if (fmtp.payload === opusPayload) {\n          if (fmtpConfigHasParam(fmtp.config, 'sprop-stereo=1')) {\n            stereoMids.push(mid);\n          }\n          return true;\n        }\n        return false;\n      });\n    }\n  });\n  return { stereoMids, nackMids };\n}\n\nfunction ensureIPAddrMatchVersion(media: MediaDescription) {\n  // Chrome could generate sdp with c = IN IP4 <ipv6 addr>\n  // in edge case and return error when set sdp.This is not a\n  // sdk error but correct it if the issue detected.\n  if (media.connection) {\n    const isV6 = media.connection.ip.indexOf(':') >= 0;\n    if ((media.connection.version === 4 && isV6) || (media.connection.version === 6 && !isV6)) {\n      // fallback to dummy address\n      media.connection.ip = '0.0.0.0';\n      media.connection.version = 4;\n    }\n  }\n}\n\nfunction getMidString(mid: string | number) {\n  return typeof mid === 'number' ? mid.toFixed(0) : mid;\n}\n\ntype PCTransportEventCallbacks = {\n  negotiationStarted: () => void;\n  negotiationComplete: () => void;\n  offerAnswered: (offerId: number) => void;\n  rtpVideoPayloadTypes: (attributes: MediaAttributes['rtp']) => void;\n};\n"],"names":["startBitrateMultiplier","maxStartBitrateKbps","minTargetBitrateKbps","setupTimeForMaxStartBitrateMs","setupTimeForMinStartBitrateMs","effectiveType3gStartBitrateKbps","debounceInterval","findTrackCodecPayload","media","cid","codec","_a","msid","includes","undefined","_c","_b","rtp","find","toUpperCase","payload","computeTrackStartBitrate","trackbr","connectionSetupTimeMs","maxbr","calculated","Math","min","round","isScreenShare","cap","computeStartBitrateCap","connectionEffectiveTypeStartBitrateCap","connection","navigator","effectiveType","ramp","max","computeConnectionStartBitrate","trackBitrates","connectionStartBitrate","m","type","direction","codecPayload","startBitrate","applyVideoStartBitrate","fmtp","entry","config","concat","push","PCEvents","NegotiationStarted","NegotiationComplete","OfferAnswered","RTPVideoPayloadTypes","PCTransport","EventEmitter","pc","_pc","createPC","constructor","loggerOptions","arguments","length","options","log","iceLog","ddExtID","latestOfferId","answeredOfferId","latestAcknowledgedOfferId","pendingCandidates","restartingIce","renegotiate","hasAppliedVideoStartBitrate","remoteStereoMids","remoteNackMids","negotiate","debounce","onError","__awaiter","emit","createAndSendOffer","e","close","debug","pendingInitialOffer","onconnectionstatechange","oniceconnectionstatechange","onicegatheringstatechange","ondatachannel","onnegotiationneeded","onsignalingstatechange","onicecandidate","ontrack","offeredAudioNackMids","singlePeerConnection","getLogger","loggerName","LoggerNames","logContext","ICE","offerLock","Mutex","RTCPeerConnection","ev","candidate","onIceCandidate","call","onicecandidateerror","event","onIceCandidateError","iceConnectionState","onIceConnectionStateChange","signalingState","onSignalingStatechange","connectionState","onConnectionStateChange","label","channel","id","onDataChannel","onTrack","Object","assign","loggerContextCb","isICEConnected","addIceCandidate","remoteDescription","pendingCount","isStaleAnswer","offerId","setRemoteDescription","sd","warn","isDuplicateAnswer","answerInFlight","applyRemoteDescription","mungedSDP","_extractStereoAndNack","extractStereoAndNackAudioFromOffer","stereoMids","nackMids","_this$pendingInitialO","original","munged","setMungedSDP","sdpParsed","parse","sdp","forEach","mid","getMidString","some","transceiver","fmtpFound","split","filter","attr","join","placeholderMids","getPlaceholderMids","size","conformBundledCodecFmtp","has","write","count","createInitialOffer","unlock","lock","offer","createOffer","ensureIPAddrMatchVersion","ensureAudioNackAndStereo","onOffer","iceRestart","currentSD","NegotiationError","connectionSetupTimeEstimateMs","appliedVideoStartBitrate","isSVCCodec","isSafari","ensureVideoDDExtension","mungedSdp","info","startBitrateKbps","createAndSetAnswer","answer","createAnswer","placeholderMidsFromTransceivers","getTransceivers","createDataChannel","dataChannelDict","addTransceiver","mediaStreamTrack","transceiverInit","addTransceiverOfKind","kind","addTrack","track","UnexpectedConnectionState","setTrackCodecBitrate","setConnectionSetupTime","ms","setConnectionStartedAt","startedAt","connectionStartedAt","performance","now","setConfiguration","rtcConfig","canRemoveTrack","removeTrack","sender","stop","stopTransceivers","senders","stopped","transceivers","isLive","t","currentDirection","receiver","error","getConnectionState","getICEConnectionState","getSignallingState","getSenders","getLocalDescription","localDescription","getRemoteDescription","getStats","getMaxMessageSize","sctp","maxMessageSize","getConnectedAddress","selectedCandidatePairId","candidatePairs","Map","candidates","stats","v","selected","set","address","port","selectedID","get","remoteCandidateId","remote","originalSdp","setLocalDescription","msg","Error","message","fields","remoteSdp","ddExtensionIDFor","ext","uri","ddExtensionURI","value","cachedID","mapped","mappedExtensionID","usedForOtherURI","unusedExtensionID","maxID","fmtpConfigHasParam","param","trim","includesThisSection","mids","opusPayload","toLowerCase","rtcpFb","fb","Set","add","isPlaceholder","canonicalByPayload","placeholder","_ref","_d","_ref2","_e","_f","_g","_h","hasPendingInitialOffer","isV6","ip","indexOf","version","toFixed"],"mappings":"oXAmBA;;;;;;;;;;;;;AAaG;AACH,MAAMA,sBAAsB,GAAG,GAAG;AAElC;AACA,MAAMC,mBAAmB,GAAG,IAAI;AAEhC;;;;AAIG;AACH,MAAMC,oBAAoB,GAAG,GAAG;AAEhC;;;;;;;;AAQG;AACH,MAAMC,6BAA6B,GAAG,IAAI;AAC1C,MAAMC,6BAA6B,GAAG,IAAI;AAE1C;AACA,MAAMC,+BAA+B,GAAG,GAAG;AAU3C,MAAMC,gBAAgB,GAAG,EAAE;AAE3B;;;;;;;AAOG;SACaC,qBAAqBA,CACnCC,KAAuB,EACvBC,GAAW,EACXC,KAAa,EAAA;;EAEb,IAAI,EAAC,CAAAC,EAAA,GAAAH,KAAK,CAACI,IAAI,MAAA,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