257 lines
6.9 KiB
TypeScript
257 lines
6.9 KiB
TypeScript
/**
|
||
* SRS 流媒体服务
|
||
* 处理 SRS 服务器认证和 WebRTC WHEP 视频流播放
|
||
*/
|
||
|
||
// SRS 服务器配置
|
||
const SRS_CONFIG = {
|
||
// 开发环境通过代理访问,生产环境直接访问
|
||
baseUrl: process.env.NODE_ENV === 'development' ? '' : 'http://220.205.16.27:8024',
|
||
// 登录密码
|
||
password: 'a6949674ed817fa3',
|
||
};
|
||
|
||
// 存储 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
|
||
const pc = new RTCPeerConnection();
|
||
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);
|
||
// 开发环境使用代理路径,生产环境使用完整 URL
|
||
const actualUrl = process.env.NODE_ENV === 'development'
|
||
? `${urlObj.pathname}${urlObj.search}` // 只使用路径和查询参数,通过代理访问
|
||
: whepUrl;
|
||
|
||
// 确保已登录
|
||
const token = await srsApi.getToken();
|
||
|
||
// 创建 RTCPeerConnection
|
||
const pc = new RTCPeerConnection();
|
||
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();
|
||
}
|
||
},
|
||
};
|