Browse Source

feat: add WebRTC streaming support with player integration and UI enhancements

- Implement WebRTC player in VideoPlayer component with connection status handling
- Add new WebRTC streaming page with configuration options for go2rtc service
- Update router and layout to include WebRTC streaming menu item
- Enhance UI for better user experience during WebRTC playback and connection management
yb 2 weeks ago
parent
commit
f007920846
4 changed files with 598 additions and 2 deletions
  1. 155 2
      src/components/VideoPlayer.vue
  2. 4 0
      src/layout/index.vue
  3. 6 0
      src/router/index.ts
  4. 433 0
      src/views/demo/webrtc-stream.vue

+ 155 - 2
src/components/VideoPlayer.vue

@@ -10,6 +10,24 @@
       />
     </template>
 
+    <!-- WebRTC Player -->
+    <template v-else-if="playerType === 'webrtc'">
+      <video
+        ref="videoRef"
+        class="video-element"
+        :controls="controls"
+        :autoplay="autoplay"
+        :muted="muted"
+        playsinline
+      />
+      <!-- WebRTC 连接状态 -->
+      <div v-if="webrtcStatus !== 'connected'" class="webrtc-status">
+        <span v-if="webrtcStatus === 'connecting'" class="status-connecting">连接中...</span>
+        <span v-else-if="webrtcStatus === 'failed'" class="status-failed">连接失败</span>
+        <span v-else class="status-idle">等待连接</span>
+      </div>
+    </template>
+
     <!-- HLS.js Player -->
     <template v-else-if="playerType === 'hls'">
       <video
