WebRTC 技术文章大纲

WebRTC 概述
  • 定义与背景:WebRTC 的基本概念、发展历程及核心目标。
  • 技术特点:实时性、P2P 通信、开源与跨平台特性。
  • 应用场景:视频会议、在线教育、直播、IoT 设备通信等。
WebRTC 核心组件
  • 媒体流(MediaStream):音视频采集、设备权限管理及流处理。
  • 信令服务(Signaling):协商通信参数(SDP 交换、ICE 候选交换)。
  • 网络传输(RTCPeerConnection):建立 P2P 连接、NAT 穿透(STUN/TURN)。
  • 数据传输(RTCDataChannel):低延迟的二进制或文本数据传输。
实现流程
  • 设备检测与权限获取:调用 getUserMedia 获取音视频流。
  • 信令交换:通过 WebSocket 或其他协议交换 SDP 和 ICE 候选。
  • 建立连接:创建 RTCPeerConnection 实例,处理 ICE 状态与媒体流绑定。
  • 数据传输:通过 RTCDataChannel 实现非音视频通信(如文件传输)。
关键技术细节
  • NAT 穿透:STUN/TURN 服务器的作用与配置。
  • 编解码支持:默认支持的编解码器(如 VP8、Opus)及兼容性问题。
  • 安全性:DTLS-SRTP 加密、身份验证与安全最佳实践。
常见问题与优化
  • 延迟优化:调整 QoS 参数、使用自适应码率。
  • 兼容性处理:不同浏览器(Chrome、Firefox、Safari)的差异与垫片方案。
  • 调试工具:WebRTC 内置统计(getStats)、Chrome://webrtc-internals)。
进阶应用
  • 与 AI 结合:实时音视频分析(如人脸识别)。
  • 大规模部署:SFU/MCU 架构选择与性能权衡。
  • 移动端适配:iOS/Android 的 WebRTC 集成方案。
示例代码发送端和接收端
public class WebRtcSender {

    private static final String TAG = "WebRtcSender";

    private final AtomicBoolean inited = new AtomicBoolean(false);
    private final AtomicBoolean dcOpen = new AtomicBoolean(false);

    private PeerConnectionFactory factory;
    private PeerConnection peerConnection;
    private DataChannel dataChannel;
    private WebRtcSignalListener signalListener;
    private Context appContext;

    public void init(Context context) {
        if (inited.get()) {
            Log.d(TAG, "init: already inited");
            return;
        }
        appContext = context.getApplicationContext();
        PeerConnectionFactory.initialize(
                PeerConnectionFactory.InitializationOptions.builder(appContext)
                        .setEnableInternalTracer(true)
                        .createInitializationOptions()
        );
        PeerConnectionFactory.Options options = new PeerConnectionFactory.Options();
        options.networkIgnoreMask = 0;
        options.disableNetworkMonitor = true; 
        factory = PeerConnectionFactory.builder()
                .setOptions(options)
                .createPeerConnectionFactory();
        inited.set(true);
        Log.i(TAG, "STEP 1 DONE: PeerConnectionFactory initialized");
    }

    private PeerConnection.RTCConfiguration defaultRtcConfigOffline() {
        List<PeerConnection.IceServer> servers = new ArrayList<>();
        PeerConnection.RTCConfiguration cfg = new PeerConnection.RTCConfiguration(servers);
        cfg.sdpSemantics = PeerConnection.SdpSemantics.UNIFIED_PLAN;
        cfg.iceTransportsType = PeerConnection.IceTransportsType.ALL;
        cfg.disableIPv6OnWifi = true;
        return cfg;
    }

    private void logNetworkInfo() {
        try {
            List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
            Log.i(TAG, "--- Network Interface Debug Info ---");
            for (NetworkInterface intf : interfaces) {
                if (intf.isUp()) {
                    List<InetAddress> addrs = Collections.list(intf.getInetAddresses());
                    for (InetAddress addr : addrs) {
                        Log.i(TAG, "Interface: " + intf.getName() + " (" + intf.getDisplayName() + ")" 
                                + " IP: " + addr.getHostAddress() 
                                + " Loopback=" + addr.isLoopbackAddress() 
                                + " LinkLocal=" + addr.isLinkLocalAddress());
                    }
                }
            }
            Log.i(TAG, "------------------------------------");
        } catch (Exception e) {
            Log.e(TAG, "Failed to list network interfaces", e);
        }
    }

