网站的分辨率,wordpress 会话,google云平台 wordpress,片头网站WebRTC 架构概览#xff08;整体框架篇#xff09; 本文是 WebRTC 系列专栏的第二篇#xff0c;将深入剖析 WebRTC 的整体架构#xff0c;包括浏览器中的实现架构、API 体系、信令流程以及底层媒体引擎 libwebrtc 的结构。 目录
WebRTC 在浏览器中的架构API 体系详解WebRT…WebRTC 架构概览整体框架篇本文是 WebRTC 系列专栏的第二篇将深入剖析 WebRTC 的整体架构包括浏览器中的实现架构、API 体系、信令流程以及底层媒体引擎 libwebrtc 的结构。目录WebRTC 在浏览器中的架构API 体系详解WebRTC 信令流程概览媒体引擎结构libwebrtc 概览总结1. WebRTC 在浏览器中的架构1.1 整体架构图┌─────────────────────────────────────────────────────────────────────────┐ │ Web Application │ │ (JavaScript / HTML) │ └─────────────────────────────────────────────────────────────────────────┘ │ ▼ ┌─────────────────────────────────────────────────────────────────────────┐ │ WebRTC JavaScript API │ │ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────────────┐ │ │ │ getUserMedia() │ │RTCPeerConnection│ │ RTCDataChannel │ │ │ │ getDisplayMedia │ │ │ │ │ │ │ └─────────────────┘ └─────────────────┘ └─────────────────────────┘ │ └─────────────────────────────────────────────────────────────────────────┘ │ ▼ ┌─────────────────────────────────────────────────────────────────────────┐ │ WebRTC Native C API │ │ (libwebrtc / webrtc.org) │ ├─────────────────────────────────────────────────────────────────────────┤ │ ┌───────────────────────────────────────────────────────────────────┐ │ │ │ Session Management │ │ │ │ (Offe/Answer, ICE, SRTP Key Exchange) │ │ │ └───────────────────────────────────────────────────────────────────┘ │ │ ┌─────────────────────────┐ ┌─────────────────────────────┐ │ │ │ Voice Engine │ │ Video Engine │ │ │ │ ┌─────────────────┐ │ │ ┌─────────────────────┐ │ │ │ │ │ Audio Codecs │ │ │ │ Video Codecs │ │ │ │ │ │ (Opus, G.711) │ │ │ │ (VP8, VP9, H.264) │ │ │ │ │ ├─────────────────┤ │ │ ├─────────────────────┤ │ │ │ │ │ Echo Cancel │ │ │ │ Video Processing │ │ │ │ │ │ Noise Suppress │ │ │ │ (Scaling, FEC) │ │ │ │ │ ├─────────────────┤ │ │ ├─────────────────────┤ │ │ │ │ │ Jitter Buffer │ │ │ │ Jitter Buffer │ │ │ │ │ └─────────────────┘ │ │ └─────────────────────┘ │ │ │ └─────────────────────────┘ └─────────────────────────────┘ │ │ ┌───────────────────────────────────────────────────────────────────┐ │ │ │ Transport Layer │ │ │ │ (ICE / STUN / TURN / DTLS / SRTP / SCTP) │ │ │ └───────────────────────────────────────────────────────────────────┘ │ └─────────────────────────────────────────────────────────────────────────┘ │ ▼ ┌─────────────────────────────────────────────────────────────────────────┐ │ Operating System │ │ (Audio/Video Capture, Network Socket, etc.) │ └─────────────────────────────────────────────────────────────────────────┘1.2 架构层次说明第一层Web 应用层开发者编写的 JavaScript 代码通过 WebRTC API 实现实时通信功能。// 应用层代码示例constpcnewRTCPeerConnection(config);conststreamawaitnavigator.mediaDevices.getUserMedia({video:true});stream.getTracks().forEach(trackpc.addTrack(track,stream));第二层WebRTC JavaScript API浏览器暴露给 JavaScript 的标准 API由 W3C 定义API职责navigator.mediaDevices.getUserMedia()获取摄像头/麦克风navigator.mediaDevices.getDisplayMedia()获取屏幕共享RTCPeerConnection建立和管理 P2P 连接RTCDataChannel传输任意数据MediaStream/MediaStreamTrack管理媒体流和轨道第三层WebRTC Native C API这是 libwebrtc 提供的 C 接口层主要包含PeerConnectionFactory创建 PeerConnection 的工厂类PeerConnection核心连接管理类MediaStreamInterface媒体流接口DataChannelInterface数据通道接口第四层核心引擎层包含三个主要模块Session Management会话管理SDP 协商ICE 候选收集与交换DTLS 密钥交换Voice Engine音频引擎音频编解码Opus、G.711回声消除AEC噪声抑制NS自动增益控制AGC抖动缓冲Jitter BufferVideo Engine视频引擎视频编解码VP8、VP9、H.264、AV1视频处理缩放、裁剪前向纠错FEC抖动缓冲第五层传输层负责网络传输的协议栈┌─────────────────────────────────────────┐ │ Application │ ├─────────────────────────────────────────┤ │ SRTP (媒体) │ SCTP (数据) │ ├─────────────────────────────────────────┤ │ DTLS (加密) │ ├─────────────────────────────────────────┤ │ ICE (NAT 穿透) │ ├─────────────────────────────────────────┤ │ STUN / TURN (服务器) │ ├─────────────────────────────────────────┤ │ UDP / TCP │ └─────────────────────────────────────────┘1.3 浏览器实现差异不同浏览器的 WebRTC 实现有所差异浏览器底层实现特点Chromelibwebrtc最完整、更新最快Firefox自研 libwebrtc 部分独立实现兼容性好Safari基于 libwebrtc更新较慢部分功能缺失EdgeChromium 内核与 Chrome 一致2. API 体系详解2.1 getUserMedia / getDisplayMediagetUserMedia - 获取摄像头和麦克风// 基础用法conststreamawaitnavigator.mediaDevices.getUserMedia({video:true,audio:true});// 高级约束conststreamawaitnavigator.mediaDevices.getUserMedia({video:{width:{min:640,ideal:1280,max:1920},height:{min:480,ideal:720,max:1080},frameRate:{ideal:30,max:60},facingMode:user,// user 前置, environment 后置deviceId:{exact:specific-camera-id}},audio:{echoCancellation:true,noiseSuppression:true,autoGainControl:true,sampleRate:48000,channelCount:2}});getDisplayMedia - 屏幕共享constscreenStreamawaitnavigator.mediaDevices.getDisplayMedia({video:{cursor:always,// 是否显示鼠标displaySurface:monitor// monitor | window | browser},audio:true// 系统音频部分浏览器支持});枚举设备constdevicesawaitnavigator.mediaDevices.enumerateDevices();devices.forEach(device{console.log(${device.kind}:${device.label}(${device.deviceId}));});// 输出示例// videoinput: FaceTime HD Camera (abc123)// audioinput: MacBook Pro Microphone (def456)// audiooutput: MacBook Pro Speakers (ghi789)2.2 RTCPeerConnectionRTCPeerConnection 是 WebRTC 的核心 API负责建立和管理 P2P 连接。构造函数与配置constconfiguration{// ICE 服务器配置iceServers:[{urls:stun:stun.l.google.com:19302},{urls:turn:turn.example.com:3478,username:user,credential:password}],// ICE 传输策略iceTransportPolicy:all,// all | relay// Bundle 策略bundlePolicy:max-bundle,// balanced | max-compat | max-bundle// RTCP 复用策略rtcpMuxPolicy:require,// require | negotiate// 证书certificates:[certificate]};constpcnewRTCPeerConnection(configuration);核心方法// 信令相关 // 创建 Offerconstofferawaitpc.createOffer({offerToReceiveAudio:true,offerToReceiveVideo:true,iceRestart:false});// 创建 Answerconstanswerawaitpc.createAnswer();// 设置本地描述awaitpc.setLocalDescription(offer);// 设置远端描述awaitpc.setRemoteDescription(remoteAnswer);// 添加 ICE 候选awaitpc.addIceCandidate(candidate);// 媒体相关 // 添加轨道constsenderpc.addTrack(track,stream);// 移除轨道pc.removeTrack(sender);// 获取发送器constsenderspc.getSenders();// 获取接收器constreceiverspc.getReceivers();// 获取收发器consttransceiverspc.getTransceivers();// 添加收发器consttransceiverpc.addTransceiver(video,{direction:sendrecv// sendrecv | sendonly | recvonly | inactive});// 数据通道 // 创建数据通道constdataChannelpc.createDataChannel(myChannel,{ordered:true,maxRetransmits:3});// 连接管理 // 关闭连接pc.close();// 获取统计信息conststatsawaitpc.getStats();核心事件// ICE 候选事件pc.onicecandidate(event){if(event.candidate){// 发送候选到远端sendToRemote({type:candidate,candidate:event.candidate});}};// ICE 连接状态变化pc.oniceconnectionstatechange(){console.log(ICE state:,pc.iceConnectionState);// new | checking | connected | completed |// failed | disconnected | closed};// 连接状态变化pc.onconnectionstatechange(){console.log(Connection state:,pc.connectionState);// new | connecting | connected | disconnected | failed | closed};// 信令状态变化pc.onsignalingstatechange(){console.log(Signaling state:,pc.signalingState);// stable | have-local-offer | have-remote-offer |// have-local-pranswer | have-remote-pranswer | closed};// 收到远端轨道pc.ontrack(event){const[remoteStream]event.streams;remoteVideo.srcObjectremoteStream;};// 收到数据通道pc.ondatachannel(event){constdataChannelevent.channel;dataChannel.onmessage(e)console.log(e.data);};// 需要重新协商pc.onnegotiationneededasync(){constofferawaitpc.createOffer();awaitpc.setLocalDescription(offer);sendToRemote({type:offer,sdp:offer.sdp});};2.3 RTCDataChannelDataChannel 提供了在 P2P 连接上传输任意数据的能力。// 创建数据通道发起方constdataChannelpc.createDataChannel(chat,{ordered:true,// 保证顺序maxRetransmits:3,// 最大重传次数// maxPacketLifeTime: 3000, // 或者设置最大生存时间msprotocol:json,// 子协议negotiated:false,// 是否手动协商id:0// 通道 IDnegotiated 为 true 时使用});// 事件处理dataChannel.onopen(){console.log(Data channel opened);dataChannel.send(Hello!);};dataChannel.onclose(){console.log(Data channel closed);};dataChannel.onmessage(event){console.log(Received:,event.data);};dataChannel.onerror(error){console.error(Data channel error:,error);};// 发送数据dataChannel.send(text message);dataChannel.send(newArrayBuffer(1024));dataChannel.send(newBlob([binary data]));// 检查缓冲区if(dataChannel.bufferedAmountdataChannel.bufferedAmountLowThreshold){dataChannel.send(moreData);}// 接收方处理pc.ondatachannel(event){constreceiveChannelevent.channel;receiveChannel.onmessage(e){console.log(Received:,e.data);};};3. WebRTC 信令流程概览3.1 什么是信令信令Signaling是 WebRTC 建立连接前的协商过程用于交换会话描述SDP媒体能力、编解码器、传输参数网络候选ICE Candidates可用的网络路径⚠️ WebRTC 标准不定义信令协议开发者需要自行实现。3.2 常见信令方案方案优点缺点WebSocket实时、双向需要维护长连接HTTP 轮询简单延迟高、效率低Socket.IO易用、自动重连额外依赖Firebase无需服务器依赖第三方MQTT适合 IoT复杂度较高3.3 完整信令流程┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │ Caller │ │ Signaling │ │ Callee │ │ (发起方) │ │ Server │ │ (接收方) │ └──────┬───────┘ └──────┬───────┘ └──────┬───────┘ │ │ │ │ 1. 获取本地媒体流 │ │ │ getUserMedia() │ │ │ │ │ │ 2. 创建 PeerConnection │ │ │ new RTCPeerConnection │ │ │ │ │ │ 3. 添加本地轨道 │ │ │ addTrack() │ │ │ │ │ │ 4. 创建 Offer │ │ │ createOffer() │ │ │ │ │ │ 5. 设置本地描述 │ │ │ setLocalDescription() │ │ │ │ │ │ 6. 发送 Offer ─────────│ │ │ │ 7. 转发 Offer ─────────│ │ │ │ │ │ 8. 获取本地媒体流 │ │ getUserMedia() │ │ │ │ │ 9. 创建 PeerConnection │ │ new RTCPeerConnection │ │ │ │ │ 10. 设置远端描述 │ │ setRemoteDescription() │ │ │ │ │ 11. 添加本地轨道 │ │ addTrack() │ │ │ │ │ 12. 创建 Answer │ │ createAnswer() │ │ │ │ │ 13. 设置本地描述 │ │ setLocalDescription() │ │ │ │ │───────── 14. 发送 Answer │───────── 15. 转发 Answer│ │ │ │ │ │ 16. 设置远端描述 │ │ │ setRemoteDescription() │ │ │ │ │ │ ═══════════ 17. ICE 候选交换 (双向) ═══════════ │ │ onicecandidate ──────│─────── onicecandidate │ │────── addIceCandidate │ addIceCandidate ──────│ │ │ │ │ ═══════════════ 18. P2P 连接建立 ═══════════════│ │═══════════════════════════════════════════════│ │ │ │ │ ═══════════════ 19. 媒体流传输 ═════════════════│ │═══════════════════════════════════════════════│ │ │ │3.4 SDP 详解SDPSession Description Protocol描述了会话的媒体能力。SDP 示例v0 o- 4611731400430051336 2 IN IP4 127.0.0.1 s- t0 0 agroup:BUNDLE 0 1 aextmap-allow-mixed amsid-semantic: WMS stream_id maudio 9 UDP/TLS/RTP/SAVPF 111 103 104 9 0 8 106 105 13 110 112 113 126 cIN IP4 0.0.0.0 artcp:9 IN IP4 0.0.0.0 aice-ufrag:abcd aice-pwd:efghijklmnopqrstuvwxyz aice-options:trickle afingerprint:sha-256 AA:BB:CC:DD:... asetup:actpass amid:0 aextmap:1 urn:ietf:params:rtp-hdrext:ssrc-audio-level asendrecv artcp-mux artpmap:111 opus/48000/2 afmtp:111 minptime10;useinbandfec1 ... mvideo 9 UDP/TLS/RTP/SAVPF 96 97 98 99 100 101 102 cIN IP4 0.0.0.0 artcp:9 IN IP4 0.0.0.0 aice-ufrag:abcd aice-pwd:efghijklmnopqrstuvwxyz afingerprint:sha-256 AA:BB:CC:DD:... asetup:actpass amid:1 asendrecv artcp-mux artcp-rsize artpmap:96 VP8/90000 artpmap:97 rtx/90000 afmtp:97 apt96 artpmap:98 VP9/90000 ...SDP 关键字段字段含义v协议版本o会话发起者信息s会话名称t会话时间m媒体描述audio/videoartpmap:RTP 负载类型映射afmtp:格式参数aice-ufrag:ICE 用户名片段aice-pwd:ICE 密码afingerprint:DTLS 证书指纹acandidate:ICE 候选3.5 ICE 候选类型// ICE 候选示例{candidate:candidate:842163049 1 udp 1677729535 192.168.1.100 54321 typ srflx raddr 10.0.0.1 rport 12345 generation 0,sdpMid:0,sdpMLineIndex:0}类型说明优先级host本地 IP 地址最高srflxServer ReflexiveSTUN 获取的公网地址中prflxPeer Reflexive对端发现的地址中relayTURN 中继地址最低4. 媒体引擎结构libwebrtc 概览4.1 libwebrtc 简介libwebrtc是 Google 开源的 WebRTC 实现也是 Chrome、Firefox部分、Safari 等浏览器的底层实现。代码仓库https://webrtc.googlesource.com/src/许可证BSD 3-Clause语言C核心 各平台绑定4.2 目录结构src/ ├── api/ # 公共 API 接口 │ ├── audio_codecs/ # 音频编解码器接口 │ ├── video_codecs/ # 视频编解码器接口 │ ├── peer_connection_interface.h │ └── ... ├── audio/ # 音频处理 │ ├── audio_send_stream.cc │ ├── audio_receive_stream.cc │ └── ... ├── video/ # 视频处理 │ ├── video_send_stream.cc │ ├── video_receive_stream.cc │ └── ... ├── call/ # 呼叫管理 ├── media/ # 媒体引擎 │ ├── engine/ │ │ ├── webrtc_voice_engine.cc │ │ └── webrtc_video_engine.cc │ └── ... ├── modules/ # 核心模块 │ ├── audio_coding/ # 音频编解码 │ ├── audio_processing/ # 音频处理AEC、NS、AGC │ ├── video_coding/ # 视频编解码 │ ├── rtp_rtcp/ # RTP/RTCP 协议 │ ├── congestion_controller/ # 拥塞控制 │ └── ... ├── pc/ # PeerConnection 实现 │ ├── peer_connection.cc │ ├── sdp_offer_answer.cc │ └── ... ├── p2p/ # P2P 连接 │ ├── base/ │ │ ├── stun.cc │ │ ├── turn_port.cc │ │ └── ... │ └── client/ │ └── basic_port_allocator.cc ├── rtc_base/ # 基础库 │ ├── thread.cc │ ├── async_socket.cc │ └── ... └── sdk/ # 平台 SDK ├── android/ ├── objc/ # iOS/macOS └── ...4.3 核心模块详解4.3.1 音频处理模块 (Audio Processing Module, APM)┌─────────────────────────────────────────────────────────────┐ │ Audio Processing Module │ ├─────────────────────────────────────────────────────────────┤ │ ┌─────────────┐ ┌─────────────┐ ┌─────────────────────┐ │ │ │ AEC │ │ NS │ │ AGC │ │ │ │ (回声消除) │ │ (噪声抑制) │ │ (自动增益控制) │ │ │ └─────────────┘ └─────────────┘ └─────────────────────┘ │ │ ┌─────────────┐ ┌─────────────┐ ┌─────────────────────┐ │ │ │ VAD │ │ Beamform │ │ Level Estimator │ │ │ │ (语音检测) │ │ (波束成形) │ │ (电平估计) │ │ │ └─────────────┘ └─────────────┘ └─────────────────────┘ │ └─────────────────────────────────────────────────────────────┘关键组件组件功能文件位置AEC3回声消除第三代modules/audio_processing/aec3/NS噪声抑制modules/audio_processing/ns/AGC2自动增益控制modules/audio_processing/agc2/VAD语音活动检测modules/audio_processing/vad/4.3.2 视频编解码模块┌─────────────────────────────────────────────────────────────┐ │ Video Coding Module │ ├─────────────────────────────────────────────────────────────┤ │ ┌─────────────────────────────────────────────────────┐ │ │ │ Encoders │ │ │ │ ┌─────────┐ ┌─────────┐ ┌─────────┐ ┌─────────┐ │ │ │ │ │ VP8 │ │ VP9 │ │ H.264 │ │ AV1 │ │ │ │ │ └─────────┘ └─────────┘ └─────────┘ └─────────┘ │ │ │ └─────────────────────────────────────────────────────┘ │ │ ┌─────────────────────────────────────────────────────┐ │ │ │ Decoders │ │ │ │ ┌─────────┐ ┌─────────┐ ┌─────────┐ ┌─────────┐ │ │ │ │ │ VP8 │ │ VP9 │ │ H.264 │ │ AV1 │ │ │ │ │ └─────────┘ └─────────┘ └─────────┘ └─────────┘ │ │ │ └─────────────────────────────────────────────────────┘ │ │ ┌─────────────────────────────────────────────────────┐ │ │ │ Video Processing │ │ │ │ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │ │ │ │ │ Scaling │ │ FEC │ │ Jitter Buf │ │ │ │ │ └─────────────┘ └─────────────┘ └─────────────┘ │ │ │ └─────────────────────────────────────────────────────┘ │ └─────────────────────────────────────────────────────────────┘4.3.3 RTP/RTCP 模块┌─────────────────────────────────────────────────────────────┐ │ RTP/RTCP Module │ ├─────────────────────────────────────────────────────────────┤ │ ┌─────────────────────────────────────────────────────┐ │ │ │ RTP Sender │ │ │ │ • 打包媒体数据 │ │ │ │ • 添加 RTP 头部 │ │ │ │ • 处理重传请求 │ │ │ └─────────────────────────────────────────────────────┘ │ │ ┌─────────────────────────────────────────────────────┐ │ │ │ RTP Receiver │ │ │ │ • 解析 RTP 包 │ │ │ │ • 处理丢包 │ │ │ │ • 抖动缓冲 │ │ │ └─────────────────────────────────────────────────────┘ │ │ ┌─────────────────────────────────────────────────────┐ │ │ │ RTCP Handler │ │ │ │ • SR/RR (发送/接收报告) │ │ │ │ • NACK (丢包重传请求) │ │ │ │ • PLI/FIR (关键帧请求) │ │ │ │ • REMB (带宽估计) │ │ │ └─────────────────────────────────────────────────────┘ │ └─────────────────────────────────────────────────────────────┘4.3.4 拥塞控制模块WebRTC 使用GCCGoogle Congestion Control算法进行带宽估计和拥塞控制。┌─────────────────────────────────────────────────────────────┐ │ Congestion Controller │ ├─────────────────────────────────────────────────────────────┤ │ ┌─────────────────────────────────────────────────────┐ │ │ │ Send-side BWE (发送端带宽估计) │ │ │ │ • 基于延迟梯度 │ │ │ │ • Transport-wide CC │ │ │ └─────────────────────────────────────────────────────┘ │ │ ┌─────────────────────────────────────────────────────┐ │ │ │ Receive-side BWE (接收端带宽估计) │ │ │ │ • REMB 反馈 │ │ │ │ • 基于丢包率 │ │ │ └─────────────────────────────────────────────────────┘ │ │ ┌─────────────────────────────────────────────────────┐ │ │ │ Pacer (发送节奏控制) │ │ │ │ • 平滑发送 │ │ │ │ • 避免突发 │ │ │ └─────────────────────────────────────────────────────┘ │ └─────────────────────────────────────────────────────────────┘4.4 线程模型libwebrtc 使用多线程架构┌─────────────────────────────────────────────────────────────┐ │ Thread Architecture │ ├─────────────────────────────────────────────────────────────┤ │ │ │ ┌─────────────────┐ │ │ │ Signaling │ 信令线程处理 API 调用、SDP 协商 │ │ │ Thread │ │ │ └─────────────────┘ │ │ │ │ │ ▼ │ │ ┌─────────────────┐ │ │ │ Worker │ 工作线程媒体处理、编解码 │ │ │ Thread │ │ │ └─────────────────┘ │ │ │ │ │ ▼ │ │ ┌─────────────────┐ │ │ │ Network │ 网络线程网络 I/O、ICE 处理 │ │ │ Thread │ │ │ └─────────────────┘ │ │ │ │ ┌─────────────────┐ ┌─────────────────┐ │ │ │ Audio │ │ Video │ │ │ │ Device Thread │ │ Capture Thread │ 设备线程 │ │ └─────────────────┘ └─────────────────┘ │ │ │ └─────────────────────────────────────────────────────────────┘5. 总结架构要点回顾层次内容应用层JavaScript 代码调用 WebRTC APIAPI 层getUserMedia、RTCPeerConnection、RTCDataChannel引擎层音频引擎、视频引擎、会话管理传输层ICE、DTLS、SRTP、SCTPAPI 体系总结API职责getUserMedia()获取摄像头/麦克风getDisplayMedia()屏幕共享RTCPeerConnectionP2P 连接管理RTCDataChannel任意数据传输信令流程要点Offer/Answer 模型发起方创建 Offer接收方回复 AnswerSDP 交换描述媒体能力和传输参数ICE 候选交换发现可用的网络路径信令协议自定义WebRTC 不规定信令协议下一篇预告在下一篇文章中我们将动手实践从零开始写一个最简单的 WebRTC Demo包括获取摄像头与麦克风建立 RTCPeerConnection实现 peer-to-peer 音视频通话参考资料WebRTC 1.0: Real-Time Communication Between Browsers - W3Clibwebrtc Source CodeWebRTC for the CuriousHigh Performance Browser Networking - WebRTCRFC 8825 - Overview: Real-Time Protocols for Browser-Based Applications