大网数据广告活动
Web 标准与前端开发

RTCRtpTransceiver: setCodecPreferences() method

· 52CE 我爱测

The **`setCodecPreferences()`** method of the RTCRtpTransceiver interface is used to set the codecs that the transceiver allows for decoding _received_ data, in order of decreasing preference.

WebRTC

The setCodecPreferences() method of the RTCRtpTransceiver interface is used to set the codecs that the transceiver allows for decoding received data, in order of decreasing preference.

The preferences set using this method influence what codecs are negotiated with the remote peer for encoding the data that it sends, including those used for retransmission, redundancy, and forward error correction. Codecs that are not included in the preferences list will not be part of the negotiation. Note that the preferences used by this transceiver for sending content depend on the preferences of the remote peer.

The recommended way to set codec preferences is to first get the array of codecs that are actually supported for decoding received data, then reorder them your in decreasing preference order. This ensures that the array is ordered as required, does not contain any unsupported codecs, and also that it also contains codecs that are needed for retransmission, redundancy, and forward error correction.

The specified set of codecs will be used for all future connections that include this transceiver until this method is called again.

When preparing to open an RTCPeerConnection the codecs should be set using setCodecPreferences() before calling either RTCPeerConnection.createOffer() or RTCPeerConnection.createAnswer, as these initiate the negotiation (and will use codec parameters from the user agent default configuration by default).

The codecs can be changed when you have an ongoing communication, but you need to first call setCodecPreferences() and then kick off a new negotiation. A WebRTC application will already have code for this in the negotiationneeded event handler. Note however that at time of writing the event is not automatically fired when you call setCodecPreferences(), so you will have to call onnegotiationneeded yourself.

A guide to codecs supported by WebRTC—and each codec's positive and negative characteristics—can be found in Codecs used by WebRTC.

Syntax

setCodecPreferences(codecs)

Parameters

  • codecs
    • : An array of objects, each providing the parameters for one of the transceiver's supported media codecs, ordered by preference. If codecs is empty, the codec configurations are all returned to the user agent's defaults.

      [!NOTE] Any codecs not included in codecs will not be considered during the process of negotiating a connection. This lets you prevent the use of codecs you don't wish to use.

      Each codec object in the array has the following properties:

      • channels

        • : A positive integer indicating the number of channels supported by the codec. For example, for audio codecs a value of 1 specifies monaural sound, while 2 indicates stereo.
      • clockRate

        • : A positive integer specifying the codec's clock rate in Hertz (Hz). The clock rate is the rate at which the codec's RTP timestamp advances. Most codecs have specific values or ranges of values they permit. The IANA maintains a list of codecs and their parameters, including their clock rates.
      • mimeType

        • : A string indicating the codec's MIME media type and subtype, specified as a string of the form "type/subtype". The MIME type strings used by RTP differ from those used elsewhere. IANA maintains a registry of valid MIME types. Also see Codecs used by WebRTC for details about potential codecs that might be referenced here.
      • sdpFmtpLine

        • : A string giving the format specific parameters field from the a=fmtp line in the SDP which corresponds to the codec, if the field is present. If there is no parameters field, this property is left out.

Return value

None (undefined).

Exceptions

  • InvalidAccessError DOMException
    • : The codecs list includes one or more codecs which are not supported by the RTCRtpReceiver associated with the transceiver.
  • InvalidModificationError DOMException
    • : The codecs list only contains entries for RTX, RED, FEC or Comfort Noise, or is an empty set. The codecs must always contain a codec for the media.

Examples

Creating the array of preferred codecs

The recommended way to set codec preferences is to first get the array of codecs that are actually supported for decoding received data, then reorder the list in decreasing preference order.

It is important to start with the list of codecs that are supported (and not a hardcoded list of your preferred codecs), because you if you include any that aren't supported by the associated RTCRtpReceiver the browser will throw an InvalidAccessError exception when you call the setCodecPreferences() method. In addition, the array has to include appropriate codecs for retransmission, redundancy, and forward error correction, and starting with the list of supported codecs ensures that these are present.

You can get the codecs supported for decoding data using the RTCRtpReceiver.getCapabilities_static static method as shown:

const availReceiveCodecs = transceiver.receiver.getCapabilities("video").codecs;

To reorder the codecs array to our preferred order, we can use the sorting function below to sort on MIME type (this comes from setCodecPreferences is now in all browsers! on blog.mozilla.org (2024)).

function sortByMimeTypes(codecs, preferredOrder) {
  return codecs.sort((a, b) => {
    const indexA = preferredOrder.indexOf(a.mimeType);
    const indexB = preferredOrder.indexOf(b.mimeType);
    const orderA = indexA >= 0 ? indexA : Number.MAX_VALUE;
    const orderB = indexB >= 0 ? indexB : Number.MAX_VALUE;
    return orderA - orderB;
  });
}

The method takes the list of supported codecs, and an array containing the preferred MIME types, in decreasing order, and returns the array sorted in place. The code below shows how this is used, assuming that you have already set up a peer connection (peerConnection):

// Get supported codecs the sort using preferred codecs
const supportedCodecs = RTCRtpReceiver.getCapabilities("video").codecs;
const preferredCodecs = ["video/H264", "video/VP8", "video/VP9"];
const sortedCodecs = sortByMimeTypes(supportedCodecs, preferredCodecs);

// Get transceiver for connection and set the preferences
const [transceiver] = peerConnection.getTransceivers();
transceiver.setCodecPreferences(sortedCodecs); // <---

Specifications

Browser compatibility

See also

来源:MDN Web Docs / Mozilla 贡献者 · 作者与贡献记录 · CC BY-SA 2.5。离线整理了版式、链接和媒体显示。

资料来源与适用范围

资料来源
MDN Web Docs / Mozilla 贡献者
适用范围
请按文中版本与环境说明核对
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 2.5

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。