    public void setSignalListener(WebRtcSignalListener listener) {
        this.signalListener = listener;
    }

    public void startAsOfferer(boolean offlineMode) {
        ensureInited();
        logNetworkInfo();
        if (peerConnection != null) {
            Log.w(TAG, "startAsOfferer: peerConnection already exists");
            return;
        }

        PeerConnection.RTCConfiguration rtcConfig = offlineMode ?
                defaultRtcConfigOffline() : defaultRtcConfig();

        peerConnection = factory.createPeerConnection(rtcConfig, new PcObserver());
        if (peerConnection == null) {
            Log.e(TAG, "startAsOfferer: createPeerConnection failed");
            return;
        }

        DataChannel.Init init = new DataChannel.Init();
        init.ordered = true;
        init.maxRetransmits = 0;
        dataChannel = peerConnection.createDataChannel("h264", init);
        if (dataChannel != null) {
            dataChannel.registerObserver(new DcObserver());
            Log.i(TAG, "STEP 3 DONE: DataChannel created");
        } else {
            Log.e(TAG, "startAsOfferer: DataChannel create failed");
        }

        MediaConstraints sdpConstraints = new MediaConstraints();
        sdpConstraints.mandatory.add(new MediaConstraints.KeyValuePair("OfferToReceiveAudio", "false"));
        sdpConstraints.mandatory.add(new MediaConstraints.KeyValuePair("OfferToReceiveVideo", "false"));
        peerConnection.createOffer(new SimpleSdpObserver("createOffer") {
            @Override
            public void onCreateSuccess(SessionDescription sessionDescription) {
                peerConnection.setLocalDescription(new SimpleSdpObserver("setLocalDescription"), sessionDescription);
                if (signalListener != null) {
                    signalListener.onLocalDescription(sessionDescription.type.canonicalForm(), sessionDescription.description);
                }
            }
        }, sdpConstraints);
    }

    public void startAsOfferer() {
        startAsOfferer(true);
    }

    public void setRemoteAnswer(String sdp) {
        ensureInited();
        if (peerConnection == null) {
            Log.e(TAG, "setRemoteAnswer: peerConnection == null");
            return;
        }
        if (sdp == null || sdp.isEmpty()) {
            Log.e(TAG, "setRemoteAnswer: sdp is null or empty!");
            return;
        }
        Log.i(TAG, "setRemoteAnswer: SDP length=" + sdp.length() + ", content:\n" + sdp);
        SessionDescription remote = new SessionDescription(SessionDescription.Type.ANSWER, sdp);
        peerConnection.setRemoteDescription(new SimpleSdpObserver("setRemoteDescription"), remote);
        Log.i(TAG, "STEP 5 DONE: Remote SDP(answer) applied, connection negotiating");
        Log.i(TAG, "SIGNAL got remote SDP (answer), setRemoteDescription done");
    }

