275 lines
7.4 KiB
TypeScript
275 lines
7.4 KiB
TypeScript
/**
|
||||
|
|
* SRS 流媒体服务
|
|||
|
|
* 处理 SRS 服务器认证和 WebRTC WHEP 视频流播放
|
|||
|
|
*/
|
|||
|
|
|
|||
|
|
// SRS 服务器配置
|
|||
|
|
const SRS_CONFIG = {
|
|||
|
|
// 所有环境都通过代理访问,避免跨域问题
|
|||
|
|
// 开发环境: webpack devServer 代理
|
|||
|
|
// 测试/生产环境: nginx 代理
|
|||
|
|
baseUrl: '',
|
|||
|
|
// 登录密码
|
|||
|
|
password: 'a6949674ed817fa3',
|
|||
|
|
};
|
|||
|
|
|
|||
|
|
// WebRTC ICE 服务器配置(用于 NAT 穿透)
|
|||
|
|
// 必须与 SRS 服务器配置的 STUN/TURN 一致
|
|||
|
|
const ICE_SERVERS: RTCConfiguration = {
|
|||
|
|
iceServers: [
|
|||
|
|
// 自建 STUN 服务器
|
|||
|
|
{ urls: 'stun:220.205.16.27:3478' },
|
|||
|
|
// 自建 TURN 服务器(用于复杂 NAT 环境)
|
|||
|
|
{
|
|||
|
|
urls: 'turn:220.205.16.27:3478?transport=udp',
|
|||
|
|
username: 'webrtc',
|
|||
|
|
credential: 'GoFly@2024',
|
|||
|
|
},
|
|||
|
|
// 备用 Google STUN(可选)
|
|||
|
|
{ urls: 'stun:stun.l.google.com:19302' },
|
|||
|
|
],
|
|||
|
|
iceCandidatePoolSize: 10,
|
|||
|
|
};
|
|||
|
|
|
|||
|
|
// 存储 token
|
|||
|
|
let srsToken: string | null = null;
|
|||
|
|
let tokenExpireTime: number = 0;
|
|||
|
|
|
|||
|
|
export interface SrsLoginResponse {
|
|||
|
|
code: number;
|
|||
|
|
data?: {
|
|||
|
|
token: string;
|
|||
|
|
[key: string]: any;
|
|||
|
|
};
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
export const srsApi = {
|
|||
|
|
/**
|
|||
|
|
* 登录 SRS 服务器获取 token
|
|||
|
|
* @param password 登录密码
|
|||
|
|
*/
|
|||
|
|
login: async (password?: string): Promise<{ success: boolean; token?: string; error?: string }> => {
|
|||
|
|
try {
|
|||
|
|
const response = await fetch(`${SRS_CONFIG.baseUrl}/terraform/v1/mgmt/login`, {
|
|||
|
|
method: 'POST',
|
|||
|
|
headers: {
|
|||
|
|
'Content-Type': 'application/json',
|
|||
|
|
},
|
|||
|
|
body: JSON.stringify({ password: password || SRS_CONFIG.password }),
|
|||
|
|
credentials: 'include', // 重要:携带 cookie
|
|||
|
|
});
|
|||
|
|
|
|||
|
|
if (!response.ok) {
|
|||
|
|
return { success: false, error: `HTTP ${response.status}` };
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
const data = await response.json();
|
|||
|
|
|
|||
|
|
if (data.code === 0 && data.data?.token) {
|
|||
|
|
srsToken = data.data.token;
|
|||
|
|
// token 有效期设为 1 小时
|
|||
|
|
tokenExpireTime = Date.now() + 3600 * 1000;
|
|||
|
|
return { success: true, token: data.data.token };
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
return { success: false, error: data.msg || '登录失败' };
|
|||
|
|
} catch (error: any) {
|
|||
|
|
return { success: false, error: error.message };
|
|||
|
|
}
|
|||
|
|
},
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* 获取当前 token(如果过期则重新登录)
|
|||
|
|
*/
|
|||
|
|
getToken: async (): Promise<string | null> => {
|
|||
|
|
// 检查 token 是否有效
|
|||
|
|
if (srsToken && Date.now() < tokenExpireTime) {
|
|||
|
|
return srsToken;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// 重新登录获取 token
|
|||
|
|
const result = await srsApi.login();
|
|||
|
|
return result.success ? result.token || null : null;
|
|||
|
|
},
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* 检查是否已登录
|
|||
|
|
*/
|
|||
|
|
isLoggedIn: (): boolean => {
|
|||
|
|
return !!srsToken && Date.now() < tokenExpireTime;
|
|||
|
|
},
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* 构建 WHEP 播放 URL
|
|||
|
|
* @param streamId 流ID(如 49214ac552fa)
|
|||
|
|
* @param app 应用名称(默认 live)
|
|||
|
|
*/
|
|||
|
|
buildWhepUrl: (streamId: string, app: string = 'live'): string => {
|
|||
|
|
return `${SRS_CONFIG.baseUrl}/rtc/v1/whep/?app=${app}&stream=${streamId}`;
|
|||
|
|
},
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* 使用 WHEP 协议播放 WebRTC 视频流
|
|||
|
|
* @param streamId 流ID
|
|||
|
|
* @param videoElement video 元素
|
|||
|
|
* @param options 选项
|
|||
|
|
*/
|
|||
|
|
playWhep: async (
|
|||
|
|
streamId: string,
|
|||
|
|
videoElement: HTMLVideoElement,
|
|||
|
|
options?: { app?: string; videoOnly?: boolean; audioOnly?: boolean }
|
|||
|
|
): Promise<{
|
|||
|
|
success: boolean;
|
|||
|
|
pc?: RTCPeerConnection;
|
|||
|
|
stream?: MediaStream;
|
|||
|
|
error?: string;
|
|||
|
|
}> => {
|
|||
|
|
try {
|
|||
|
|
// 确保已登录
|
|||
|
|
const token = await srsApi.getToken();
|
|||
|
|
if (!token) {
|
|||
|
|
return { success: false, error: 'SRS 认证失败,请检查密码' };
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
const url = srsApi.buildWhepUrl(streamId, options?.app);
|
|||
|
|
|
|||
|
|
// 创建 RTCPeerConnection(配置 ICE 服务器用于 NAT 穿透)
|
|||
|
|
const pc = new RTCPeerConnection(ICE_SERVERS);
|
|||
|
|
const stream = new MediaStream();
|
|||
|
|
|
|||
|
|
// 设置接收音视频轨道
|
|||
|
|
if (!options?.videoOnly) {
|
|||
|
|
pc.addTransceiver('audio', { direction: 'recvonly' });
|
|||
|
|
}
|
|||
|
|
if (!options?.audioOnly) {
|
|||
|
|
pc.addTransceiver('video', { direction: 'recvonly' });
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// 监听远端轨道
|
|||
|
|
pc.ontrack = (event) => {
|
|||
|
|
stream.addTrack(event.track);
|
|||
|
|
videoElement.srcObject = stream;
|
|||
|
|
};
|
|||
|
|
|
|||
|
|
// 创建 offer
|
|||
|
|
const offer = await pc.createOffer();
|
|||
|
|
await pc.setLocalDescription(offer);
|
|||
|
|
|
|||
|
|
// 发送 offer 到 WHEP 端点
|
|||
|
|
const response = await fetch(url, {
|
|||
|
|
method: 'POST',
|
|||
|
|
headers: {
|
|||
|
|
'Content-Type': 'application/sdp',
|
|||
|
|
},
|
|||
|
|
body: offer.sdp,
|
|||
|
|
credentials: 'include', // 携带 cookie
|
|||
|
|
});
|
|||
|
|
|
|||
|
|
if (!response.ok) {
|
|||
|
|
pc.close();
|
|||
|
|
return { success: false, error: `WHEP 请求失败: HTTP ${response.status}` };
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
const answerSdp = await response.text();
|
|||
|
|
|
|||
|
|
// 设置远端描述
|
|||
|
|
await pc.setRemoteDescription(new RTCSessionDescription({
|
|||
|
|
type: 'answer',
|
|||
|
|
sdp: answerSdp,
|
|||
|
|
}));
|
|||
|
|
|
|||
|
|
return { success: true, pc, stream };
|
|||
|
|
} catch (error: any) {
|
|||
|
|
return { success: false, error: error.message };
|
|||
|
|
}
|
|||
|
|
},
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* 使用完整 URL 播放 WHEP 视频流
|
|||
|
|
* @param whepUrl 完整的 WHEP URL(如:http://220.205.16.27:8024/rtc/v1/whep/?app=live&stream=xxx)
|
|||
|
|
* @param videoElement video 元素
|
|||
|
|
* @param options 选项
|
|||
|
|
*/
|
|||
|
|
playWhepByUrl: async (
|
|||
|
|
whepUrl: string,
|
|||
|
|
videoElement: HTMLVideoElement,
|
|||
|
|
options?: { videoOnly?: boolean; audioOnly?: boolean }
|
|||
|
|
): Promise<{
|
|||
|
|
success: boolean;
|
|||
|
|
pc?: RTCPeerConnection;
|
|||
|
|
stream?: MediaStream;
|
|||
|
|
error?: string;
|
|||
|
|
}> => {
|
|||
|
|
try {
|
|||
|
|
// 解析 URL,提取路径部分通过代理访问(避免跨域)
|
|||
|
|
const urlObj = new URL(whepUrl);
|
|||
|
|
// 所有环境都使用代理路径,避免跨域问题
|
|||
|
|
const actualUrl = `${urlObj.pathname}${urlObj.search}`;
|
|||
|
|
|
|||
|
|
// 确保已登录
|
|||
|
|
const token = await srsApi.getToken();
|
|||
|
|
|
|||
|
|
// 创建 RTCPeerConnection(配置 ICE 服务器用于 NAT 穿透)
|
|||
|
|
const pc = new RTCPeerConnection(ICE_SERVERS);
|
|||
|
|
const stream = new MediaStream();
|
|||
|
|
|
|||
|
|
// 设置接收音视频轨道
|
|||
|
|
if (!options?.videoOnly) {
|
|||
|
|
pc.addTransceiver('audio', { direction: 'recvonly' });
|
|||
|
|
}
|
|||
|
|
if (!options?.audioOnly) {
|
|||
|
|
pc.addTransceiver('video', { direction: 'recvonly' });
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// 监听远端轨道
|
|||
|
|
pc.ontrack = (event) => {
|
|||
|
|
stream.addTrack(event.track);
|
|||
|
|
videoElement.srcObject = stream;
|
|||
|
|
};
|
|||
|
|
|
|||
|
|
// 创建 offer
|
|||
|
|
const offer = await pc.createOffer();
|
|||
|
|
await pc.setLocalDescription(offer);
|
|||
|
|
|
|||
|
|
// 发送 offer 到 WHEP 端点
|
|||
|
|
const response = await fetch(actualUrl, {
|
|||
|
|
method: 'POST',
|
|||
|
|
headers: {
|
|||
|
|
'Content-Type': 'application/sdp',
|
|||
|
|
},
|
|||
|
|
body: offer.sdp,
|
|||
|
|
credentials: 'include', // 携带 cookie
|
|||
|
|
});
|
|||
|
|
|
|||
|
|
if (!response.ok) {
|
|||
|
|
pc.close();
|
|||
|
|
return { success: false, error: `WHEP 请求失败: HTTP ${response.status}` };
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
const answerSdp = await response.text();
|
|||
|
|
|
|||
|
|
// 设置远端描述
|
|||
|
|
await pc.setRemoteDescription(new RTCSessionDescription({
|
|||
|
|
type: 'answer',
|
|||
|
|
sdp: answerSdp,
|
|||
|
|
}));
|
|||
|
|
|
|||
|
|
return { success: true, pc, stream };
|
|||
|
|
} catch (error: any) {
|
|||
|
|
return { success: false, error: error.message };
|
|||
|
|
}
|
|||
|
|
},
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* 停止播放并清理资源
|
|||
|
|
*/
|
|||
|
|
stopPlay: (pc: RTCPeerConnection | null, stream: MediaStream | null) => {
|
|||
|
|
if (stream) {
|
|||
|
|
stream.getTracks().forEach(track => track.stop());
|
|||
|
|
}
|
|||
|
|
if (pc) {
|
|||
|
|
pc.close();
|
|||
|
|
}
|
|||
|
|
},
|
|||
|
|
};
|