use-rtc-ws.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495
  1. import { getRandomString } from 'billd-utils';
  2. import { computed, onUnmounted, ref, watch } from 'vue';
  3. import { fetchRtcV1Publish } from '@/api/srs';
  4. import { WEBSOCKET_URL } from '@/constant';
  5. import {
  6. DanmuMsgTypeEnum,
  7. IDanmu,
  8. ILiveRoom,
  9. ILiveUser,
  10. IUser,
  11. LiveRoomTypeEnum,
  12. } from '@/interface';
  13. import {
  14. WSGetRoomAllUserType,
  15. WsGetLiveUserType,
  16. WsHeartbeatType,
  17. WsJoinType,
  18. WsLeavedType,
  19. WsMessageType,
  20. WsOtherJoinType,
  21. WsRoomLivingType,
  22. WsStartLiveType,
  23. WsUpdateJoinInfoType,
  24. } from '@/interface-ws';
  25. import { WebRTCClass } from '@/network/webRTC';
  26. import {
  27. WebSocketClass,
  28. WsConnectStatusEnum,
  29. WsMsgTypeEnum,
  30. prettierReceiveWsMsg,
  31. } from '@/network/webSocket';
  32. import { AppRootState, useAppStore } from '@/store/app';
  33. import { useNetworkStore } from '@/store/network';
  34. import { useUserStore } from '@/store/user';
  35. import { createVideo } from '@/utils';
  36. import { useRTCParams } from './use-rtc-params';
  37. export const useRtcWs = () => {
  38. const appStore = useAppStore();
  39. const userStore = useUserStore();
  40. const networkStore = useNetworkStore();
  41. const loopHeartbeatTimer = ref();
  42. const liveUserList = ref<ILiveUser[]>([]);
  43. const roomId = ref('');
  44. const roomLiving = ref(false);
  45. const liveRoomInfo = ref<ILiveRoom>();
  46. const anchorInfo = ref<IUser>();
  47. const isAnchor = ref(false);
  48. const localStream = ref<MediaStream>();
  49. const canvasVideoStream = ref<MediaStream>();
  50. const lastCoverImg = ref('');
  51. const { maxBitrate, maxFramerate, resolutionRatio } = useRTCParams();
  52. const currentMaxBitrate = ref(maxBitrate.value[2].value);
  53. const currentResolutionRatio = ref(resolutionRatio.value[3].value);
  54. const currentMaxFramerate = ref(maxFramerate.value[2].value);
  55. const damuList = ref<IDanmu[]>([]);
  56. watch(
  57. () => appStore.allTrack,
  58. (newTrack, oldTrack) => {
  59. console.log('appStore.allTrack变了', newTrack, oldTrack);
  60. const mixedStream = new MediaStream();
  61. newTrack.forEach((item) => {
  62. if (item.track) {
  63. mixedStream.addTrack(item.track);
  64. }
  65. });
  66. console.log('新的allTrack音频轨', mixedStream.getAudioTracks());
  67. console.log('新的allTrack视频轨', mixedStream.getVideoTracks());
  68. console.log('旧的allTrack音频轨', localStream.value?.getAudioTracks());
  69. console.log('旧的allTrack视频轨', localStream.value?.getVideoTracks());
  70. localStream.value = mixedStream;
  71. },
  72. { deep: true }
  73. );
  74. onUnmounted(() => {
  75. clearInterval(loopHeartbeatTimer.value);
  76. });
  77. watch(
  78. () => currentResolutionRatio.value,
  79. (newVal) => {
  80. if (canvasVideoStream.value) {
  81. canvasVideoStream.value.getVideoTracks().forEach((track) => {
  82. track.applyConstraints({
  83. frameRate: { max: currentMaxFramerate.value },
  84. height: newVal,
  85. });
  86. });
  87. } else {
  88. appStore.allTrack.forEach((info) => {
  89. info.track?.applyConstraints({
  90. frameRate: { max: currentMaxFramerate.value },
  91. height: newVal,
  92. });
  93. });
  94. }
  95. networkStore.rtcMap.forEach(async (rtc) => {
  96. const res = await rtc.setResolutionRatio(newVal);
  97. if (res === 1) {
  98. window.$message.success('切换分辨率成功!');
  99. } else {
  100. window.$message.success('切换分辨率失败!');
  101. }
  102. });
  103. }
  104. );
  105. watch(
  106. () => currentMaxFramerate.value,
  107. (newVal) => {
  108. console.log(currentMaxFramerate.value, 'currentMaxFramerate.value');
  109. if (canvasVideoStream.value) {
  110. canvasVideoStream.value.getVideoTracks().forEach((track) => {
  111. track.applyConstraints({
  112. frameRate: { max: newVal },
  113. height: currentResolutionRatio.value,
  114. });
  115. });
  116. } else {
  117. appStore.allTrack.forEach((info) => {
  118. info.track?.applyConstraints({
  119. frameRate: { max: newVal },
  120. height: currentResolutionRatio.value,
  121. });
  122. });
  123. }
  124. networkStore.rtcMap.forEach(async (rtc) => {
  125. const res = await rtc.setMaxFramerate(newVal);
  126. if (res === 1) {
  127. window.$message.success('切换帧率成功!');
  128. } else {
  129. window.$message.success('切换帧率失败!');
  130. }
  131. });
  132. }
  133. );
  134. watch(
  135. () => currentMaxBitrate.value,
  136. (newVal) => {
  137. networkStore.rtcMap.forEach(async (rtc) => {
  138. const res = await rtc.setMaxBitrate(newVal);
  139. if (res === 1) {
  140. window.$message.success('切换码率成功!');
  141. } else {
  142. window.$message.success('切换码率失败!');
  143. }
  144. });
  145. }
  146. );
  147. function addTrack(addTrackInfo: { track; stream }) {
  148. if (isAnchor.value) {
  149. networkStore.rtcMap.forEach((rtc) => {
  150. const sender = rtc.peerConnection
  151. ?.getSenders()
  152. .find((sender) => sender.track?.id === addTrackInfo.track?.id);
  153. if (!sender) {
  154. console.log('pc添加track-开播后中途添加', addTrackInfo.track?.id);
  155. rtc.peerConnection
  156. ?.getSenders()
  157. ?.find((sender) => sender.track?.kind === 'audio')
  158. ?.replaceTrack(canvasVideoStream.value!.getAudioTracks()[0]);
  159. const vel = createVideo({});
  160. vel.srcObject = canvasVideoStream.value!;
  161. }
  162. });
  163. }
  164. const mixedStream = new MediaStream();
  165. appStore.allTrack.forEach((item) => {
  166. if (item.track) {
  167. mixedStream.addTrack(item.track);
  168. }
  169. });
  170. console.log('addTrack后结果的音频轨', mixedStream.getAudioTracks());
  171. console.log('addTrack后结果的视频轨', mixedStream.getVideoTracks());
  172. localStream.value = mixedStream;
  173. }
  174. function delTrack(delTrackInfo: AppRootState['allTrack'][0]) {
  175. if (isAnchor.value) {
  176. networkStore.rtcMap.forEach((rtc) => {
  177. const sender = rtc.peerConnection
  178. ?.getSenders()
  179. .find((sender) => sender.track?.id === delTrackInfo.track?.id);
  180. if (sender) {
  181. console.log('删除track', delTrackInfo, sender);
  182. rtc.peerConnection?.removeTrack(sender);
  183. }
  184. });
  185. }
  186. const mixedStream = new MediaStream();
  187. appStore.allTrack.forEach((item) => {
  188. if (item.track) {
  189. mixedStream.addTrack(item.track);
  190. }
  191. });
  192. console.log('delTrack后结果的音频轨', mixedStream.getAudioTracks());
  193. console.log('delTrack后结果的视频轨', mixedStream.getVideoTracks());
  194. localStream.value = mixedStream;
  195. }
  196. const mySocketId = computed(() => {
  197. return networkStore.wsMap.get(roomId.value)?.socketIo?.id || '-1';
  198. });
  199. function handleHeartbeat(socketId: string) {
  200. loopHeartbeatTimer.value = setInterval(() => {
  201. const ws = networkStore.wsMap.get(roomId.value);
  202. if (!ws) return;
  203. ws.send<WsHeartbeatType['data']>({
  204. msgType: WsMsgTypeEnum.heartbeat,
  205. data: {
  206. socket_id: socketId,
  207. },
  208. });
  209. }, 1000 * 5);
  210. }
  211. async function sendOffer({ receiver }: { receiver: string }) {
  212. console.log('开始sendOffer');
  213. const ws = networkStore.wsMap.get(roomId.value);
  214. if (!ws) return;
  215. const rtc = networkStore.getRtcMap(`${roomId.value}___${receiver}`);
  216. if (!rtc) return;
  217. const sdp = await rtc.createOffer();
  218. await rtc.setLocalDescription(sdp!);
  219. const myLiveRoom = userStore.userInfo!.live_rooms![0];
  220. const res = await fetchRtcV1Publish({
  221. api: `/rtc/v1/publish/`,
  222. clientip: null,
  223. sdp: sdp!.sdp!,
  224. streamurl: `${myLiveRoom.rtmp_url!}?token=${myLiveRoom.key!}&type=${
  225. LiveRoomTypeEnum.user_srs
  226. }`,
  227. tid: getRandomString(10),
  228. });
  229. networkStore.wsMap.get(roomId.value)?.send<WsUpdateJoinInfoType['data']>({
  230. msgType: WsMsgTypeEnum.updateJoinInfo,
  231. data: {
  232. live_room_id: Number(roomId.value),
  233. track: {
  234. audio: 1,
  235. video: 1,
  236. },
  237. },
  238. });
  239. if (res.data.code !== 0) {
  240. console.error('/rtc/v1/publish/拿不到sdp');
  241. window.$message.error('/rtc/v1/publish/拿不到sdp');
  242. return;
  243. }
  244. await rtc.setRemoteDescription(
  245. new RTCSessionDescription({ type: 'answer', sdp: res.data.sdp })
  246. );
  247. }
  248. function handleStartLive({ coverImg, name }) {
  249. networkStore.wsMap.get(roomId.value)?.send<WsStartLiveType['data']>({
  250. msgType: WsMsgTypeEnum.startLive,
  251. data: {
  252. cover_img: coverImg,
  253. name,
  254. type: LiveRoomTypeEnum.user_srs,
  255. },
  256. });
  257. startNewSrsWebRtc({
  258. videoEl: document.createElement('video'),
  259. receiver: 'srs',
  260. });
  261. }
  262. function sendJoin() {
  263. const instance = networkStore.wsMap.get(roomId.value);
  264. if (!instance) return;
  265. instance.send<WsJoinType['data']>({
  266. msgType: WsMsgTypeEnum.join,
  267. data: {
  268. socket_id: mySocketId.value,
  269. live_room: {
  270. id: Number(roomId.value),
  271. },
  272. user_info: userStore.userInfo,
  273. },
  274. });
  275. }
  276. /** 原生的webrtc时,receiver必传 */
  277. function startNewSrsWebRtc({
  278. receiver,
  279. videoEl,
  280. }: {
  281. receiver: string;
  282. videoEl: HTMLVideoElement;
  283. }) {
  284. console.warn('SRS开始new WebRTCClass', `${roomId.value}___${receiver!}`);
  285. const rtc = new WebRTCClass({
  286. maxBitrate: currentMaxBitrate.value,
  287. maxFramerate: currentMaxFramerate.value,
  288. resolutionRatio: currentResolutionRatio.value,
  289. roomId: `${roomId.value}___${receiver!}`,
  290. videoEl,
  291. isSRS: true,
  292. receiver,
  293. });
  294. if (canvasVideoStream.value) {
  295. localStream.value = canvasVideoStream.value;
  296. rtc.localStream = canvasVideoStream.value;
  297. canvasVideoStream.value.getTracks().forEach((track) => {
  298. console.log('pc添加track-srs', track.kind, track.id);
  299. rtc.peerConnection?.addTrack(track, localStream.value!);
  300. });
  301. }
  302. sendOffer({
  303. receiver,
  304. });
  305. }
  306. function initReceive() {
  307. const ws = networkStore.wsMap.get(roomId.value);
  308. if (!ws?.socketIo) return;
  309. // websocket连接成功
  310. ws.socketIo.on(WsConnectStatusEnum.connect, () => {
  311. prettierReceiveWsMsg(WsConnectStatusEnum.connect, ws.socketIo);
  312. handleHeartbeat(ws.socketIo!.id);
  313. if (!ws) return;
  314. ws.status = WsConnectStatusEnum.connect;
  315. ws.update();
  316. sendJoin();
  317. });
  318. // websocket连接断开
  319. ws.socketIo.on(WsConnectStatusEnum.disconnect, () => {
  320. prettierReceiveWsMsg(WsConnectStatusEnum.disconnect, ws);
  321. if (!ws) return;
  322. ws.status = WsConnectStatusEnum.disconnect;
  323. ws.update();
  324. });
  325. // 主播正在直播
  326. ws.socketIo.on(WsMsgTypeEnum.roomLiving, (data: WsRoomLivingType) => {
  327. prettierReceiveWsMsg(WsMsgTypeEnum.roomLiving, data);
  328. roomLiving.value = true;
  329. });
  330. // 主播不在直播
  331. ws.socketIo.on(WsMsgTypeEnum.roomNoLive, (data) => {
  332. prettierReceiveWsMsg(WsMsgTypeEnum.roomNoLive, data);
  333. roomLiving.value = false;
  334. });
  335. // 当前所有在线用户
  336. ws.socketIo.on(
  337. WsMsgTypeEnum.liveUser,
  338. (data: WSGetRoomAllUserType['data']) => {
  339. prettierReceiveWsMsg(WsMsgTypeEnum.liveUser, data);
  340. const res = data.liveUser.map((item) => {
  341. return {
  342. id: item.id,
  343. // userInfo: item.id,
  344. };
  345. });
  346. liveUserList.value = res;
  347. }
  348. );
  349. // 收到用户发送消息
  350. ws.socketIo.on(WsMsgTypeEnum.message, (data: WsMessageType) => {
  351. prettierReceiveWsMsg(WsMsgTypeEnum.message, data);
  352. damuList.value.push({
  353. socket_id: data.socket_id,
  354. msgType: DanmuMsgTypeEnum.danmu,
  355. msg: data.data.msg,
  356. userInfo: data.user_info,
  357. });
  358. });
  359. // 用户加入房间完成
  360. ws.socketIo.on(WsMsgTypeEnum.joined, (data: WsJoinType['data']) => {
  361. prettierReceiveWsMsg(WsMsgTypeEnum.joined, data);
  362. liveUserList.value.push({
  363. id: data.socket_id,
  364. userInfo: data.user_info,
  365. });
  366. liveRoomInfo.value = data.live_room;
  367. anchorInfo.value = data.anchor_info;
  368. ws.send<WsGetLiveUserType['data']>({
  369. msgType: WsMsgTypeEnum.getLiveUser,
  370. data: {
  371. live_room_id: data.live_room.id!,
  372. },
  373. });
  374. });
  375. // 其他用户加入房间
  376. ws.socketIo.on(WsMsgTypeEnum.otherJoin, (data: WsOtherJoinType['data']) => {
  377. prettierReceiveWsMsg(WsMsgTypeEnum.otherJoin, data);
  378. liveUserList.value.push({
  379. id: data.join_socket_id,
  380. userInfo: data.join_user_info,
  381. });
  382. const danmu: IDanmu = {
  383. msgType: DanmuMsgTypeEnum.otherJoin,
  384. socket_id: data.join_socket_id,
  385. userInfo: data.join_user_info,
  386. msg: '',
  387. };
  388. damuList.value.push(danmu);
  389. ws.send<WsGetLiveUserType['data']>({
  390. msgType: WsMsgTypeEnum.getLiveUser,
  391. data: {
  392. live_room_id: data.live_room.id!,
  393. },
  394. });
  395. });
  396. // 用户离开房间
  397. ws.socketIo.on(WsMsgTypeEnum.leave, (data) => {
  398. prettierReceiveWsMsg(WsMsgTypeEnum.leave, data);
  399. });
  400. // 用户离开房间完成
  401. ws.socketIo.on(WsMsgTypeEnum.leaved, (data: WsLeavedType['data']) => {
  402. prettierReceiveWsMsg(WsMsgTypeEnum.leaved, data);
  403. networkStore.rtcMap
  404. .get(`${roomId.value}___${data.socket_id as string}`)
  405. ?.close();
  406. networkStore.removeRtc(`${roomId.value}___${data.socket_id as string}`);
  407. const res = liveUserList.value.filter(
  408. (item) => item.id !== data.socket_id
  409. );
  410. liveUserList.value = res;
  411. damuList.value.push({
  412. socket_id: data.socket_id,
  413. msgType: DanmuMsgTypeEnum.userLeaved,
  414. userInfo: data.user_info,
  415. msg: '',
  416. });
  417. });
  418. }
  419. function initSrsWs(data: {
  420. isAnchor: boolean;
  421. roomId: string;
  422. currentResolutionRatio?: number;
  423. currentMaxFramerate?: number;
  424. currentMaxBitrate?: number;
  425. }) {
  426. roomId.value = data.roomId;
  427. isAnchor.value = data.isAnchor;
  428. if (data.currentMaxBitrate) {
  429. currentMaxBitrate.value = data.currentMaxBitrate;
  430. }
  431. if (data.currentMaxFramerate) {
  432. currentMaxFramerate.value = data.currentMaxFramerate;
  433. }
  434. if (data.currentResolutionRatio) {
  435. currentResolutionRatio.value = data.currentResolutionRatio;
  436. }
  437. new WebSocketClass({
  438. roomId: roomId.value,
  439. url: WEBSOCKET_URL,
  440. isAnchor: data.isAnchor,
  441. });
  442. initReceive();
  443. }
  444. return {
  445. initSrsWs,
  446. addTrack,
  447. delTrack,
  448. handleStartLive,
  449. mySocketId,
  450. canvasVideoStream,
  451. lastCoverImg,
  452. roomLiving,
  453. liveRoomInfo,
  454. anchorInfo,
  455. localStream,
  456. liveUserList,
  457. damuList,
  458. currentMaxFramerate,
  459. currentMaxBitrate,
  460. currentResolutionRatio,
  461. };
  462. };