    public void addRemoteIceCandidate(String sdpMid, int sdpMLineIndex, String candidateSdp) {
        ensureInited();
        if (peerConnection == null) {
            Log.e(TAG, "addRemoteIceCandidate: peerConnection == null");
            return;
        }
        IceCandidate candidate = new IceCandidate(sdpMid, sdpMLineIndex, candidateSdp);
        boolean ok = peerConnection.addIceCandidate(candidate);
       

    public boolean sendEncodedFrame(ByteBuffer encodedData, long ptsUs, int flags) {
        int payloadSize = encodedData.remaining();
        ByteBuffer packet = ByteBuffer.allocate(8 + 4 + payloadSize).order(ByteOrder.BIG_ENDIAN);
        packet.putLong(ptsUs);
        packet.putInt(flags);
        packet.put(encodedData);
        packet.flip();
        DataChannel.Buffer buffer = new DataChannel.Buffer(packet, true);
        boolean ok = dataChannel.send(buffer);
        return ok;
    }

    public void stopAndRelease() {
        Log.i(TAG, "STEP 8: Releasing all WebRTC resources");
        if (dataChannel != null) {
            dataChannel.dispose();
            dataChannel = null;
        }
        if (peerConnection != null) {
            peerConnection.close();
            peerConnection.dispose();
            peerConnection = null;
        }
        if (factory != null) {
            factory.dispose();
            factory = null;
        }
        inited.set(false);
        dcOpen.set(false);
    }

    private void ensureInited() {
        if (!inited.get()) {
            throw new IllegalStateException("WebRtcSender not initialized. Call init(context) first.");
        }
    }

    private PeerConnection.RTCConfiguration defaultRtcConfig() {
        List<PeerConnection.IceServer> servers = new ArrayList<>();
        servers.add(PeerConnection.IceServer.builder("stun:stun.l.google.com:19302").createIceServer());
        PeerConnection.RTCConfiguration cfg = new PeerConnection.RTCConfiguration(servers);
        cfg.sdpSemantics = PeerConnection.SdpSemantics.UNIFIED_PLAN;
        return cfg;
    }

    private class PcObserver implements PeerConnection.Observer {
       
        @Override
        public void onIceConnectionChange(PeerConnection.IceConnectionState newState) {
            Log.d(TAG, "PC onIceConnectionChange: " + newState);
            if (newState == PeerConnection.IceConnectionState.CONNECTED) {
                Log.i(TAG, "SIGNAL connected");
                signalListener.onNotifyConnected(1);
            } else if (newState == PeerConnection.IceConnectionState.DISCONNECTED) {
                signalListener.onNotifyConnected(0);
            }
        }
        
        
        @Override
        public void onIceCandidate(IceCandidate candidate) {
            Log.i(TAG, "SIGNAL send local ICE to remote: " + candidate.sdpMid + "," + candidate.sdpMLineIndex + "\nContent: " + candidate.sdp);
            if (signalListener != null) {
                signalListener.onIceCandidate(candidate.sdpMid, candidate.sdpMLineIndex, candidate.sdp);
            }
        }
        
        //其他方法实现
    }

    private class DcObserver implements DataChannel.Observer {
        
        @Override
        public void onStateChange() {
            DataChannel.State st = dataChannel.state();
            Log.i(TAG, "DC onStateChange: " + st + " (OPEN means ready to send frames)");
            dcOpen.set(st == DataChannel.State.OPEN);
        }
        //其他方法实现
    }

    private static class SimpleSdpObserver implements SdpObserver {
        private final String tag;
        SimpleSdpObserver(String tag) { this.tag = tag; }
        @Override public void onCreateSuccess(SessionDescription sessionDescription) {
            Log.d(TAG, tag + " onCreateSuccess");
        }
        @Override public void onSetSuccess() { Log.d(TAG, tag + " onSetSuccess"); }
        @Override public void onCreateFailure(String s) { Log.e(TAG, tag + " onCreateFailure: " + s); }
        @Override public void onSetFailure(String s) { Log.e(TAG, tag + " onSetFailure: " + s); }
    }
}

======================================
public class WebRtcReceiver {

    private static final String TAG = "WebRtcReceiver";

    private final AtomicBoolean inited = new AtomicBoolean(false);

    private PeerConnectionFactory factory;
    private PeerConnection peerConnection;
    private DataChannel dataChannel;
    private WebRtcSignalListener signalListener;
    private WebRtcFrameListener frameListener;
    private Context appContext;

    public void init(Context context) {
        if (inited.get()) {
            Log.d(TAG, "init: already inited");
            return;
        }
        appContext = context.getApplicationContext();
        PeerConnectionFactory.initialize(
                PeerConnectionFactory.InitializationOptions.builder(appContext)
                        .setEnableInternalTracer(true)
                        .createInitializationOptions()
        );
        PeerConnectionFactory.Options options = new PeerConnectionFactory.Options();
        options.networkIgnoreMask = 0; 
        options.disableNetworkMonitor = true; 
        factory = PeerConnectionFactory.builder()
                .setOptions(options)
                .createPeerConnectionFactory();
        inited.set(true);
        Log.i(TAG, "STEP A1 DONE: PeerConnectionFactory initialized");
    }

