### Example RTCIceServer Configuration Source: https://www.w3.org/TR/webrtc/index An example demonstrating how to configure an array of RTCIceServer objects, including STUN and TURN servers with authentication credentials. ```javascript [ {urls: 'stun:stun1.example.net'}, {urls: ['turns:turn.example.org', 'turn:turn.example.net'], username: 'user', credential: 'myPassword', ]; ``` -------------------------------- ### WebRTC Peer-to-Peer Connection Setup Source: https://www.w3.org/TR/webrtc/index Sets up a WebRTC peer-to-peer connection, handling ICE candidates, media tracks, and signaling messages. It requires a SignalingChannel implementation and DOM elements for video display (selfView, remoteView). ```javascript const signaling = new SignalingChannel(); // handles JSON.stringify/parse const constraints = {audio: true, video: true}; const configuration = {iceServers: [{urls: 'stun:stun.example.org'}]}; const pc = new RTCPeerConnection(configuration); // send any ice candidates to the other peer pc.onicecandidate = ({candidate}) => signaling.send({candidate}); // let the "negotiationneeded" event trigger offer generation pc.onnegotiationneeded = async () => { try { await pc.setLocalDescription(); // send the offer to the other peer signaling.send({description: pc.localDescription}); } catch (err) { console.error(err); } }; pc.ontrack = ({track, streams}) => { // once media for a remote track arrives, show it in the remote video element track.onunmute = () => { // don't set srcObject again if it is already set. if (remoteView.srcObject) return; remoteView.srcObject = streams[0]; }; }; // call start() to initiate function start() { addCameraMic(); } // add camera and microphone to connection async function addCameraMic() { try { // get a local stream, show it in a self-view and add it to be sent const stream = await navigator.mediaDevices.getUserMedia(constraints); for (const track of stream.getTracks()) { pc.addTrack(track, stream); } selfView.srcObject = stream; } catch (err) { console.error(err); } } signaling.onmessage = async ({data: {description, candidate}}) => { try { if (description) { await pc.setRemoteDescription(description); // if we got an offer, we need to reply with an answer if (description.type == 'offer') { if (!selfView.srcObject) { // blocks negotiation on permission (not recommended in production code) await addCameraMic(); } await pc.setLocalDescription(); signaling.send({description: pc.localDescription}); } } else if (candidate) { await pc.addIceCandidate(candidate); } } catch (err) { console.error(err); } }; ``` -------------------------------- ### Simulcast Encoding Parameters Example (JavaScript) Source: https://www.w3.org/TR/webrtc/index This example shows how to configure encoding parameters for a 3-layer spatial simulcast scenario, disabling higher resolution layers. ```javascript var encodings = [ {rid: 'q', active: true, scaleResolutionDownBy: 4.0} {rid: 'h', active: false, scaleResolutionDownBy: 2.0}, {rid: 'f', active: false}, ]; ``` -------------------------------- ### Configure WebRTC Identity Provider (Advanced) Source: https://www.w3.org/TR/webrtc/-identity This example shows how to configure the identity provider with additional options, such as a username hint and a specific peer identity. This allows for more granular control over the identity assertion process. ```javascript pc.setIdentityProvider('example.com', { usernameHint: 'alice@example.com', peerIdentity: 'bob@example.net' }); ``` -------------------------------- ### Configure WebRTC Identity Provider (Simple) Source: https://www.w3.org/TR/webrtc/-identity This example demonstrates the basic method for setting an identity provider for a WebRTC connection. It takes the identity provider's domain as a string argument. ```javascript pc.setIdentityProvider('example.com'); ``` -------------------------------- ### WebRTC Peer-to-Peer Data Channel Example: Chat Application Source: https://www.w3.org/TR/webrtc/index This JavaScript example demonstrates setting up an RTCDataChannel for peer-to-peer communication, suitable for a simple chat application. It uses the 'negotiated' pattern for channel creation and includes offer/answer exchange via a SignalingChannel. Input for chat messages is handled, and received messages are displayed. ```javascript const signaling = new SignalingChannel(); // handles JSON.stringify/parse const configuration = {iceServers: [{urls: 'stun:stun.example.org'}]}; let pc, channel; // call start() to initiate function start() { pc = new RTCPeerConnection(configuration); // send any ice candidates to the other peer pc.onicecandidate = ({candidate}) => signaling.send({candidate}); // let the "negotiationneeded" event trigger offer generation pc.onnegotiationneeded = async () => { try { await pc.setLocalDescription(); // send the offer to the other peer signaling.send({description: pc.localDescription}); } catch (err) { console.error(err); } }; // create data channel and setup chat using "negotiated" pattern channel = pc.createDataChannel('chat', {negotiated: true, id: 0}); channel.onopen = () => input.disabled = false; channel.onmessage = ({data}) => showChatMessage(data); input.onkeydown = ({key}) => { if (key != 'Enter') return; channel.send(input.value); } } signaling.onmessage = async ({data: {description, candidate}}) => { if (!pc) start(); try { if (description) { await pc.setRemoteDescription(description); // if we got an offer, we need to reply with an answer if (description.type == 'offer') { await pc.setLocalDescription(); signaling.send({description: pc.localDescription}); } } else if (candidate) { await pc.addIceCandidate(candidate); } } catch (err) { console.error(err); } }; ``` -------------------------------- ### WebRTC Session Description Negotiation (Offer/Answer) Source: https://context7.com/context7/w3_tr_webrtc/llms.txt Manages the creation and exchange of Session Description Protocol (SDP) offers and answers to establish a WebRTC connection. This involves getting local media, creating offers/answers, setting local/remote descriptions, and sending them via a signaling channel. ```javascript // Caller: Create offer async function startCall() { try { const localStream = await navigator.mediaDevices.getUserMedia({ video: true, audio: true }); localStream.getTracks().forEach(track => { pc.addTrack(track, localStream); }); const offer = await pc.createOffer({ iceRestart: false }); await pc.setLocalDescription(offer); // Send offer to remote peer signalingChannel.send({ type: 'offer', sdp: pc.localDescription }); } catch (error) { console.error('Error creating offer:', error); } } // Callee: Receive offer and create answer async function handleOffer(offer) { try { await pc.setRemoteDescription(new RTCSessionDescription(offer)); const answer = await pc.createAnswer(); await pc.setLocalDescription(answer); // Send answer back to caller signalingChannel.send({ type: 'answer', sdp: pc.localDescription }); } catch (error) { console.error('Error handling offer:', error); } } // Caller: Receive answer async function handleAnswer(answer) { try { await pc.setRemoteDescription(new RTCSessionDescription(answer)); } catch (error) { console.error('Error handling answer:', error); } } ``` -------------------------------- ### Send DTMF with Keylight Feedback Source: https://www.w3.org/TR/webrtc/index This example sends DTMF tones while simultaneously controlling external feedback, such as lighting up a key, using a `lightKey` function. It defines a `wait` utility function and uses the `sender.dtmf.ontonechange` event to trigger `lightKey` when a tone starts and turn it off after the tone's duration. ```javascript const wait = ms => new Promise(resolve => setTimeout(resolve, ms)); if (sender.dtmf.canInsertDTMF) { const duration = 500; // ms sender.dtmf.insertDTMF(sender.dtmf.toneBuffer + '1234', duration); sender.dtmf.ontonechange = async ({tone}) => { if (!tone) return; lightKey(tone); // light up the key when playout starts await wait(duration); lightKey(''); // turn off the light after tone duration }; } else { console.log('DTMF function not available'); } ``` -------------------------------- ### WebRTC Simulcast Example: Sending Multiple RTP Encodings Source: https://www.w3.org/TR/webrtc/index This JavaScript example demonstrates how to send multiple RTP encodings (simulcast) to a server using WebRTC. It configures RTCRtpTransceiver to send video with different resolutions and qualities, controlled by sendEncodings. It requires a SignalingChannel for communication and navigator.mediaDevices.getUserMedia for accessing the local stream. ```javascript const signaling = new SignalingChannel(); // handles JSON.stringify/parse const constraints = {audio: true, video: true}; const configuration = {'iceServers': [{'urls': 'stun:stun.example.org'}]}; let pc; // call start() to initiate async function start() { pc = new RTCPeerConnection(configuration); // let the "negotiationneeded" event trigger offer generation pc.onnegotiationneeded = async () => { try { await pc.setLocalDescription(); // send the offer to the other peer signaling.send({description: pc.localDescription}); } catch (err) { console.error(err); } }; try { // get a local stream, show it in a self-view and add it to be sent const stream = await navigator.mediaDevices.getUserMedia(constraints); selfView.srcObject = stream; pc.addTransceiver(stream.getAudioTracks()[0], {direction: 'sendonly'}); pc.addTransceiver(stream.getVideoTracks()[0], { direction: 'sendonly', sendEncodings: [ {rid: 'q', scaleResolutionDownBy: 4.0} {rid: 'h', scaleResolutionDownBy: 2.0}, {rid: 'f'}, ] }); } catch (err) { console.error(err); } } signaling.onmessage = async ({data: {description, candidate}}) => { try { if (description) { await pc.setRemoteDescription(description); // if we got an offer, we need to reply with an answer if (description.type == 'offer') { await pc.setLocalDescription(); signaling.send({description: pc.localDescription}); } } else if (candidate) { await pc.addIceCandidate(candidate); } } catch (err) { console.error(err); } }; ``` -------------------------------- ### WebRTC "Hold" Functionality Examples (JavaScript) Source: https://www.w3.org/TR/webrtc/index These examples demonstrate implementing "hold" functionality in WebRTC, including sending music on hold, responding to "sendonly" offers, stopping music, and responding to being taken off hold. They utilize the direction attribute and replaceTrack method. ```javascript async function playMusicOnHold() { try { // Assume we have an audio transceiver and a music track named musicTrack await audio.sender.replaceTrack(musicTrack); // Mute received audio audio.receiver.track.enabled = false; // Set the direction to send-only (requires negotiation) audio.direction = 'sendonly'; } catch (err) { console.error(err); } } ``` ```javascript async function handleSendonlyOffer() { try { // Apply the sendonly offer first, // to ensure the receiver is ready for ICE candidates. await pc.setRemoteDescription(sendonlyOffer); // Stop sending audio await audio.sender.replaceTrack(null); // Align our direction to avoid further negotiation audio.direction = 'recvonly'; // Call createAnswer and send a recvonly answer await doAnswer(); } catch (err) { // handle signaling error } } ``` ```javascript async function stopOnHoldMusic() { // Assume we have an audio transceiver and a microphone track named micTrack await audio.sender.replaceTrack(micTrack); // Unmute received audio audio.receiver.track.enabled = true; // Set the direction to sendrecv (requires negotiation) audio.direction = 'sendrecv'; } ``` ```javascript async function onOffHold() { try { // Apply the sendrecv offer first, to ensure receiver is ready for ICE candidates. await pc.setRemoteDescription(sendrecvOffer); // Start sending audio await audio.sender.replaceTrack(micTrack); // Set the direction sendrecv (just in time for the answer) audio.direction = 'sendrecv'; // Call createAnswer and send a sendrecv answer await doAnswer(); } catch (err) { // handle signaling error } } ``` -------------------------------- ### Configure RTP Sender Encoding Parameters for Simulcast and Bitrate Control (JavaScript) Source: https://context7.com/context7/w3_tr_webrtc/llms.txt This example shows how to configure the encoding parameters for an RTP sender, enabling features like simulcast for adaptive video quality and controlling bitrate for different encoding layers. It includes setting up initial encoding parameters, dynamically adjusting them, and replacing the media track without requiring a full renegotiation. ```javascript // Add video track with simulcast const videoTrack = localStream.getVideoTracks()[0]; const sender = pc.addTrack(videoTrack, localStream); // Get current parameters const params = sender.getParameters(); if (!params.encodings || params.encodings.length === 0) { params.encodings = [ { rid: 'h', scaleResolutionDownBy: 1.0, maxBitrate: 900000 }, { rid: 'm', scaleResolutionDownBy: 2.0, maxBitrate: 300000 }, { rid: 'l', scaleResolutionDownBy: 4.0, maxBitrate: 100000 } ]; } // Set encoding parameters try { await sender.setParameters(params); console.log('Simulcast configured'); } catch (error) { console.error('Failed to set parameters:', error); } // Temporarily disable an encoding layer const updatedParams = sender.getParameters(); updatedParams.encodings[2].active = false; // Disable low layer await sender.setParameters(updatedParams); // Replace track without renegotiation const newTrack = await getScreenShareTrack(); await sender.replaceTrack(newTrack); ``` -------------------------------- ### Send Sequential DTMF Tones with Different Durations Source: https://www.w3.org/TR/webrtc/index This example sends a sequence of DTMF tones with distinct durations. It uses the `sender.dtmf.ontonechange` event to schedule the next tone with its specific duration (1 second for '1', 2 seconds for '2') after the previous tone has started playing. ```javascript if (sender.dtmf.canInsertDTMF) { sender.dtmf.ontonechange = ({tone}) => { if (tone == '1') { sender.dtmf.insertDTMF(sender.dtmf.toneBuffer + '2', 2000); } }; sender.dtmf.insertDTMF(sender.dtmf.toneBuffer + '1', 1000); } else { console.log('DTMF function not available'); } ``` -------------------------------- ### Send DTMF Tones with Duration Source: https://www.w3.org/TR/webrtc/index This example demonstrates how to send a sequence of DTMF tones with a specified duration for each tone. It first checks if DTMF insertion is supported using `sender.dtmf.canInsertDTMF`. If supported, it calls `sender.dtmf.insertDTMF` with the tone string and duration in milliseconds. ```javascript if (sender.dtmf.canInsertDTMF) { const duration = 500; sender.dtmf.insertDTMF('1234', duration); } else { console.log('DTMF function not available'); } ``` -------------------------------- ### Receive Simulcast with setRemoteDescription Source: https://www.w3.org/TR/webrtc/index This example shows how to configure an `RTCPeerConnection` to receive simulcast streams when acting as the answerer. The `setRemoteDescription` method is used with a remote offer that specifies multiple RTP encodings, allowing the `RTCRtpSender` to establish a simulcast envelope. ```javascript const peerConnection = new RTCPeerConnection(); const offer = new RTCSessionDescription({ type: 'offer', sdp: 'v=0\r\no=- 1234 1234 IN IP4 127.0.0.1\r\ns=simulcast-test\r\nt=0 0\r\n' + 'm=video 9 UDP/TLS/RTP/SAVPF 96\r\nc=IN IP4 0.0.0.0\r\n' + 'a=rtcp-mux\r\n' + 'a=sendrecv\r\n' + 'a=simulcast:send \'1\'\r\n' + 'a=rtpmap:96 VP8/90000\r\n' + 'a=fmtp:96\r\n' + 'a=ssrc:123456789 cname:user1@example.com\r\n' + 'a=ssrc:123456789 msid:stream1 track1\r\n' + 'a=ssrc:123456789 max-width=1920\r\n' + 'a=ssrc:123456789 max-height=1080\r\n' + 'a=ssrc:987654321 cname:user1@example.com\r\n' + 'a=ssrc:987654321 msid:stream1 track1\r\n' + 'a=ssrc:987654321 max-width=1280\r\n' + 'a=ssrc:987654321 max-height=720\r\n' }); await peerConnection.setRemoteDescription(offer); const answer = await peerConnection.createAnswer(); await peerConnection.setLocalDescription(answer); ``` -------------------------------- ### Generate and Use DTLS Certificates in WebRTC (JavaScript) Source: https://context7.com/context7/w3_tr_webrtc/llms.txt Demonstrates how to generate DTLS certificates for RTCPeerConnection using different algorithms (ECDSA, RSA). It includes examples of using generated certificates and storing/loading them from IndexedDB for persistence. ```javascript const certOptions = { name: 'ECDSA', namedCurve: 'P-256' }; const certificate = await RTCPeerConnection.generateCertificate(certOptions); console.log('Certificate expires:', new Date(certificate.expires)); console.log('Certificate fingerprints:', certificate.getFingerprints()); const pcWithCert = new RTCPeerConnection({ certificates: [certificate], iceServers: config.iceServers }); async function storeCertificate(cert) { const db = await openDatabase(); const tx = db.transaction('certificates', 'readwrite'); await tx.objectStore('certificates').put({ id: 'my-cert', certificate: cert, expires: cert.expires }); } async function loadCertificate() { const db = await openDatabase(); const tx = db.transaction('certificates', 'readonly'); const stored = await tx.objectStore('certificates').get('my-cert'); if (stored && stored.expires > Date.now()) { return stored.certificate; } return null; } const rsaCert = await RTCPeerConnection.generateCertificate({ name: 'RSASSA-PKCS1-v1_5', modulusLength: 2048, publicExponent: new Uint8Array([1, 0, 1]), hash: 'SHA-256' }); ``` -------------------------------- ### RTCPeerConnection Interface Extensions for Identity Management Source: https://www.w3.org/TR/webrtc/-identity Extends the RTCPeerConnection interface with methods and attributes for identity provider integration, assertion retrieval, and error reporting. This includes setting the identity provider, getting an identity assertion, and accessing properties related to the peer's identity, login URL, and error information. ```javascript partial interface RTCPeerConnection { void setIdentityProvider(DOMString provider, optional RTCIdentityProviderOptions options); Promise getIdentityAssertion(); readonly attribute Promise peerIdentity; readonly attribute DOMString? idpLoginUrl; readonly attribute DOMString? idpErrorInfo; }; ``` -------------------------------- ### RTCIceCandidate Constructor Initialization Source: https://www.w3.org/TR/webrtc/index Explains the steps involved in creating and initializing an RTCIceCandidate object using the constructor with an optional candidateInitDict. It includes basic parsing and type checking. ```pseudocode // Steps to create an RTCIceCandidate with candidateInitDict: // 1. Let iceCandidate be a newly created RTCIceCandidate object. // 2. Create internal slots for attributes (foundation, component, etc.), initialized to null. // 3. Create internal slots for candidate, sdpMid, sdpMLineIndex, usernameFragment, initialized from candidateInitDict. // 4. Parse the candidate string from candidateInitDict if not empty. // 5. If parsing fails or values are invalid, abort or set attributes to null. // 6. Set corresponding internal slots in iceCandidate to the parsed field values. // 7. Return iceCandidate. ``` -------------------------------- ### RTCPeerConnection.createOffer() Source: https://www.w3.org/TR/webrtc/index Generates an SDP offer containing supported session configurations, local media stream descriptions, codec capabilities, ICE agent parameters, and DTLS connection details. ```APIDOC ## POST /websites/w3_tr_webrtc/createOffer ### Description Generates a Session Description Protocol (SDP) offer. This offer includes information about the local media streams, supported codecs, ICE agent configuration, and DTLS connection parameters. It reflects the current state of the `RTCPeerConnection` and must be valid for subsequent `setLocalDescription` calls. ### Method POST ### Endpoint `/websites/w3_tr_webrtc/createOffer` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **options** (object) - Optional - Provides additional control over the offer generation process. The specific fields depend on the WebRTC implementation. ### Request Example ```json { "options": { "offerToReceiveAudio": true, "offerToReceiveVideo": false } } ``` ### Response #### Success Response (200) - **sdp** (string) - The generated SDP offer. - **type** (string) - The type of the session description, which will be "offer". #### Response Example ```json { "sdp": "v=0\r\no=- 1234567890 1234567890 IN IP4 192.168.1.1\r\ns=My WebRTC Session\r\nt=0 0\r\n... (rest of SDP offer)", "type": "offer" } ``` #### Error Response - **InvalidStateError**: Thrown if the `RTCPeerConnection` is closed. - **OperationError**: Thrown if the inspection of system state fails during offer creation. ``` -------------------------------- ### RTCRtpSender Interface Definition - WebIDL Source: https://www.w3.org/TR/webrtc/index Defines the RTCRtpSender interface, outlining its readonly attributes and methods for controlling media transmission. This includes methods for getting capabilities, setting and getting transmission parameters, replacing tracks, setting streams, and retrieving statistics. ```WebIDL WebIDL[Exposed=Window] interface RTCRtpSender { readonly attribute MediaStreamTrack? track; readonly attribute RTCDtlsTransport? transport; static RTCRtpCapabilities? getCapabilities(DOMString kind); Promise setParameters(RTCRtpSendParameters parameters, optional RTCSetParameterOptions setParameterOptions = {}); RTCRtpSendParameters getParameters(); Promise replaceTrack(MediaStreamTrack? withTrack); undefined setStreams(MediaStream... streams); Promise getStats(); }; ``` -------------------------------- ### Instantiating an IdP Proxy Source: https://www.w3.org/TR/webrtc/-identity Explains how the user agent loads the IdP JavaScript and instantiates an isolated JavaScript realm to communicate with the IdP. ```APIDOC ## Instantiating an IdP Proxy ### Description User agents load IdP JavaScript from a well-known URI. This script is executed in an isolated JavaScript realm operating in the origin of the loaded script. The realm is populated with a global scope implementing `RTCIdentityProviderGlobalScope` and `WorkerGlobalScope`, providing access to `RTCIdentityProviderRegistrar`. ### Key Components - **IdP Script URI**: A well-known URI derived from "domain" and "protocol" fields. - **Origin Management**: Redirects to non-"https" origins are fatal errors. Redirects change the script's origin. - **JavaScript Realm**: An isolated context with `RTCIdentityProviderGlobalScope` and `WorkerGlobalScope` interfaces. - **`rtcIdentityProvider`**: An instance of `RTCIdentityProviderRegistrar` available in the global scope for IdP interaction. ### Interface: `RTCIdentityProviderGlobalScope` ``` [Global, Exposed=RTCIdentityProviderGlobalScope] interface RTCIdentityProviderGlobalScope : WorkerGlobalScope { readonly attribute RTCIdentityProviderRegistrar rtcIdentityProvider; }; ``` #### Attribute `rtcIdentityProvider` - **Type**: `RTCIdentityProviderRegistrar` - **Description**: Readonly attribute used by the IdP to register an `RTCIdentityProvider` instance with the browser. ``` -------------------------------- ### RTCPeerConnection Constructor and Core Methods Source: https://www.w3.org/TR/webrtc/index Defines the RTCPeerConnection interface, its constructor, and core methods for creating offers/answers, setting local/remote descriptions, and managing ICE candidates. ```APIDOC ## RTCPeerConnection Interface ### Description The `RTCPeerConnection` interface represents a peer-to-peer connection to a remote peer. ### Methods #### constructor ```javascript constructor(optional RTCConfiguration configuration = {}) ``` - Initializes a new `RTCPeerConnection` object. #### createOffer ```javascript Promise createOffer(optional RTCOfferOptions options = {}) ``` - Creates an SDP offer for a new or existing connection. #### createAnswer ```javascript Promise createAnswer(optional RTCAnswerOptions options = {}) ``` - Creates an SDP answer to an offer received from a remote peer. #### setLocalDescription ```javascript Promise setLocalDescription(optional RTCLocalSessionDescriptionInit description = {}) ``` - Sets the local description, usually after creating an offer or answer. #### setRemoteDescription ```javascript Promise setRemoteDescription(RTCSessionDescriptionInit description) ``` - Sets the remote description received from a peer. #### addIceCandidate ```javascript Promise addIceCandidate(optional RTCIceCandidateInit candidate = {}) ``` - Adds an ICE candidate gathered from the network to the connection. ### Attributes - **localDescription** (RTCSessionDescription?): The local session description. - **currentLocalDescription** (RTCSessionDescription?): The current local session description. - **pendingLocalDescription** (RTCSessionDescription?): The pending local session description. - **remoteDescription** (RTCSessionDescription?): The remote session description. - **currentRemoteDescription** (RTCSessionDescription?): The current remote session description. - **pendingRemoteDescription** (RTCSessionDescription?): The pending remote session description. - **signalingState** (RTCSignalingState): The signaling state of the connection. - **iceGatheringState** (RTCIceGatheringState): The ICE gathering state. - **iceConnectionState** (RTCIceConnectionState): The ICE connection state. - **connectionState** (RTCPeerConnectionState): The connection state. - **canTrickleIceCandidates** (boolean?): Indicates if trickle ICE candidates are supported. ### Event Handlers - **onnegotiationneeded**: Fired when a negotiation is needed. - **onicecandidate**: Fired when an ICE candidate is gathered. - **onicecandidateerror**: Fired when an error occurs during ICE candidate gathering. - **onsignalingstatechange**: Fired when the signaling state changes. - **oniceconnectionstatechange**: Fired when the ICE connection state changes. - **onicegatheringstatechange**: Fired when the ICE gathering state changes. - **onconnectionstatechange**: Fired when the connection state changes. ### Legacy Interface Extensions These methods are optional but must be implemented if supported. #### createOffer (Legacy) ```javascript Promise createOffer(RTCSessionDescriptionCallback successCallback, RTCPeerConnectionErrorCallback failureCallback, optional RTCOfferOptions options = {}) ``` #### setLocalDescription (Legacy) ```javascript Promise setLocalDescription(RTCLocalSessionDescriptionInit description, VoidFunction successCallback, RTCPeerConnectionErrorCallback failureCallback) ``` #### createAnswer (Legacy) ```javascript Promise createAnswer(RTCSessionDescriptionCallback successCallback, RTCPeerConnectionErrorCallback failureCallback) ``` #### setRemoteDescription (Legacy) ```javascript Promise setRemoteDescription(RTCSessionDescriptionInit description, VoidFunction successCallback, RTCPeerConnectionErrorCallback failureCallback) ``` #### addIceCandidate (Legacy) ```javascript Promise addIceCandidate(RTCIceCandidateInit candidate, VoidFunction successCallback, RTCPeerConnectionErrorCallback failureCallback) ``` ``` -------------------------------- ### RTCPeerConnection createOffer Source: https://www.w3.org/TR/webrtc/index Creates an SDP offer for establishing a WebRTC connection. It accepts success and failure callbacks, and optional configuration options. ```APIDOC ## POST /webrtc/offer ### Description Creates an SDP offer for establishing a WebRTC connection. It accepts success and failure callbacks, and optional configuration options. ### Method POST ### Endpoint /webrtc/offer ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **successCallback** (function) - Required - Callback function invoked upon successful offer creation. - **failureCallback** (function) - Required - Callback function invoked upon failure to create offer. - **options** (object) - Optional - Configuration options for offer creation. ### Request Example ```json { "successCallback": "function(offer) { ... }", "failureCallback": "function(error) { ... }", "options": { ... } } ``` ### Response #### Success Response (200) - **undefined** - The promise resolves with undefined upon successful execution. #### Response Example ```json { "message": "Offer created successfully, callback invoked." } ``` ``` -------------------------------- ### RTCOfferOptions Dictionary Source: https://www.w3.org/TR/webrtc/index Options specific to creating an offer, including the ability to restart ICE. ```APIDOC ## RTCOfferOptions Dictionary ### Description Options that can be used to control the offer creation process, including ICE restart. ### Members * **iceRestart** (boolean) - Optional - Defaults to `false`. When `true`, the generated description will have ICE credentials different from the current ones, causing ICE to restart. Recommended when `iceConnectionState` transitions to `failed`. ``` -------------------------------- ### Create Offer for WebRTC Source: https://www.w3.org/TR/webrtc/index The createOffer method generates an SDP offer to establish a WebRTC connection. It accepts success and failure callbacks, and optional configuration options. The method returns a promise that resolves with undefined. ```javascript RTCPeerConnection.prototype.createOffer = function(successCallback, failureCallback, options) { // ... implementation details ... return Promise.resolve(undefined); }; ``` -------------------------------- ### Generate RTCCertificate with Custom Expiration Source: https://www.w3.org/TR/webrtc/index Generates an RTCCertificate with a custom expiration time, specified in milliseconds. The 'expires' value is capped at a maximum of 365 days (31536000000 milliseconds) from the creation time. The example uses the RSASSA-PKCS1-v1_5 algorithm. ```javascript const certificate = await RTCPeerConnection.generateCertificate({ name: "RSASSA-PKCS1-v1_5", modulusLength: 2048, publicExponent: new Uint8Array([1, 0, 1]), hash: "SHA-256", expires: 31536000000 // 365 days in milliseconds }); ``` -------------------------------- ### Peer-to-peer connections Source: https://www.w3.org/TR/webrtc/index APIs for establishing and managing peer-to-peer connections, including configuration, state management, and session negotiation. ```APIDOC ## Peer-to-peer connections API ### Description Provides interfaces and data structures for establishing and managing peer-to-peer connections using technologies like ICE, STUN, and TURN. ### Method N/A (Interface definitions) ### Endpoint N/A (Interface definitions) ### Parameters None ### Request Example None ### Response None ``` -------------------------------- ### Analyze Packet Loss with WebRTC Statistics (JavaScript) Source: https://www.w3.org/TR/webrtc/-stats An example demonstrating how to retrieve and process sender statistics in JavaScript to detect packet loss. It compares baseline statistics with current statistics to calculate the interval fraction loss. ```javascript var baselineReport, currentReport; var sender = pc.getSenders()[0]; sender.getStats().then(function (report) { baselineReport = report; }) .then(function() { return new Promise(function(resolve) { setTimeout(resolve, aBit); // ... wait a bit }); }) .then(function() { return sender.getStats(); }) .then(function (report) { currentReport = report; processStats(); }) .catch(function (error) { console.log(error.toString()); }); function processStats() { // compare the elements from the current report with the baseline for (let now of currentReport.values()) { if (now.type != "outbound-rtp") continue; // get the corresponding stats from the baseline report let base = baselineReport.get(now.id); if (base) { remoteNow = currentReport.get(now.remoteId); remoteBase = baselineReport.get(base.remoteId); var packetsSent = now.packetsSent - base.packetsSent; var packetsReceived = remoteNow.packetsReceived - remoteBase.packetsReceived; // if intervalFractionLoss is > 0.3, we've probably found the culprit var intervalFractionLoss = (packetsSent - packetsReceived) / packetsSent; } }); } ``` -------------------------------- ### RTCIceCandidateInit Dictionary Source: https://www.w3.org/TR/webrtc/index Defines the structure for initializing an RTCIceCandidate. ```APIDOC ## Dictionary `RTCIceCandidateInit` ### Description Represents the members used to initialize an `RTCIceCandidate` object. ### Members - **candidate** (DOMString) - Defaults to `""`. The candidate-attribute as defined in RFC5245. An empty string indicates an end-of-candidates. - **sdpMid** (DOMString? | null) - Defaults to `null`. The media stream "identification-tag" associated with the candidate. - **sdpMLineIndex** (unsigned short? | null) - Defaults to `null`. The index of the media description in the SDP this candidate is associated with. - **usernameFragment** (DOMString? | null) - Defaults to `null`. The `ufrag` as defined in RFC5245. ``` -------------------------------- ### RTCPeerConnection createAnswer Source: https://www.w3.org/TR/webrtc/index Creates an SDP answer for establishing a WebRTC connection. It accepts success and failure callbacks. ```APIDOC ## POST /webrtc/answer ### Description Creates an SDP answer for establishing a WebRTC connection. It accepts success and failure callbacks. ### Method POST ### Endpoint /webrtc/answer ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **successCallback** (function) - Required - Callback function invoked upon successful answer creation. - **failureCallback** (function) - Required - Callback function invoked upon failure to create answer. ### Request Example ```json { "successCallback": "function(answer) { ... }", "failureCallback": "function(error) { ... }" } ``` ### Response #### Success Response (200) - **undefined** - The promise resolves with undefined upon successful execution. #### Response Example ```json { "message": "Answer created successfully, callback invoked." } ``` ``` -------------------------------- ### Get WebRTC Identity Assertion Source: https://www.w3.org/TR/webrtc/-identity Initiates the process to obtain an identity assertion from the configured identity provider. If the connection is closed, it throws an InvalidStateError. Otherwise, it requests an assertion and resolves a promise with the encoded result. ```javascript RTCPeerConnection.prototype.getIdentityAssertion = function() { // Implementation details for getting identity assertion }; ``` -------------------------------- ### RTCIceServer Dictionary Source: https://www.w3.org/TR/webrtc/index Describes STUN and TURN servers for ICE Agent connectivity. ```APIDOC ## RTCIceServer Dictionary ### Description The `RTCIceServer` dictionary is used to describe the STUN and TURN servers that can be used by the ICE Agent to establish a connection with a peer. ```webidl dictionary RTCIceServer { required (DOMString or sequence) urls; DOMString username; DOMString credential; }; ``` ### Members #### urls - **Type**: `DOMString` or `sequence` - **Required**: Yes - **Description**: STUN or TURN URI(s) as defined in [RFC7064] and [RFC7065] or other URI types. #### username - **Type**: `DOMString` - **Required**: No - **Description**: If this `RTCIceServer` object represents a TURN server, then this attribute specifies the username to use with that TURN server. #### credential - **Type**: `DOMString` - **Required**: No - **Description**: If this `RTCIceServer` object represents a TURN server, then this attribute specifies the credential to use with that TURN server. `credential` represents a long-term authentication password, as described in [RFC5389], Section 10.2. ### Request Example ```json [ {"urls": "stun:stun1.example.net"}, {"urls": ["turns:turn.example.org", "turn:turn.example.net"], "username": "user", "credential": "myPassword" } ] ``` ``` -------------------------------- ### RTCRtpCapabilities Dictionary Source: https://www.w3.org/TR/webrtc/index Details about the RTCRtpCapabilities dictionary, listing supported RTP codecs and header extensions. ```APIDOC ## RTCRtpCapabilities Dictionary ```WebIDL WebIDLdictionary RTCRtpCapabilities { required sequence codecs; required sequence headerExtensions; }; ``` ### Description Lists supported media codecs and RTP header extensions. ### Members - **codecs** (sequence<`RTCRtpCodec`>) - Required - Supported media codecs as well as entries for RTX, RED and FEC mechanisms. Only combinations that would utilize distinct payload types in a generated SDP offer are to be provided. - **headerExtensions** (sequence<`RTCRtpHeaderExtensionCapability`>) - Required - Supported RTP header extensions. ``` -------------------------------- ### Retrieve WebRTC Statistics Source: https://context7.com/context7/w3_tr_webrtc/llms.txt Fetches and processes various statistics for WebRTC connections, including inbound/outbound RTP data, candidate pair states, and ICE candidate information. It also demonstrates how to get stats for specific senders and monitor them periodically. Dependencies include a valid RTCPeerConnection object named 'pc'. ```javascript async function getStats() { try { const stats = await pc.getStats(); stats.forEach(report => { console.log('Report type:', report.type, report); switch (report.type) { case 'inbound-rtp': console.log('Inbound RTP:', { packetsReceived: report.packetsReceived, packetsLost: report.packetsLost, jitter: report.jitter, bytesReceived: report.bytesReceived, framesDecoded: report.framesDecoded, keyFramesDecoded: report.keyFramesDecoded }); break; case 'outbound-rtp': console.log('Outbound RTP:', { packetsSent: report.packetsSent, bytesSent: report.bytesSent, framesEncoded: report.framesEncoded, retransmittedPacketsSent: report.retransmittedPacketsSent, qualityLimitationReason: report.qualityLimitationReason }); break; case 'candidate-pair': if (report.state === 'succeeded') { console.log('Active candidate pair:', { localCandidate: report.localCandidateId, remoteCandidate: report.remoteCandidateId, currentRoundTripTime: report.currentRoundTripTime, availableOutgoingBitrate: report.availableOutgoingBitrate, bytesReceived: report.bytesReceived, bytesSent: report.bytesSent }); } break; case 'local-candidate': case 'remote-candidate': console.log('ICE Candidate:', { candidateType: report.candidateType, ip: report.address, port: report.port, protocol: report.protocol }); break; } }); } catch (error) { console.error('Error getting stats:', error); } } // Get stats for specific sender const sender = pc.getSenders()[0]; const senderStats = await sender.getStats(); senderStats.forEach(report => { console.log('Sender stat:', report); }); // Monitor stats periodically setInterval(getStats, 5000); ``` -------------------------------- ### RTCLocalSessionDescriptionInit Dictionary Definition (WebIDL) Source: https://www.w3.org/TR/webrtc/index Defines the structure for local session description initialization. It includes 'type' and 'sdp' members. The 'type' can be inferred if not provided. The 'sdp' member is unused for 'rollback' types. ```WebIDL WebIDLdictionary RTCLocalSessionDescriptionInit { RTCSdpType type; DOMString sdp = ""; }; ``` -------------------------------- ### RTCIceCandidateInit Dictionary WebIDL Source: https://www.w3.org/TR/webrtc/index Defines the structure for initializing an RTCIceCandidate. It includes optional attributes for the candidate string, SDP mid, SDP line index, and username fragment. ```WebIDL dictionary RTCIceCandidateInit { DOMString candidate = ""; DOMString? sdpMid = null; unsigned short? sdpMLineIndex = null; DOMString? usernameFragment = null; }; ``` -------------------------------- ### Registering an IdP Proxy Source: https://www.w3.org/TR/webrtc/-identity Details the process for an IdP to register itself with the user agent by implementing and calling the `register()` method. ```APIDOC ## Registering an IdP Proxy ### Description An IdP proxy implements the `RTCIdentityProvider` methods. After the IdP script is executed, it MUST call the `register()` function on the `RTCIdentityProviderRegistrar` instance. Failure to register prevents the user agent from using the IdP proxy. ### Interface: `RTCIdentityProviderRegistrar` ``` [Exposed=RTCIdentityProviderGlobalScope] interface RTCIdentityProviderRegistrar { void register(RTCIdentityProvider idp); }; ``` #### Method `register` - **Description**: Invoked by the IdP during script execution to register its `RTCIdentityProvider` methods with the user agent. - **Parameter**: `idp` (`RTCIdentityProvider`) - The object implementing the identity provider methods. ``` -------------------------------- ### RTCPeerConnection.setRemoteDescription Source: https://www.w3.org/TR/webrtc/index Applies the supplied RTCSessionDescriptionInit as the remote offer or answer, changing the local media state. It handles rollback scenarios for invalid offers. ```APIDOC ## POST /rtc/peerconnection/setRemoteDescription ### Description Sets the remote description of the RTCPeerConnection. This is used to apply the offer or answer received from the remote peer. ### Method POST ### Endpoint /rtc/peerconnection/setRemoteDescription ### Parameters #### Request Body - **description** (RTCSessionDescriptionInit) - Required - The remote session description initialization object, containing 'type' and 'sdp'. - **type** (string) - Required - The type of the description ('offer', 'pranswer', or 'answer'). - **sdp** (string) - Optional - The Session Description Protocol string. ### Request Example ```json { "description": { "type": "answer", "sdp": "v=0\r\n..." } } ``` ### Response #### Success Response (200) - **result** (any) - A promise that resolves when the description is successfully set. #### Response Example ```json { "result": null } ``` ### Notes - If the provided offer is invalid for the current signaling state, the connection will attempt to rollback its local description. ``` -------------------------------- ### RTCDataChannelInit Dictionary - WebIDL Source: https://www.w3.org/TR/webrtc/index The RTCDataChannelInit dictionary provides optional parameters for configuring a new RTCDataChannel. These include settings for ordered delivery, packet lifetime, retransmissions, protocol negotiation, and channel ID. ```WebIDL dictionary RTCDataChannelInit { boolean ordered = true; [EnforceRange] unsigned short maxPacketLifeTime; [EnforceRange] unsigned short maxRetransmits; USVString protocol = ""; boolean negotiated = false; [EnforceRange] unsigned short id; }; ``` -------------------------------- ### RTCPeerConnection.restartIce Source: https://www.w3.org/TR/webrtc/index Tells the RTCPeerConnection that ICE should be restarted. Subsequent calls to createOffer will create descriptions that will restart ICE. ```APIDOC ## RTCPeerConnection.restartIce ### Description Restarts the ICE (Interactive Connectivity Establishment) process for the `RTCPeerConnection`. ### Method `RTCPeerConnection.restartIce()` ### Parameters None ### Request Example ```javascript peerConnection.restartIce(); ``` ### Response #### Success Response (200) - **undefined** (void) - Indicates the operation completed successfully. #### Response Example ```json // No explicit response body for success, operation implies success. ``` ### Error Handling This method does not explicitly define error responses in the provided text, but it initiates a process that may encounter ICE-related errors. ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.