WebRTC(TODO)

1 简介

只是简单学学。。。

简单看了下,貌似就是SIP的下一代。因为我对SIP很熟,所以就比对着来写。

传统的SIP

WebRTC

网络端

终端

2 树莓派的实现

代码

bash 复制代码
webrtc-pi/
├── server.py
├── static/
│   └── client.html

server.py

python 复制代码
import cv2
import asyncio
from aiortc import MediaStreamTrack, RTCPeerConnection, RTCSessionDescription
from aiortc.contrib.media import MediaRelay
from flask import Flask, render_template, request, jsonify, send_from_directory
import json

app = Flask(__name__, static_url_path='')

pcs = set()
relay = MediaRelay()

# 视频采集轨道(OpenCV)
class VideoTrack(MediaStreamTrack):
    kind = "video"

    def __init__(self):
        super().__init__()
        self.cap = cv2.VideoCapture(0)

    async def recv(self):
        pts, time_base = await self.next_timestamp()
        ret, frame = self.cap.read()
        if not ret:
            return None
        # 关键:OpenCV 转 RGB
        frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
        from av import VideoFrame
        video_frame = VideoFrame.from_ndarray(frame, format="rgb24")
        video_frame.pts = pts
        video_frame.time_base = time_base
        return video_frame

@app.route('/')
def index():
    return send_from_directory('static', 'client.html')

@app.route('/offer', methods=['POST'])
def offer():
    offer_sdp = request.get_json()
    pc = RTCPeerConnection()
    pcs.add(pc)

    video = VideoTrack()
    pc.addTrack(video)

    async def create_answer():
        await pc.setRemoteDescription(RTCSessionDescription(**offer_sdp))
        answer = await pc.createAnswer()
        await pc.setLocalDescription(answer)
        return pc.localDescription

    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)
    desc = loop.run_until_complete(create_answer())
    return jsonify({'sdp': desc.sdp, 'type': desc.type})

@app.route('/answer', methods=['POST'])
def answer():
    return "OK"

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000)

client.html

html 复制代码
<!DOCTYPE html>
<html>
<head>
  <title>Raspberry Pi WebRTC Camera</title>
</head>
<body>
  <h2>WebRTC Camera Stream</h2>
  <video id="video" autoplay playsinline controls></video>
  <script>
    const pc = new RTCPeerConnection();
    const video = document.getElementById("video");

    pc.ontrack = function (event) {
      video.srcObject = event.streams[0];
    };

    fetch("/offer", { method: "POST" })
      .then(res => res.json())
      .then(async ({ sdp, type }) => {
        await pc.setRemoteDescription({ sdp, type });
        const answer = await pc.createAnswer();
        await pc.setLocalDescription(answer);

        fetch("/answer", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify(pc.localDescription),
        });
      });
  </script>
</body>
</html>

TODO

相关推荐
EasyDSS20 小时前
基于WebRTC的视频会议系统:私有化视频会议平台EasyDSS视频会议到底能干什么
音视频·webrtc·easydss
福大大架构师每日一题4 天前
RustDesk 1.5.0发布:WebRTC、HDR 色调映射、剪贴板同步与百余项修复全面汇总
webrtc
福大大架构师每日一题9 天前
webrtc-rs/webrtc v0.21.0发布:API 可扩展、异步集成、确定性时间、ICE 重启与 SCTP 全面修复
webrtc
智联视频超融合平台9 天前
WebRTC + AI:实时音视频中嵌入神经网络推理的架构设计
人工智能·webrtc·实时音视频
P1Browser10 天前
换了 IP 还是被关联:WebRTC 泄露本地 IP 的三种触发路径
网络协议·tcp/ip·webrtc
福大大架构师每日一题11 天前
pion/webrtc v4.2.22 最新发布:TCP mux 写缓冲区调整至 4 MB,补齐缺失媒体方向处理
tcp/ip·webrtc·媒体
程序员老陆20 天前
WHIP 与 WHEP:WebRTC 直播的标准化入口与出口
ffmpeg·音视频·webrtc·whip·whep
平行云1 个月前
国产GPU云渲染适配实战:驱动兼容、编码调优与多路并发
unity·ue5·webrtc·webgl·实时云渲染·云桌面·像素流送
隐擎fox1 个月前
网络传输安全剖析:WebRTC 本地真实 IP 泄漏机制(STUN/TURN)与 Python 防护检测实战
网络·网络协议·tcp/ip·安全·webrtc
福大大架构师每日一题1 个月前
mediamtx v1.21.0 发布:Media-over-QUIC、RTSP、HLS、WebRTC 与安全能力全面升级
安全·webrtc