    public void setSignalListener(WebRtcSignalListener listener) {
        this.signalListener = listener;
    }

    public void setFrameListener(WebRtcFrameListener listener) {
        this.frameListener = listener;
    }

    private PeerConnection.RTCConfiguration defaultRtcConfigOffline() {
        List<PeerConnection.IceServer> servers = new ArrayList<>();
        // 不添加任何STUN/TURN服务器,仅使用主机候选
        PeerConnection.RTCConfiguration cfg = new PeerConnection.RTCConfiguration(servers);
        cfg.iceTransportsType = PeerConnection.IceTransportsType.ALL;
        cfg.sdpSemantics = PeerConnection.SdpSemantics.UNIFIED_PLAN;
        cfg.disableIPv6OnWifi = true; // 禁用IPv6以避免潜在的P2P网络兼容性问题
        return cfg;
    }

    private void logNetworkInfo() {
        try {
            List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
            Log.i(TAG, "--- Network Interface Debug Info ---");
            for (NetworkInterface intf : interfaces) {
                if (intf.isUp()) {
                    List<InetAddress> addrs = Collections.list(intf.getInetAddresses());
                    for (InetAddress addr : addrs) {
                        Log.i(TAG, "Interface: " + intf.getName() + " (" + intf.getDisplayName() + ")" 
                                + " IP: " + addr.getHostAddress() 
                                + " Loopback=" + addr.isLoopbackAddress() 
                                + " LinkLocal=" + addr.isLinkLocalAddress());
                    }
                }
            }
            Log.i(TAG, "------------------------------------");
        } catch (Exception e) {
            Log.e(TAG, "Failed to list network interfaces", e);
        }
    }

    public void startAsAnswerer(String remoteOfferSdp, boolean offlineMode) {
        ensureInited();
        logNetworkInfo();

        PeerConnection.RTCConfiguration rtcConfig = offlineMode ?
                defaultRtcConfigOffline() : defaultRtcConfig();

        peerConnection = factory.createPeerConnection(rtcConfig, new PcObserver());
        if (peerConnection == null) {
            Log.e(TAG, "startAsAnswerer: createPeerConnection failed");
            return;
        }

        SessionDescription remoteOffer =
                new SessionDescription(SessionDescription.Type.OFFER, remoteOfferSdp);
        peerConnection.setRemoteDescription(new SimpleSdpObserver("setRemoteDescription"), remoteOffer);

        MediaConstraints sdpConstraints = new MediaConstraints();
        sdpConstraints.mandatory.add(new MediaConstraints.KeyValuePair("OfferToReceiveAudio", "false"));
        sdpConstraints.mandatory.add(new MediaConstraints.KeyValuePair("OfferToReceiveVideo", "false"));
        peerConnection.createAnswer(new SimpleSdpObserver("createAnswer") {
            @Override
            public void onCreateSuccess(SessionDescription sessionDescription) {
               
                peerConnection.setLocalDescription(new SimpleSdpObserver("setLocalDescription"), sessionDescription);
                
                if (signalListener != null) {
                    signalListener.onLocalDescription(sessionDescription.type.canonicalForm(), sessionDescription.description);
                }
            }
        }, sdpConstraints);
    }

    public void startAsAnswerer(String remoteOfferSdp) {
        startAsAnswerer(remoteOfferSdp, true);
    }

    public void addRemoteIceCandidate(String sdpMid, int sdpMLineIndex, String candidateSdp) {
        ensureInited();
        if (peerConnection == null) {
            Log.e(TAG, "addRemoteIceCandidate: peerConnection == null");
            return;
        }
        IceCandidate candidate = new IceCandidate(sdpMid, sdpMLineIndex, candidateSdp);
        boolean ok = peerConnection.addIceCandidate(candidate);
    }