@@ -48,7 +66,7 @@ interface Props {
   src?: string // 视频源地址
   videoId?: string // Cloudflare Stream video ID
   customerDomain?: string // Cloudflare 自定义域名
-  playerType?: 'cloudflare' | 'hls' | 'native'
+  playerType?: 'cloudflare' | 'hls' | 'native' | 'webrtc'
   useIframe?: boolean // Cloudflare 是否使用 iframe
   controls?: boolean
   autoplay?: boolean
@@ -56,6 +74,9 @@ interface Props {
   loop?: boolean
   poster?: string
   preload?: 'auto' | 'metadata' | 'none'
+  // WebRTC 配置
+  go2rtcUrl?: string // go2rtc 服务地址,如 http://localhost:1984
+  streamName?: string // 流名称,如 camera1
 }
 
 const props = withDefaults(defineProps<Props>(), {
@@ -80,6 +101,8 @@ const wrapperRef = ref<HTMLElement>()
 const videoRef = ref<HTMLVideoElement>()
 
 let hlsInstance: any = null
+let peerConnection: RTCPeerConnection | null = null
+const webrtcStatus = ref<'idle' | 'connecting' | 'connected' | 'failed'>('idle')
 
 // Cloudflare Stream iframe URL
 const cloudflareIframeSrc = computed(() => {
@@ -164,6 +187,87 @@ function destroyHls() {
   }
 }
 
+// 初始化 WebRTC
+async function initWebRTC() {
+  if (!videoRef.value || !props.go2rtcUrl || !props.streamName) return
+
+  webrtcStatus.value = 'connecting'
+
+  try {
+    // 创建 RTCPeerConnection
+    peerConnection = new RTCPeerConnection({
+      iceServers: [{ urls: 'stun:stun.l.google.com:19302' }]
+    })
+
+    // 监听远程流
+    peerConnection.ontrack = (event) => {
+      if (videoRef.value && event.streams[0]) {
+        videoRef.value.srcObject = event.streams[0]
+        webrtcStatus.value = 'connected'
+        if (props.autoplay) {
+          videoRef.value.play()
+        }
+      }
+    }
+
+    // 监听连接状态
+    peerConnection.oniceconnectionstatechange = () => {
+      if (!peerConnection) return
+      const state = peerConnection.iceConnectionState
+      if (state === 'connected' || state === 'completed') {
+        webrtcStatus.value = 'connected'
+      } else if (state === 'failed' || state === 'disconnected') {
+        webrtcStatus.value = 'failed'
+        emit('error', { type: 'webrtc', message: `ICE connection ${state}` })
+      }
+    }
+
+    // 添加音视频收发器
+    peerConnection.addTransceiver('video', { direction: 'recvonly' })
+    peerConnection.addTransceiver('audio', { direction: 'recvonly' })
+
+    // 创建 Offer
+    const offer = await peerConnection.createOffer()
+    await peerConnection.setLocalDescription(offer)
+
+    // 发送 Offer 到 go2rtc 并获取 Answer
+    const apiUrl = `${props.go2rtcUrl}/api/webrtc?src=${encodeURIComponent(props.streamName)}`
+    const response = await fetch(apiUrl, {
+      method: 'POST',
+      headers: { 'Content-Type': 'application/sdp' },
+      body: offer.sdp
+    })
+
+    if (!response.ok) {
+      throw new Error(`go2rtc API 请求失败: ${response.status}`)
+    }
+
+    const answerSdp = await response.text()
+    await peerConnection.setRemoteDescription({
+      type: 'answer',
+      sdp: answerSdp
+    })
+
+    // 绑定视频事件
+    bindVideoEvents()
+  } catch (error) {
+    console.error('WebRTC 连接失败:', error)
+    webrtcStatus.value = 'failed'
+    emit('error', { type: 'webrtc', message: String(error) })
+  }
+}
+
+function destroyWebRTC() {
+  if (peerConnection) {
+    peerConnection.close()
+    peerConnection = null
+  }
+  webrtcStatus.value = 'idle'
+  if (videoRef.value) {
+    videoRef.value.srcObject = null
+  }
+}
+
 // 公开方法
 function play() {
   if (videoRef.value) {
@@ -216,6 +320,14 @@ function fullscreen() {
   }
 }
 
+// WebRTC 重连
+function reconnect() {
+  if (props.playerType === 'webrtc') {
+    destroyWebRTC()
+    initWebRTC()
+  }
+}
+
 defineExpose({
   play,
   pause,
@@ -223,7 +335,9 @@ defineExpose({
   setVolume,
   setMuted,
   screenshot,
-  fullscreen
+  fullscreen,
+  reconnect,
+  webrtcStatus
 })
 
 watch(
@@ -236,9 +350,22 @@ watch(
   }
 )
 
+// WebRTC 配置变化时重新连接
+watch(
+  [() => props.go2rtcUrl, () => props.streamName],
+  ([newUrl, newStream]) => {
+    if (props.playerType === 'webrtc' && newUrl && newStream) {
+      destroyWebRTC()
+      initWebRTC()
+    }
+  }
+)
+
 onMounted(() => {
   if (props.playerType === 'hls') {
     initHls()
+  } else if (props.playerType === 'webrtc') {
+    initWebRTC()
   } else if (props.playerType === 'native') {
     bindVideoEvents()
   }
@@ -246,6 +373,7 @@ onMounted(() => {
 
 onBeforeUnmount(() => {
   destroyHls()
+  destroyWebRTC()
 })
 </script>
 
@@ -269,4 +397,29 @@ onBeforeUnmount(() => {
 .video-element {
   object-fit: contain;
 }
+
+// WebRTC 连接状态
+.webrtc-status {
+  position: absolute;
+  top: 50%;
+  left: 50%;
+  transform: translate(-50%, -50%);
+  padding: 12px 24px;
+  border-radius: 8px;
+  background-color: rgba(0, 0, 0, 0.7);
+  color: #fff;
+  font-size: 14px;
+
+  .status-connecting {
+    color: #409eff;
+  }
+
+  .status-failed {
+    color: #f56c6c;
+  }
+
+  .status-idle {
+    color: #909399;
+  }
+}
 </style>

+ 4 - 0
src/layout/index.vue

@@ -52,6 +52,10 @@
             <el-icon><Film /></el-icon>
             <template #title>{{ t('测试视频') }}</template>
           </el-menu-item>
+          <el-menu-item index="/demo/webrtc-stream">
+            <el-icon><Connection /></el-icon>
+            <template #title>{{ t('WebRTC 流') }}</template>
+          </el-menu-item>
         </el-sub-menu>
 
         <el-sub-menu index="/stream">

+ 6 - 0
src/router/index.ts

@@ -115,6 +115,12 @@ const routes: RouteRecordRaw[] = [
         name: 'SampleVideos',
         component: () => import('@/views/demo/sample-videos.vue'),
         meta: { title: '测试视频', icon: 'Film' }
+      },
+      {
+        path: 'demo/webrtc-stream',
+        name: 'WebrtcStream',
+        component: () => import('@/views/demo/webrtc-stream.vue'),
+        meta: { title: 'WebRTC 流', icon: 'Connection' }
       }
     ]
   },

+ 433 - 0
src/views/demo/webrtc-stream.vue

@@ -0,0 +1,433 @@
+<template>
+  <div class="page-container">
+    <div class="page-header">
+      <span class="title">WebRTC 低延迟播放</span>
+      <el-tag type="success" size="small" style="margin-left: 10px">延迟 &lt; 2s</el-tag>
+    </div>
+
+    <!-- 配置区域 -->
+    <div class="config-section">
+      <el-form label-width="120px">
+        <el-form-item label="go2rtc 地址">
+          <el-input
+            v-model="config.go2rtcUrl"
+            placeholder="go2rtc 服务地址"
+            style="width: 400px"
+          >
+            <template #prepend>http://</template>
+          </el-input>
+          <el-text type="info" style="margin-left: 10px">默认端口 1984</el-text>
+        </el-form-item>
+        <el-form-item label="流名称">
+          <el-input v-model="config.streamName" placeholder="摄像头流名称,如 camera1" style="width: 300px" />
+        </el-form-item>
+        <el-form-item label="生成的 URL">
+          <el-input :value="generatedUrl" readonly style="width: 600px">
+            <template #append>
+              <el-button @click="copyUrl">复制</el-button>
+            </template>
+          </el-input>
+        </el-form-item>
+        <el-form-item>
+          <el-button type="primary" @click="startPlay">播放</el-button>
+          <el-button @click="handleReconnect">重连</el-button>
+          <el-button type="danger" @click="handleStop">停止</el-button>
+        </el-form-item>
+      </el-form>
+    </div>
+
+    <!-- 播放器区域 -->
+    <div class="player-section">
+      <div v-if="!isPlaying" class="player-placeholder">
+        <el-icon :size="60" color="#ddd"><VideoPlay /></el-icon>
+        <p>请配置 go2rtc 地址和流名称后点击播放</p>
+      </div>
+      <VideoPlayer
+        v-else
+        ref="playerRef"
+        player-type="webrtc"
+        :go2rtc-url="fullGo2rtcUrl"
+        :stream-name="config.streamName"
+        :autoplay="playConfig.autoplay"
+        :muted="playConfig.muted"
+        :controls="true"
+        @play="onPlay"
+        @pause="onPause"
+        @error="onError"
+      />
+    </div>
+
+    <!-- 播放控制 -->
+    <div class="control-section">
+      <el-space wrap>
+        <el-button type="primary" @click="handlePlay">播放</el-button>
+        <el-button @click="handlePause">暂停</el-button>
+        <el-button @click="handleScreenshot">截图</el-button>
+        <el-button @click="handleFullscreen">全屏</el-button>
+
+        <el-divider direction="vertical" />
+
+        <el-switch v-model="playConfig.muted" active-text="静音" inactive-text="有声" />
+        <el-switch v-model="playConfig.autoplay" active-text="自动播放" inactive-text="手动" />
+      </el-space>
+    </div>
+
+    <!-- 当前状态 -->
+    <div class="status-section">
+      <el-descriptions title="当前状态" :column="3" border>
+        <el-descriptions-item label="连接状态">
+          <el-tag :type="statusTagType">{{ statusText }}</el-tag>
+        </el-descriptions-item>
+        <el-descriptions-item label="go2rtc 地址">{{ fullGo2rtcUrl || '-' }}</el-descriptions-item>
+        <el-descriptions-item label="流名称">{{ config.streamName || '-' }}</el-descriptions-item>
+      </el-descriptions>
+    </div>
+
+    <!-- 说明区域 -->
+    <div class="info-section">
+      <el-collapse>
+        <el-collapse-item title="go2rtc 配置说明" name="1">
+          <div class="info-content">
+            <h4>1. 下载 go2rtc</h4>
+            <p>访问 <el-link type="primary" href="https://github.com/AlexxIT/go2rtc/releases" target="_blank">GitHub Releases</el-link> 下载对应系统版本</p>
+
+            <h4>2. 创建配置文件 go2rtc.yaml</h4>
+            <pre class="code-block">streams:
+  camera1: rtsp://admin:password@192.168.0.64:554/Streaming/Channels/101
+
+webrtc:
+  candidates:
+    - stun:stun.l.google.com:19302</pre>
+
+            <h4>3. 启动服务</h4>
+            <pre class="code-block">./go2rtc -config go2rtc.yaml</pre>
+
+            <h4>4. 验证</h4>
+            <p>访问 <el-link type="primary" href="http://localhost:1984" target="_blank">http://localhost:1984</el-link> 查看管理界面</p>
+          </div>
+        </el-collapse-item>
+      </el-collapse>
+    </div>
+
+    <!-- 日志区域 -->
+    <div class="log-section">
+      <div class="log-header">
+        <h4>事件日志</h4>
+        <el-button size="small" @click="logs = []">清空</el-button>
+      </div>
+      <div class="log-content">
+        <div v-for="(log, index) in logs" :key="index" class="log-item" :class="log.type">
+          <span class="time">{{ log.time }}</span>
+          <span class="message">{{ log.message }}</span>
+        </div>
+        <div v-if="logs.length === 0" class="log-empty">暂无日志</div>
+      </div>
+    </div>
+  </div>
+</template>
+
+<script setup lang="ts">
+import { ref, reactive, computed } from 'vue'
+import { ElMessage } from 'element-plus'
+import { VideoPlay } from '@element-plus/icons-vue'
+import VideoPlayer from '@/components/VideoPlayer.vue'
+
+const playerRef = ref<InstanceType<typeof VideoPlayer>>()
+
+// 配置
+const config = reactive({
+  go2rtcUrl: 'localhost:1984',
+  streamName: 'camera1'
+})
+
+// 播放配置
+const playConfig = reactive({
+  autoplay: true,
+  muted: true
+})
+
+// 播放状态
+const isPlaying = ref(false)
+
+// 完整的 go2rtc URL
+const fullGo2rtcUrl = computed(() => {
+  if (!config.go2rtcUrl) return ''
+  const url = config.go2rtcUrl.startsWith('http') ? config.go2rtcUrl : `http://${config.go2rtcUrl}`
+  return url
+})
+
+// 生成的 WebRTC API URL
+const generatedUrl = computed(() => {
+  if (!fullGo2rtcUrl.value || !config.streamName) return ''
+  return `${fullGo2rtcUrl.value}/api/webrtc?src=${config.streamName}`
+})
+
+// 连接状态
+const connectionStatus = computed(() => {
+  return playerRef.value?.webrtcStatus?.value || 'idle'
+})
+
+const statusText = computed(() => {
+  const map: Record<string, string> = {
+    idle: '未连接',
+    connecting: '连接中',
+    connected: '已连接',
+    failed: '连接失败'
+  }
+  return map[connectionStatus.value] || '未知'
+})
+
+const statusTagType = computed(() => {
+  const map: Record<string, '' | 'success' | 'warning' | 'danger' | 'info'> = {
+    idle: 'info',
+    connecting: 'warning',
+    connected: 'success',
+    failed: 'danger'
+  }
+  return map[connectionStatus.value] || 'info'
+})
+
+// 日志
+interface LogItem {
+  time: string
+  type: 'info' | 'success' | 'error'
+  message: string
+}
+const logs = ref<LogItem[]>([])
+
+function addLog(message: string, type: LogItem['type'] = 'info') {
+  const time = new Date().toLocaleTimeString()
+  logs.value.unshift({ time, type, message })
+  if (logs.value.length > 100) {
+    logs.value.pop()
+  }
+}
+
+// 开始播放
+function startPlay() {
+  if (!config.go2rtcUrl) {
+    ElMessage.warning('请输入 go2rtc 地址')
+    return
+  }
+  if (!config.streamName) {
+    ElMessage.warning('请输入流名称')
+    return
+  }
+  isPlaying.value = true
+  addLog(`开始 WebRTC 播放: ${config.streamName}`, 'success')
+}
+
+// 复制 URL
+function copyUrl() {
+  if (!generatedUrl.value) {
+    ElMessage.warning('请先配置 go2rtc 地址和流名称')
+    return
+  }
+  navigator.clipboard.writeText(generatedUrl.value)
+  ElMessage.success('已复制到剪贴板')
+}
+
+// 播放控制
+function handlePlay() {
+  playerRef.value?.play()
+  addLog('播放', 'info')
+}
+
+function handlePause() {
+  playerRef.value?.pause()
+  addLog('暂停', 'info')
+}
+
+function handleStop() {
+  isPlaying.value = false
+  addLog('停止播放', 'info')
+}
+
+function handleReconnect() {
+  playerRef.value?.reconnect()
+  addLog('重新连接', 'info')
+}
+
+function handleScreenshot() {
+  playerRef.value?.screenshot()
+  addLog('截图', 'info')
+}
+
+function handleFullscreen() {
+  playerRef.value?.fullscreen()
+  addLog('全屏', 'info')
+}
+
+// 事件处理
+function onPlay() {
+  addLog('视频开始播放', 'success')
+}
+
+function onPause() {
+  addLog('视频已暂停', 'info')
+}
+
+function onError(error: any) {
+  addLog(`播放错误: ${error?.message || JSON.stringify(error)}`, 'error')
+}
+</script>
+
+<style lang="scss" scoped>
+.page-container {
+  min-height: 100vh;
+  background-color: var(--bg-page);
+}
+
+.page-header {
+  display: flex;
+  align-items: center;
+  margin-bottom: 20px;
+  padding: 15px 20px;
+  background-color: var(--bg-container);
+  border-radius: var(--radius-base);
+  color: var(--text-primary);
+
+  .title {
+    font-size: 18px;
+    font-weight: 600;
+  }
+}
+
+.config-section {
+  margin-bottom: 20px;
+  padding: 20px;
+  background-color: var(--bg-container);
+  border-radius: var(--radius-base);
+}
+
+.player-section {
+  height: 500px;
+  margin-bottom: 20px;
+  border-radius: var(--radius-base);
+  overflow: hidden;
+  background-color: #000;
+
+  .player-placeholder {
+    height: 100%;
+    display: flex;
+    flex-direction: column;
+    align-items: center;
+    justify-content: center;
+    color: var(--text-secondary);
+
+    p {
+      margin-top: 15px;
+      font-size: 14px;
+    }
+  }
+}
+
+.control-section {
+  padding: 15px 20px;
+  background-color: var(--bg-container);
+  border-radius: var(--radius-base);
+  margin-bottom: 20px;
+}
+
+.status-section {
+  margin-bottom: 20px;
+  padding: 15px 20px;
+  background-color: var(--bg-container);
+  border-radius: var(--radius-base);
+}
+
+.info-section {
+  margin-bottom: 20px;
+  background-color: var(--bg-container);
+  border-radius: var(--radius-base);
+
+  .info-content {
+    padding: 10px 0;
+
+    h4 {
+      margin: 15px 0 8px;
+      color: var(--text-primary);
+      font-size: 14px;
+
+      &:first-child {
+        margin-top: 0;
+      }
+    }
+
+    p {
+      margin: 0;
+      color: var(--text-regular);
+      font-size: 13px;
+    }
+
+    .code-block {
+      background-color: var(--bg-hover);
+      padding: 12px;
+      border-radius: var(--radius-sm);
+      font-family: 'Monaco', 'Menlo', monospace;
+      font-size: 12px;
+      line-height: 1.6;
+      overflow-x: auto;
+      color: var(--text-primary);
+    }
+  }
+}
+
+.log-section {
+  padding: 15px 20px;
+  background-color: var(--bg-container);
+  border-radius: var(--radius-base);
+
+  .log-header {
+    display: flex;
+    justify-content: space-between;
+    align-items: center;
+    margin-bottom: 10px;
+
+    h4 {
+      font-size: 14px;
+      margin: 0;
+      color: var(--text-primary);
+    }
+  }
+
+  .log-content {
+    max-height: 200px;
+    overflow-y: auto;
+    background-color: var(--bg-hover);
+    border-radius: var(--radius-sm);
+    padding: 10px;
+  }
+
+  .log-item {
+    font-size: 12px;
+    padding: 4px 0;
+    border-bottom: 1px solid var(--border-color-light);
+    color: var(--text-regular);
+
+    &:last-child {
+      border-bottom: none;
+    }
+
+    .time {
+      color: var(--text-secondary);
+      margin-right: 10px;
+    }
+
+    &.success .message {
+      color: var(--color-success);
+    }
+
+    &.error .message {
+      color: var(--color-danger);
+    }
+  }
+
+  .log-empty {
+    text-align: center;
+    color: var(--text-secondary);
+    font-size: 12px;
+    padding: 20px 0;
+  }
+}
+</style>