    public void stopAndRelease() {
        Log.i(TAG, "STEP A6: Releasing all WebRTC resources");
        if (dataChannel != null) {
            dataChannel.dispose();
            dataChannel = null;
        }
        if (peerConnection != null) {
            peerConnection.close();
            peerConnection.dispose();
            peerConnection = null;
        }
        if (factory != null) {
            factory.dispose();
            factory = null;
        }
        inited.set(false);
        Log.i(TAG, "STEP A6 DONE: Resources released");
    }

    private void ensureInited() {
        if (!inited.get()) {
            throw new IllegalStateException("WebRtcReceiver not initialized. Call init(context) first.");
        }
    }

    private PeerConnection.RTCConfiguration defaultRtcConfig() {
        List<PeerConnection.IceServer> servers = new ArrayList<>();
        servers.add(PeerConnection.IceServer.builder("stun:stun.l.google.com:19302").createIceServer());
        PeerConnection.RTCConfiguration cfg = new PeerConnection.RTCConfiguration(servers);
        cfg.sdpSemantics = PeerConnection.SdpSemantics.UNIFIED_PLAN;
        return cfg;
    }

    private class PcObserver implements PeerConnection.Observer {
        private int localIceCount = 0;

        @Override
        public void onIceGatheringChange(PeerConnection.IceGatheringState newState) {
            Log.d(TAG, "PC onIceGatheringChange: " + newState);
            if (newState == PeerConnection.IceGatheringState.COMPLETE) {
                if (localIceCount == 0) {
                    Log.e(TAG, "ICE Gathering COMPLETE but NO candidates found! Check network permissions (ACCESS_FINE_LOCATION) and connectivity.");
                } else {
                    Log.i(TAG, "ICE Gathering COMPLETE. Total candidates: " + localIceCount);
                }
            }
        }
        @Override
        public void onIceCandidate(IceCandidate candidate) {
            localIceCount++;
            Log.i(TAG, "SIGNAL send local ICE to remote: " + candidate.sdpMid + "," + candidate.sdpMLineIndex + "\nContent: " + candidate.sdp);
            if (signalListener != null) {
                signalListener.onIceCandidate(candidate.sdpMid, candidate.sdpMLineIndex, candidate.sdp);
            }
        }
        
        @Override
        public void onDataChannel(DataChannel channel) {
            Log.d(TAG, "PC onDataChannel: " + channel.label());
            dataChannel = channel;
            dataChannel.registerObserver(new DcObserver());
        }
        //其他方法实现
    }

    private class DcObserver implements DataChannel.Observer {
        
        @Override
        public void onStateChange() {
        Log.i(TAG, "DC onStateChange: " + dataChannel.state() + " (OPEN means ready to receive frames)");
        }
        @Override
        public void onMessage(DataChannel.Buffer buffer) {
            if (buffer == null || buffer.data == null) {
                Log.w(TAG, "DC onMessage: buffer/data is null");
                return;
            }
            ByteBuffer packet = buffer.data;
            int total = packet.remaining();
            if (total < 12) {
                Log.w(TAG, "DC onMessage: packet too small=" + total);
                return;
            }
            packet.order(ByteOrder.BIG_ENDIAN);
            long ptsUs = packet.getLong();
            int flags = packet.getInt();
            ByteBuffer payload = packet.slice();
            
        }
    }

    private static class SimpleSdpObserver implements SdpObserver {
        private final String tag;
        SimpleSdpObserver(String tag) { this.tag = tag; }
        @Override public void onCreateSuccess(SessionDescription sessionDescription) { Log.d(TAG, tag + " onCreateSuccess"); }
        @Override public void onSetSuccess() { Log.d(TAG, tag + " onSetSuccess"); }
        @Override public void onCreateFailure(String s) { Log.e(TAG, tag + " onCreateFailure: " + s); }
        @Override public void onSetFailure(String s) { Log.e(TAG, tag + " onSetFailure: " + s); }
    }
}
Logo

邀请您加入社区

更多推荐